@wirecat/cli-core 0.690.0 → 0.692.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.
@@ -0,0 +1,234 @@
1
+ import { DEAL_STATUSES } from "../../domain/deals.js";
2
+ import { amountOf, crmValuesOf, epoch, fullName, id, isRaw, text } from "../values.js";
3
+ /** The service sent nothing at this path: the field is left out, so the stored copy keeps what it held. */
4
+ export const MISSING = Symbol("missing");
5
+ /** A dotted path; a number steps into a list (`results.0.id`), and `.` is the value itself. */
6
+ export const at = (value, path) => path === "."
7
+ ? value
8
+ : path.split(".").reduce((inner, key) =>
9
+ // Past the end of a list the service sent is "none", not "not sent": a removed link must leave the copy.
10
+ Array.isArray(inner) && /^\d+$/.test(key)
11
+ ? (inner[Number(key)] ?? null)
12
+ : isRaw(inner)
13
+ ? inner[key]
14
+ : undefined, value);
15
+ const read = (raw, path) => {
16
+ const found = at(raw, path);
17
+ return found === undefined ? MISSING : found;
18
+ };
19
+ const listOf = (value) => (Array.isArray(value) ? value : value === null ? [] : [value]);
20
+ const reads = (raw, paths) => {
21
+ const found = paths.map((path) => read(raw, path)).filter((one) => one !== MISSING);
22
+ return found.length ? found : MISSING;
23
+ };
24
+ export const evaluate = (rule, raw) => {
25
+ if (typeof rule === "string")
26
+ return read(raw, rule);
27
+ if (typeof rule === "function") {
28
+ const found = rule(raw);
29
+ return found === undefined ? MISSING : found;
30
+ }
31
+ if ("value" in rule && !("each" in rule))
32
+ return rule.value;
33
+ if ("first" in rule) {
34
+ const found = reads(raw, rule.first);
35
+ return found === MISSING ? MISSING : (found.find((one) => text(one) !== null) ?? null);
36
+ }
37
+ if ("join" in rule) {
38
+ const found = reads(raw, rule.join);
39
+ return found === MISSING ? MISSING : fullName(...found);
40
+ }
41
+ if ("all" in rule) {
42
+ const found = reads(raw, rule.all);
43
+ if (found === MISSING)
44
+ return MISSING;
45
+ return found.flatMap((one) => (rule.split && typeof one === "string" ? one.split(rule.split) : listOf(one)));
46
+ }
47
+ if ("each" in rule) {
48
+ const found = read(raw, rule.each);
49
+ if (found === MISSING)
50
+ return MISSING;
51
+ if ("value" in rule)
52
+ return listOf(found).map((one) => at(one, rule.value));
53
+ const primary = rule.primary === undefined ? null : id(at(raw, rule.primary));
54
+ return listOf(found).map((one) => ({ id: at(one, rule.id), primary }));
55
+ }
56
+ const found = read(raw, rule.path);
57
+ if (found === MISSING)
58
+ return MISSING;
59
+ if ("map" in rule)
60
+ return Object.hasOwn(rule.map, String(found)) ? rule.map[String(found)] : null;
61
+ return rule.split && typeof found === "string" ? found.split(rule.split) : found;
62
+ };
63
+ /** A time as epoch ms: ISO, epoch seconds, or epoch ms as digits in a string (HubSpot sends both forms). */
64
+ const epochOf = (value) => typeof value === "string" && /^\d{10,16}$/.test(value.trim()) ? epoch(Number(value)) : epoch(value);
65
+ /** The day as the service wrote it: a time with an offset turned into UTC may fall on the day before. */
66
+ const dayOf = (value) => {
67
+ const written = /^(\d{4}-\d{2}-\d{2})/.exec(typeof value === "string" ? value.trim() : "")?.[1];
68
+ if (written)
69
+ return written;
70
+ const ms = epochOf(value);
71
+ return ms === null ? null : new Date(ms).toISOString().slice(0, 10);
72
+ };
73
+ const unique = (values) => [...new Set(values.filter((one) => one !== null))];
74
+ const yes = (value) => value === true || value === 1 || value === "1" || value === "true";
75
+ /** Links each once, the primary first: `primary` names it, else none is marked. */
76
+ const linksOf = (value) => {
77
+ const listed = listOf(value).map((one) => isRaw(one) && "id" in one ? { id: id(one.id), primary: id(one.primary) } : { id: id(one), primary: null });
78
+ const ids = unique(listed.map((one) => one.id));
79
+ const primary = listed.find((one) => one.primary !== null)?.primary ?? null;
80
+ const ordered = primary !== null && ids.includes(primary) ? [primary, ...ids.filter((one) => one !== primary)] : ids;
81
+ return ordered.map((externalId) => ({ externalId, primary: externalId === primary }));
82
+ };
83
+ const CONVERT = {
84
+ id,
85
+ text,
86
+ epoch: epochOf,
87
+ day: dayOf,
88
+ bool: yes,
89
+ texts: (value) => unique(listOf(value).map(text)),
90
+ ids: (value) => linksOf(value).map(({ externalId }) => externalId),
91
+ status: (value) => {
92
+ const found = text(value);
93
+ return DEAL_STATUSES.includes(found ?? "") ? found : null;
94
+ },
95
+ organizations: (value) => linksOf(value).map(({ externalId, primary }) => ({ externalId, ...(primary ? { primary } : {}) })),
96
+ people: (value) => linksOf(value).map(({ externalId, primary }) => ({
97
+ externalId,
98
+ role: "contact",
99
+ ...(primary ? { primary } : {}),
100
+ })),
101
+ };
102
+ const TIMES = { createdAt: "epoch", updatedAt: "epoch" };
103
+ const ITEM = {
104
+ externalId: "id",
105
+ title: "text",
106
+ pipeline: "text",
107
+ stage: "text",
108
+ status: "status",
109
+ closeDate: "day",
110
+ closedDate: "day",
111
+ closedReason: "text",
112
+ organization: "id",
113
+ contactName: "text",
114
+ companyName: "text",
115
+ people: "people",
116
+ deal: "id",
117
+ url: "text",
118
+ assignee: "id",
119
+ ...TIMES,
120
+ };
121
+ /** Each of our fields and how a value the service sent becomes it. */
122
+ export const FIELDS = {
123
+ person: {
124
+ externalId: "id",
125
+ name: "text",
126
+ firstName: "text",
127
+ lastName: "text",
128
+ email: "text",
129
+ phone: "text",
130
+ emails: "texts",
131
+ phones: "texts",
132
+ position: "text",
133
+ organizations: "organizations",
134
+ assignee: "id",
135
+ url: "text",
136
+ ...TIMES,
137
+ },
138
+ organization: {
139
+ externalId: "id",
140
+ name: "text",
141
+ url: "text",
142
+ type: "text",
143
+ own: "bool",
144
+ phones: "texts",
145
+ emails: "texts",
146
+ people: "ids",
147
+ assignee: "id",
148
+ ...TIMES,
149
+ },
150
+ deal: ITEM,
151
+ lead: ITEM,
152
+ };
153
+ /** The fields a record of the kind always has; a missing one gets its empty value, never a guess. */
154
+ const REQUIRED = {
155
+ person: { name: null },
156
+ organization: { name: "" },
157
+ deal: { title: "", pipeline: "", stage: "" },
158
+ lead: { title: "", pipeline: "", stage: "" },
159
+ };
160
+ export const convert = (conversion, value) => CONVERT[conversion](value);
161
+ /** Our fields from the rules, each converted by `types`; a rule whose path is missing gives no key. */
162
+ export const mapFields = (rules, types, raw) => {
163
+ const out = {};
164
+ for (const [field, rule] of Object.entries(rules)) {
165
+ const type = types[field];
166
+ if (rule === undefined || type === undefined)
167
+ continue;
168
+ const found = evaluate(rule, raw);
169
+ if (found !== MISSING)
170
+ out[field] = convert(type, found);
171
+ }
172
+ return out;
173
+ };
174
+ /** The account's own fields' values under `from`, labelled by their definitions. */
175
+ const customOf = (raw, custom, defined) => {
176
+ const under = at(raw, custom.from);
177
+ if (!isRaw(under))
178
+ return undefined;
179
+ const values = {};
180
+ for (const field of defined) {
181
+ const value = under[field.code];
182
+ if (value === null || value === undefined || value === "")
183
+ continue;
184
+ values[field.code] = field.multiple && custom.split && typeof value === "string" ? value.split(custom.split) : value;
185
+ }
186
+ return Object.keys(values).length ? crmValuesOf(values, defined) : undefined;
187
+ };
188
+ /** One row as our record of the kind, or null for a row without an id. */
189
+ export const mapRecord = (kind, rules, raw, defined = []) => {
190
+ const out = mapFields(rules.map, FIELDS[kind], raw);
191
+ if (typeof out.externalId !== "string")
192
+ return null;
193
+ for (const [field, empty] of Object.entries(REQUIRED[kind]))
194
+ if (out[field] == null)
195
+ out[field] = empty ?? null;
196
+ if (kind === "person") {
197
+ if (out.email === undefined && Array.isArray(out.emails))
198
+ out.email = out.emails[0] ?? null;
199
+ if (out.phone === undefined && Array.isArray(out.phones))
200
+ out.phone = out.phones[0] ?? null;
201
+ }
202
+ if (rules.map.amount !== undefined || rules.map.currency !== undefined) {
203
+ const amount = rules.map.amount === undefined ? MISSING : evaluate(rules.map.amount, raw);
204
+ const currency = rules.map.currency === undefined ? MISSING : evaluate(rules.map.currency, raw);
205
+ if (amount !== MISSING || currency !== MISSING)
206
+ Object.assign(out, amountOf(amount === MISSING ? null : amount, currency === MISSING ? null : currency));
207
+ }
208
+ const metadata = rules.custom ? customOf(raw, rules.custom, defined) : undefined;
209
+ if (metadata)
210
+ out.metadata = metadata;
211
+ return out;
212
+ };
213
+ /** The names under `from` that the rules read: what a service that names its returned fields is asked for. */
214
+ export const selectedOf = (rules, from) => {
215
+ const prefix = `${from}.`;
216
+ const paths = Object.values(rules).flatMap((rule) => {
217
+ if (rule === undefined || typeof rule === "function")
218
+ return [];
219
+ if (typeof rule === "string")
220
+ return [rule];
221
+ if ("first" in rule)
222
+ return [...rule.first];
223
+ if ("join" in rule)
224
+ return [...rule.join];
225
+ if ("all" in rule)
226
+ return [...rule.all];
227
+ if ("each" in rule)
228
+ return [rule.each, ...("primary" in rule && rule.primary ? [rule.primary] : [])];
229
+ return "path" in rule ? [rule.path] : [];
230
+ });
231
+ return [
232
+ ...new Set(paths.filter((one) => one.startsWith(prefix)).map((one) => one.slice(prefix.length).split(".")[0] ?? "")),
233
+ ].filter(Boolean);
234
+ };
@@ -0,0 +1,18 @@
1
+ import type { ServiceApiCall } from "../../cli/service-api-call.js";
2
+ import { type ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
+ import type { CrmSource } from "../source.js";
4
+ import { type CrmManifestHooks } from "./manifest.js";
5
+ export interface CrmManifestSourceOptions {
6
+ /** The generated API manifest the operations are named in: their paths, paging and sign-in. */
7
+ api: ServiceApiManifest;
8
+ /** Sends one operation: `serviceApiCall` over the CLI's fetch and token, or a test's fake. */
9
+ call: ServiceApiCall;
10
+ now?: () => number;
11
+ hooks?: CrmManifestHooks;
12
+ }
13
+ /**
14
+ * A `CrmSource` read from a manifest: every kind listed and read for changes by the operations it names, paged by each
15
+ * operation's own `pagination`, each row mapped onto the shared schema. Deletions are found by a pass over every id.
16
+ * What the manifest cannot say comes from `hooks`.
17
+ */
18
+ export declare const crmSourceFromManifest: (input: unknown, options: CrmManifestSourceOptions) => CrmSource;
@@ -0,0 +1,314 @@
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
+ context?.gap({
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
+ const selectOf = (kind, defined) => {
144
+ const entity = entityOf(kind);
145
+ if (!entity.select)
146
+ return [];
147
+ const custom = entity.custom?.from === entity.select.from ? defined.map(({ code }) => code) : [];
148
+ return [...new Set([...selectedOf(entity.map, entity.select.from), ...custom, ...(entity.select.also ?? [])])];
149
+ };
150
+ const mapped = async (kind, rows, defined, send) => {
151
+ const entity = entityOf(kind);
152
+ const after = hooks.after?.[kind];
153
+ const records = [];
154
+ for (const raw of rows) {
155
+ const record = mapRecord(kind, entity, raw, defined);
156
+ if (record !== null)
157
+ records.push(after ? await after(record, raw, { call: send }) : record);
158
+ }
159
+ return records;
160
+ };
161
+ /**
162
+ * One page of a change read sorted by modified time: the next page starts at the last row's time, or further along
163
+ * the same time when the whole page shares it. A service's own page token is an offset into a list that moves when
164
+ * a row changes mid-round, and would skip the row behind it. Past `cap`, only a full list reads them all.
165
+ */
166
+ const keysetPage = async (changes, slots, since, token, send) => {
167
+ const [fromText, offsetText] = (token ?? "").split(".");
168
+ const from = token === undefined ? since : Number(fromText);
169
+ const offset = token === undefined ? 0 : Number(offsetText);
170
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(offset))
171
+ return { reset: true };
172
+ const { rows, next } = await readPage(changes, { ...slots, since: SINCE[changes.since](from) }, offset ? String(offset) : undefined, send);
173
+ if (next === undefined)
174
+ return { rows, next: undefined };
175
+ const last = convert("epoch", at(rows.at(-1), changes.keyset.field));
176
+ const spot = typeof last === "number" && last > from ? { from: last, offset: 0 } : { from, offset: offset + rows.length };
177
+ if (changes.keyset.cap !== undefined && spot.offset + rows.length > changes.keyset.cap)
178
+ return { reset: true };
179
+ return { rows, next: `${spot.from}.${spot.offset}` };
180
+ };
181
+ const base = {
182
+ provider: manifest.provider,
183
+ traits: { kinds: manifest.kinds, removedInChanges: false },
184
+ async pipelines(kind, context) {
185
+ const spec = manifest.pipelines?.[kind];
186
+ if (!spec)
187
+ return [];
188
+ const rows = await readAll(spec.call, metered(context));
189
+ return rows.flatMap((raw) => toPipeline(spec, raw) ?? []);
190
+ },
191
+ async changes(kind, cursor, page, context) {
192
+ const entity = entityOf(kind);
193
+ const since = cursor === null ? null : Date.parse(cursor);
194
+ if (since !== null && Number.isNaN(since))
195
+ return { reset: true };
196
+ const { token, started } = pageOf(page, now());
197
+ const send = metered(context);
198
+ const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
199
+ const changes = since !== null ? entity.changes : undefined;
200
+ const slots = { select: selectOf(kind, defined) };
201
+ const read = changes?.keyset && since !== null
202
+ ? await keysetPage({ ...changes, keyset: changes.keyset }, slots, since - overlap, token, send)
203
+ : await readPage(changes ?? entity.list, changes && since !== null ? { ...slots, since: SINCE[changes.since](since - overlap) } : slots, token, send);
204
+ if ("reset" in read)
205
+ return { reset: true };
206
+ const { rows, next } = read;
207
+ const items = await mapped(kind, rows, defined, send);
208
+ return next === undefined
209
+ ? { items, hasMore: false, cursor: new Date(started).toISOString() }
210
+ : { items, hasMore: true, nextCursor: `${next}@${started}` };
211
+ },
212
+ async ids(kind, page, context) {
213
+ const entity = entityOf(kind);
214
+ const { rows, next } = await readPage(entity.ids ?? entity.list, {}, page, metered(context));
215
+ const items = rows.flatMap((raw) => {
216
+ const found = evaluate(entity.map.externalId, raw);
217
+ const externalId = found === MISSING ? null : id(found);
218
+ return externalId === null ? [] : [externalId];
219
+ });
220
+ return next === undefined ? { items, hasMore: false } : { items, hasMore: true, nextCursor: next };
221
+ },
222
+ async get(kind, externalId, context) {
223
+ const entity = entityOf(kind);
224
+ if (!entity.get)
225
+ return null;
226
+ const send = metered(context);
227
+ const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
228
+ let answer;
229
+ try {
230
+ answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined) }));
231
+ }
232
+ catch (error) {
233
+ if (unseen(error))
234
+ return null;
235
+ throw error;
236
+ }
237
+ const raw = entity.get.items === undefined ? answer : at(answer, entity.get.items);
238
+ return isRaw(raw) ? ((await mapped(kind, [raw], defined, send))[0] ?? null) : null;
239
+ },
240
+ ...(manifest.fields
241
+ ? { fields: (kind, context) => fieldsOf(kind, metered(context), context) }
242
+ : {}),
243
+ ...(manifest.users
244
+ ? {
245
+ async users(context) {
246
+ const spec = manifest.users;
247
+ const rows = await readAll(spec.call, metered(context));
248
+ const users = rows.flatMap((raw) => {
249
+ const user = mapFields(spec.map, { externalId: "id", name: "text", email: "text", position: "text", active: "bool" }, raw);
250
+ return typeof user.externalId === "string" ? [user] : [];
251
+ });
252
+ return [...new Map(users.map((user) => [user.externalId, user])).values()];
253
+ },
254
+ }
255
+ : {}),
256
+ };
257
+ return { ...base, ...hooks.extend?.(base) };
258
+ };
259
+ const outcomeOf = (spec, stage, pipeline) => {
260
+ if (typeof spec === "function")
261
+ return spec(stage, pipeline);
262
+ if ("value" in spec)
263
+ return spec.value;
264
+ const found = text(at(stage, spec.path)) ?? "";
265
+ if (spec.won?.includes(found))
266
+ return "won";
267
+ return spec.lost?.includes(found) ? "lost" : "open";
268
+ };
269
+ const toPipeline = (spec, raw) => {
270
+ const { externalId, name } = mapFields(spec.map, { externalId: "id", name: "text" }, raw);
271
+ if (typeof externalId !== "string")
272
+ return null;
273
+ return {
274
+ externalId,
275
+ name: typeof name === "string" ? name : externalId,
276
+ stages: rawsOf(at(raw, spec.stages.each)).flatMap((stage, place) => {
277
+ const found = mapFields(spec.stages.map, { externalId: "id", name: "text", position: "text" }, stage);
278
+ if (typeof found.externalId !== "string")
279
+ return [];
280
+ return [
281
+ {
282
+ externalId: found.externalId,
283
+ name: typeof found.name === "string" ? found.name : found.externalId,
284
+ position: number(found.position) ?? place,
285
+ outcome: outcomeOf(spec.stages.outcome, stage, raw),
286
+ },
287
+ ];
288
+ }),
289
+ };
290
+ };
291
+ const toField = (spec, raw) => {
292
+ if (spec.keep && !spec.keep(raw))
293
+ return null;
294
+ const { options: optionsRule, ...rules } = spec.map;
295
+ const found = mapFields(rules, { code: "text", label: "text", type: "text", multiple: "bool", filterable: "bool" }, raw);
296
+ if (typeof found.code !== "string")
297
+ return null;
298
+ const options = typeof optionsRule === "function"
299
+ ? optionsRule(raw)
300
+ : optionsRule === undefined
301
+ ? undefined
302
+ : rawsOf(at(raw, optionsRule.each)).flatMap((one) => {
303
+ const option = convert("text", at(one, optionsRule.id));
304
+ return typeof option === "string" ? [{ id: option, label: text(at(one, optionsRule.label)) ?? option }] : [];
305
+ });
306
+ return {
307
+ code: found.code,
308
+ label: typeof found.label === "string" ? found.label : null,
309
+ type: typeof found.type === "string" ? found.type : "string",
310
+ multiple: found.multiple === true,
311
+ filterable: found.filterable !== false,
312
+ ...(options?.length ? { options: [...new Map(options.map((one) => [one.id, one])).values()] } : {}),
313
+ };
314
+ };
@@ -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"],
@@ -19,7 +19,8 @@ export interface MeetingCommandDeps {
19
19
  * never writes over a file.
20
20
  */
21
21
  newFileOutput?: (command: Command, option: string) => void;
22
- write: (value: unknown, format: "json" | "jsonl" | "text") => void;
22
+ /** Prints an answer; `meetingAnswerBody(command, value)` from `@wirecat/cli-core/cli` makes it the host's body. */
23
+ write: (value: unknown, format: "json" | "jsonl" | "text", command: Command) => void;
23
24
  /**
24
25
  * Runs a command that reaches the account inside cli-core's run, so it is recorded and ended by `--timeout`:
25
26
  * `inCommandRun` from `@wirecat/cli-core/cli`. Required, since this module cannot reach the run itself.
@@ -48,7 +48,7 @@ const addMeetingCommandsDefinition = (program, deps) => {
48
48
  const output = (command) => command;
49
49
  const print = (value, command) => {
50
50
  const opts = command.optsWithGlobals();
51
- deps.write(value, opts.json ? "json" : opts.jsonl ? "jsonl" : "text");
51
+ deps.write(value, opts.json ? "json" : opts.jsonl ? "jsonl" : "text", command);
52
52
  };
53
53
  const access = (command, backend) => {
54
54
  const signal = deps.signal?.();