@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,161 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import * as v from "valibot";
|
|
3
|
+
import { CRM_KINDS } from "../../domain/crm.js";
|
|
4
|
+
import { DEAL_KINDS, STAGE_OUTCOMES } from "../../domain/deals.js";
|
|
5
|
+
import { editDistance } from "../../search/correct.js";
|
|
6
|
+
import { FIELDS } from "./map.js";
|
|
7
|
+
const path = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dotted path such as properties.name"));
|
|
8
|
+
const paths = v.pipe(v.array(path), v.minLength(1));
|
|
9
|
+
const rule = v.union([
|
|
10
|
+
path,
|
|
11
|
+
v.strictObject({ first: paths }),
|
|
12
|
+
v.strictObject({ join: paths }),
|
|
13
|
+
v.strictObject({ all: paths, split: v.optional(v.string()) }),
|
|
14
|
+
v.strictObject({ path, split: v.optional(v.string()) }),
|
|
15
|
+
v.strictObject({ path, map: v.record(v.string(), v.unknown()) }),
|
|
16
|
+
v.strictObject({ each: path, id: path, primary: v.optional(path) }),
|
|
17
|
+
v.strictObject({ each: path, value: path }),
|
|
18
|
+
v.strictObject({ value: v.unknown() }),
|
|
19
|
+
v.function(),
|
|
20
|
+
], "a path, one of first, join, all, path, each, value, or a function");
|
|
21
|
+
const call = v.strictObject({
|
|
22
|
+
operation: v.pipe(v.string(), v.minLength(1)),
|
|
23
|
+
path: v.optional(v.record(v.string(), v.string())),
|
|
24
|
+
query: v.optional(v.record(v.string(), v.union([v.string(), v.number(), v.boolean()]))),
|
|
25
|
+
body: v.optional(v.unknown()),
|
|
26
|
+
items: v.optional(path),
|
|
27
|
+
});
|
|
28
|
+
const entity = v.strictObject({
|
|
29
|
+
list: call,
|
|
30
|
+
changes: v.optional(v.strictObject({
|
|
31
|
+
...call.entries,
|
|
32
|
+
since: v.picklist(["ms", "seconds", "iso", "datetime"]),
|
|
33
|
+
keyset: v.optional(v.strictObject({ field: path, cap: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))) })),
|
|
34
|
+
})),
|
|
35
|
+
ids: v.optional(call),
|
|
36
|
+
get: v.optional(call),
|
|
37
|
+
select: v.optional(v.strictObject({
|
|
38
|
+
from: path,
|
|
39
|
+
also: v.optional(v.array(v.string())),
|
|
40
|
+
max: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
|
|
41
|
+
})),
|
|
42
|
+
map: v.record(v.string(), rule),
|
|
43
|
+
custom: v.optional(v.strictObject({ from: path, split: v.optional(v.string()) })),
|
|
44
|
+
optional: v.optional(v.strictObject({ message: v.pipe(v.string(), v.minLength(1)), scope: v.optional(v.string()) })),
|
|
45
|
+
});
|
|
46
|
+
const pipelines = v.strictObject({
|
|
47
|
+
call,
|
|
48
|
+
map: v.strictObject({ externalId: rule, name: rule }),
|
|
49
|
+
stages: v.strictObject({
|
|
50
|
+
each: path,
|
|
51
|
+
map: v.strictObject({ externalId: rule, name: rule, position: v.optional(rule) }),
|
|
52
|
+
outcome: v.union([
|
|
53
|
+
v.strictObject({ path, won: v.optional(v.array(v.string())), lost: v.optional(v.array(v.string())) }),
|
|
54
|
+
v.strictObject({ value: v.picklist(STAGE_OUTCOMES) }),
|
|
55
|
+
v.function(),
|
|
56
|
+
]),
|
|
57
|
+
}),
|
|
58
|
+
});
|
|
59
|
+
const fields = v.strictObject({
|
|
60
|
+
call,
|
|
61
|
+
map: v.strictObject({
|
|
62
|
+
code: rule,
|
|
63
|
+
label: v.optional(rule),
|
|
64
|
+
type: v.optional(rule),
|
|
65
|
+
multiple: v.optional(rule),
|
|
66
|
+
filterable: v.optional(rule),
|
|
67
|
+
options: v.optional(v.union([v.strictObject({ each: path, id: path, label: path }), v.function()])),
|
|
68
|
+
}),
|
|
69
|
+
keep: v.optional(v.function()),
|
|
70
|
+
});
|
|
71
|
+
const kind = v.picklist(CRM_KINDS);
|
|
72
|
+
const schema = v.strictObject({
|
|
73
|
+
provider: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]*$/, "a registry name such as hubspot")),
|
|
74
|
+
kinds: v.pipe(v.array(kind), v.minLength(1)),
|
|
75
|
+
overlapMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
|
|
76
|
+
entities: v.record(kind, v.optional(entity)),
|
|
77
|
+
pipelines: v.optional(v.record(v.picklist(DEAL_KINDS), v.optional(pipelines))),
|
|
78
|
+
fields: v.optional(v.record(kind, v.optional(fields))),
|
|
79
|
+
users: v.optional(v.strictObject({
|
|
80
|
+
call,
|
|
81
|
+
map: v.strictObject({
|
|
82
|
+
externalId: rule,
|
|
83
|
+
name: v.optional(rule),
|
|
84
|
+
email: v.optional(rule),
|
|
85
|
+
position: v.optional(rule),
|
|
86
|
+
active: v.optional(rule),
|
|
87
|
+
}),
|
|
88
|
+
})),
|
|
89
|
+
});
|
|
90
|
+
const invalid = (where, message) => new CliError("configuration_error", `source manifest: ${where}: ${message}`, { reason: "manifest.invalid" });
|
|
91
|
+
/** The known name a typo most likely meant: at most two edits away, else none. */
|
|
92
|
+
const nearest = (wanted, known) => known
|
|
93
|
+
.map((one) => ({ one, edits: editDistance(wanted, one, 2) }))
|
|
94
|
+
.filter(({ edits }) => edits <= 2)
|
|
95
|
+
.sort((a, b) => a.edits - b.edits)[0]?.one;
|
|
96
|
+
const hasPlaceholder = (value, placeholder) => value === placeholder ||
|
|
97
|
+
(Array.isArray(value) && value.some((one) => hasPlaceholder(one, placeholder))) ||
|
|
98
|
+
(typeof value === "object" && value !== null && Object.values(value).some((one) => hasPlaceholder(one, placeholder)));
|
|
99
|
+
/**
|
|
100
|
+
* The manifest checked against its shape and the generated API: each operation exists, a list pages or says where its
|
|
101
|
+
* rows are, a change call places `{since}`, a deal or lead kind has pipelines. Every error names where it is.
|
|
102
|
+
*/
|
|
103
|
+
export const parseCrmManifest = (input, api) => {
|
|
104
|
+
const parsed = v.safeParse(schema, input);
|
|
105
|
+
if (!parsed.success) {
|
|
106
|
+
const [issue] = parsed.issues;
|
|
107
|
+
throw invalid(v.getDotPath(issue) ?? "(root)", issue.message);
|
|
108
|
+
}
|
|
109
|
+
const manifest = parsed.output;
|
|
110
|
+
const operations = new Map(api.operations.map((one) => [one.id, one]));
|
|
111
|
+
const known = [...operations.keys()];
|
|
112
|
+
const checkCall = (where, one, pages) => {
|
|
113
|
+
const operation = operations.get(one.operation);
|
|
114
|
+
if (!operation) {
|
|
115
|
+
const near = nearest(one.operation, known);
|
|
116
|
+
throw invalid(`${where}.operation`, `no operation ${one.operation} in the API${near ? `; did you mean ${near}?` : ""}`);
|
|
117
|
+
}
|
|
118
|
+
if (operation.effect !== "read")
|
|
119
|
+
throw invalid(`${where}.operation`, `${one.operation} is a ${operation.effect}, and a source only reads`);
|
|
120
|
+
if (pages && operation.pagination?.style === "link")
|
|
121
|
+
throw invalid(`${where}.operation`, `${one.operation} pages by a link, which a source does not read yet`);
|
|
122
|
+
};
|
|
123
|
+
for (const kind of manifest.kinds) {
|
|
124
|
+
const one = manifest.entities[kind];
|
|
125
|
+
if (!one)
|
|
126
|
+
throw invalid(`entities.${kind}`, `${kind} is in kinds but has no entity`);
|
|
127
|
+
checkCall(`entities.${kind}.list`, one.list, true);
|
|
128
|
+
if (one.changes) {
|
|
129
|
+
checkCall(`entities.${kind}.changes`, one.changes, true);
|
|
130
|
+
if (!hasPlaceholder([one.changes.path, one.changes.query, one.changes.body], "{since}"))
|
|
131
|
+
throw invalid(`entities.${kind}.changes`, 'no "{since}" in its path, query or body');
|
|
132
|
+
}
|
|
133
|
+
if (one.ids)
|
|
134
|
+
checkCall(`entities.${kind}.ids`, one.ids, true);
|
|
135
|
+
if (one.get) {
|
|
136
|
+
checkCall(`entities.${kind}.get`, one.get, false);
|
|
137
|
+
if (!hasPlaceholder([one.get.path, one.get.query, one.get.body], "{id}"))
|
|
138
|
+
throw invalid(`entities.${kind}.get`, 'no "{id}" in its path, query or body');
|
|
139
|
+
}
|
|
140
|
+
if (one.map.externalId === undefined)
|
|
141
|
+
throw invalid(`entities.${kind}.map.externalId`, "every kind maps its id");
|
|
142
|
+
const fields = [...Object.keys(FIELDS[kind]), "amount", "currency"];
|
|
143
|
+
for (const field of Object.keys(one.map))
|
|
144
|
+
if (!fields.includes(field)) {
|
|
145
|
+
const near = nearest(field, fields);
|
|
146
|
+
throw invalid(`entities.${kind}.map.${field}`, `${kind} has no such field${near ? `; did you mean ${near}?` : ""}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
for (const kind of DEAL_KINDS.filter((one) => manifest.kinds.includes(one))) {
|
|
150
|
+
const one = manifest.pipelines?.[kind];
|
|
151
|
+
if (!one)
|
|
152
|
+
throw invalid(`pipelines.${kind}`, `${kind} is in kinds, and every deal or lead stands in a pipeline`);
|
|
153
|
+
checkCall(`pipelines.${kind}.call`, one.call, true);
|
|
154
|
+
}
|
|
155
|
+
for (const [kind, one] of Object.entries(manifest.fields ?? {}))
|
|
156
|
+
if (one)
|
|
157
|
+
checkCall(`fields.${kind}.call`, one.call, true);
|
|
158
|
+
if (manifest.users)
|
|
159
|
+
checkCall("users.call", manifest.users.call, true);
|
|
160
|
+
return manifest;
|
|
161
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { CrmField, CrmKind, CrmRecords } from "../../domain/crm.js";
|
|
2
|
+
import { type CrmRaw, id, text } from "../values.js";
|
|
3
|
+
import type { CrmRule } from "./manifest.js";
|
|
4
|
+
/** The service sent nothing at this path: the field is left out, so the stored copy keeps what it held. */
|
|
5
|
+
export declare const MISSING: unique symbol;
|
|
6
|
+
type Read = unknown | typeof MISSING;
|
|
7
|
+
/** A dotted path; a number steps into a list (`results.0.id`), and `.` is the value itself. */
|
|
8
|
+
export declare const at: (value: unknown, path: string) => unknown;
|
|
9
|
+
export declare const evaluate: (rule: CrmRule, raw: CrmRaw) => Read;
|
|
10
|
+
/** A time as epoch ms: ISO, epoch seconds, or epoch ms as digits in a string (HubSpot sends both forms). */
|
|
11
|
+
declare const epochOf: (value: unknown) => number | null;
|
|
12
|
+
/** The day as the service wrote it: a time with an offset turned into UTC may fall on the day before. */
|
|
13
|
+
declare const dayOf: (value: unknown) => string | null;
|
|
14
|
+
declare const yes: (value: unknown) => boolean;
|
|
15
|
+
declare const CONVERT: {
|
|
16
|
+
id: typeof id;
|
|
17
|
+
text: typeof text;
|
|
18
|
+
epoch: typeof epochOf;
|
|
19
|
+
day: typeof dayOf;
|
|
20
|
+
bool: typeof yes;
|
|
21
|
+
texts: (value: unknown) => string[];
|
|
22
|
+
ids: (value: unknown) => string[];
|
|
23
|
+
status: (value: unknown) => string | null;
|
|
24
|
+
organizations: (value: unknown) => {
|
|
25
|
+
externalId: string;
|
|
26
|
+
primary?: true | undefined;
|
|
27
|
+
}[];
|
|
28
|
+
people: (value: unknown) => {
|
|
29
|
+
externalId: string;
|
|
30
|
+
role: "contact";
|
|
31
|
+
primary?: true | undefined;
|
|
32
|
+
}[];
|
|
33
|
+
};
|
|
34
|
+
export type Conversion = keyof typeof CONVERT;
|
|
35
|
+
/** Each of our fields and how a value the service sent becomes it. */
|
|
36
|
+
export declare const FIELDS: {
|
|
37
|
+
readonly [K in CrmKind]: Readonly<Record<string, Conversion>>;
|
|
38
|
+
};
|
|
39
|
+
export declare const convert: (conversion: Conversion, value: unknown) => unknown;
|
|
40
|
+
/** Our fields from the rules, each converted by `types`; a rule whose path is missing gives no key. */
|
|
41
|
+
export declare const mapFields: (rules: Readonly<Record<string, CrmRule | undefined>>, types: Readonly<Record<string, Conversion>>, raw: CrmRaw) => Record<string, unknown>;
|
|
42
|
+
export interface RecordRules {
|
|
43
|
+
map: Readonly<Record<string, CrmRule | undefined>>;
|
|
44
|
+
custom?: {
|
|
45
|
+
from: string;
|
|
46
|
+
split?: string;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** One row as our record of the kind, or null for a row without an id. */
|
|
50
|
+
export declare const mapRecord: <K extends CrmKind>(kind: K, rules: RecordRules, raw: CrmRaw, defined?: readonly CrmField[]) => CrmRecords[K] | null;
|
|
51
|
+
/** Each path a rule reads; `inside` is the list an `each` reads its `id` or `value` from, item by item. */
|
|
52
|
+
export declare const rulePaths: (rule: CrmRule | undefined) => {
|
|
53
|
+
path: string;
|
|
54
|
+
inside?: string;
|
|
55
|
+
}[];
|
|
56
|
+
/** The names under `from` that the rules read: what a service that names its returned fields is asked for. */
|
|
57
|
+
export declare const selectedOf: (rules: Readonly<Record<string, CrmRule | undefined>>, from: string) => string[];
|
|
58
|
+
export {};
|
|
@@ -0,0 +1,240 @@
|
|
|
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
|
+
/** Each path a rule reads; `inside` is the list an `each` reads its `id` or `value` from, item by item. */
|
|
214
|
+
export const rulePaths = (rule) => {
|
|
215
|
+
if (rule === undefined || typeof rule === "function")
|
|
216
|
+
return [];
|
|
217
|
+
if (typeof rule === "string")
|
|
218
|
+
return [{ path: rule }];
|
|
219
|
+
if ("first" in rule)
|
|
220
|
+
return rule.first.map((path) => ({ path }));
|
|
221
|
+
if ("join" in rule)
|
|
222
|
+
return rule.join.map((path) => ({ path }));
|
|
223
|
+
if ("all" in rule)
|
|
224
|
+
return rule.all.map((path) => ({ path }));
|
|
225
|
+
if ("each" in rule)
|
|
226
|
+
return [
|
|
227
|
+
{ path: rule.each },
|
|
228
|
+
{ path: "id" in rule ? rule.id : rule.value, inside: rule.each },
|
|
229
|
+
...("primary" in rule && rule.primary ? [{ path: rule.primary }] : []),
|
|
230
|
+
];
|
|
231
|
+
return "path" in rule ? [{ path: rule.path }] : [];
|
|
232
|
+
};
|
|
233
|
+
/** The names under `from` that the rules read: what a service that names its returned fields is asked for. */
|
|
234
|
+
export const selectedOf = (rules, from) => {
|
|
235
|
+
const prefix = `${from}.`;
|
|
236
|
+
const paths = Object.values(rules).flatMap((rule) => rulePaths(rule).flatMap(({ path, inside }) => (inside === undefined ? [path] : [])));
|
|
237
|
+
return [
|
|
238
|
+
...new Set(paths.filter((one) => one.startsWith(prefix)).map((one) => one.slice(prefix.length).split(".")[0] ?? "")),
|
|
239
|
+
].filter(Boolean);
|
|
240
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SchemaNode } from "@wirecat/cli-base/codegen";
|
|
2
|
+
import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
|
|
3
|
+
import type { CrmManifest } from "./manifest.js";
|
|
4
|
+
type Definitions = Readonly<Record<string, SchemaNode>>;
|
|
5
|
+
/**
|
|
6
|
+
* Every path the manifest reads, checked against the schema each operation answers (`definitions` of the generated
|
|
7
|
+
* API): a misspelt or moved field is named with the operation, and the field it likely meant, before a sync runs.
|
|
8
|
+
* A part of a schema that says nothing (`unknown`, an open object) passes. Empty when all hold.
|
|
9
|
+
*/
|
|
10
|
+
export declare const crmManifestProblems: (manifest: CrmManifest, api: ServiceApiManifest, definitions: Definitions) => string[];
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { editDistance } from "../../search/correct.js";
|
|
2
|
+
import { rulePaths } from "./map.js";
|
|
3
|
+
const resolve = (node, definitions, seen = new Set()) => {
|
|
4
|
+
if (node.type !== "ref" || seen.has(node.ref))
|
|
5
|
+
return node;
|
|
6
|
+
const found = definitions[node.ref];
|
|
7
|
+
return found ? resolve(found, definitions, new Set([...seen, node.ref])) : { type: "unknown" };
|
|
8
|
+
};
|
|
9
|
+
/** The node one step down, `null` when the schema has no such field, `undefined` when the schema cannot say. */
|
|
10
|
+
const step = (node, key, definitions) => {
|
|
11
|
+
const at = resolve(node, definitions);
|
|
12
|
+
switch (at.type) {
|
|
13
|
+
case "object": {
|
|
14
|
+
const found = at.properties[key] ?? at.additionalProperties;
|
|
15
|
+
if (found)
|
|
16
|
+
return found;
|
|
17
|
+
// An object the spec leaves open ("any object") comes out of the adapter with no fields at all.
|
|
18
|
+
return Object.keys(at.properties).length === 0 ? undefined : null;
|
|
19
|
+
}
|
|
20
|
+
case "array":
|
|
21
|
+
return /^\d+$/.test(key) ? at.items : null;
|
|
22
|
+
case "allOf":
|
|
23
|
+
case "union": {
|
|
24
|
+
const found = at.of.map((one) => step(one, key, definitions));
|
|
25
|
+
if (found.includes(undefined))
|
|
26
|
+
return undefined;
|
|
27
|
+
const matched = found.filter((one) => one !== null);
|
|
28
|
+
if (matched.length === 0)
|
|
29
|
+
return null;
|
|
30
|
+
return matched.length === 1 ? matched[0] : { type: "union", of: matched };
|
|
31
|
+
}
|
|
32
|
+
case "unknown":
|
|
33
|
+
return undefined;
|
|
34
|
+
default:
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const keysOf = (node, definitions) => {
|
|
39
|
+
const at = resolve(node, definitions);
|
|
40
|
+
if (at.type === "object")
|
|
41
|
+
return Object.keys(at.properties);
|
|
42
|
+
if (at.type === "allOf" || at.type === "union")
|
|
43
|
+
return at.of.flatMap((one) => keysOf(one, definitions));
|
|
44
|
+
return [];
|
|
45
|
+
};
|
|
46
|
+
const walk = (node, path, definitions) => {
|
|
47
|
+
let at = node;
|
|
48
|
+
const segments = path === "." ? [] : path.split(".");
|
|
49
|
+
for (const [place, key] of segments.entries()) {
|
|
50
|
+
if (at === undefined)
|
|
51
|
+
return { node: undefined };
|
|
52
|
+
const next = step(at, key, definitions);
|
|
53
|
+
if (next === null) {
|
|
54
|
+
const near = keysOf(at, definitions)
|
|
55
|
+
.map((one) => ({ one, edits: editDistance(key, one, 2) }))
|
|
56
|
+
.filter(({ edits }) => edits <= 2)
|
|
57
|
+
.sort((a, b) => a.edits - b.edits)[0]?.one;
|
|
58
|
+
return {
|
|
59
|
+
missing: segments.slice(0, place + 1).join("."),
|
|
60
|
+
...(near ? { near: [...segments.slice(0, place), near].join(".") } : {}),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
at = next;
|
|
64
|
+
}
|
|
65
|
+
return { node: at };
|
|
66
|
+
};
|
|
67
|
+
/** One item of the list a path ends on; a path that ends on one object is read as a list of it, as the map does. */
|
|
68
|
+
const itemOf = (node, definitions) => {
|
|
69
|
+
if (node === undefined)
|
|
70
|
+
return undefined;
|
|
71
|
+
const at = resolve(node, definitions);
|
|
72
|
+
return at.type === "array" ? at.items : at;
|
|
73
|
+
};
|
|
74
|
+
const missingText = (found, operation) => `${found.missing} is not in what ${operation} answers${found.near ? `; did you mean ${found.near}?` : ""}`;
|
|
75
|
+
/**
|
|
76
|
+
* Every path the manifest reads, checked against the schema each operation answers (`definitions` of the generated
|
|
77
|
+
* API): a misspelt or moved field is named with the operation, and the field it likely meant, before a sync runs.
|
|
78
|
+
* A part of a schema that says nothing (`unknown`, an open object) passes. Empty when all hold.
|
|
79
|
+
*/
|
|
80
|
+
export const crmManifestProblems = (manifest, api, definitions) => {
|
|
81
|
+
const operations = new Map(api.operations.map((one) => [one.id, one]));
|
|
82
|
+
const problems = [];
|
|
83
|
+
const problem = (where, text) => problems.push(`source manifest: ${where}: ${text}`);
|
|
84
|
+
/** The schema of one row the call answers: its response, down `items`, one item of the list. */
|
|
85
|
+
const rowOf = (where, operation, call) => {
|
|
86
|
+
const schema = operation.response?.schema;
|
|
87
|
+
if (!schema)
|
|
88
|
+
return undefined;
|
|
89
|
+
const root = { type: "ref", ref: schema };
|
|
90
|
+
const items = call.items ?? operation.pagination?.items;
|
|
91
|
+
if (items === undefined)
|
|
92
|
+
return itemOf(root, definitions);
|
|
93
|
+
const found = walk(root, items, definitions);
|
|
94
|
+
if ("missing" in found) {
|
|
95
|
+
problem(`${where}.items`, missingText(found, call.operation));
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
return itemOf(found.node, definitions);
|
|
99
|
+
};
|
|
100
|
+
const check = (where, call, rules, inside) => {
|
|
101
|
+
const operation = operations.get(call.operation);
|
|
102
|
+
if (!operation)
|
|
103
|
+
return problem(where, `no operation ${call.operation} in the API`);
|
|
104
|
+
let row = rowOf(where, operation, call);
|
|
105
|
+
if (row === undefined)
|
|
106
|
+
return;
|
|
107
|
+
if (inside !== undefined) {
|
|
108
|
+
const list = walk(row, inside, definitions);
|
|
109
|
+
if ("missing" in list)
|
|
110
|
+
return problem(where, missingText(list, call.operation));
|
|
111
|
+
row = itemOf(list.node, definitions);
|
|
112
|
+
if (row === undefined)
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
for (const [field, rule] of Object.entries(rules))
|
|
116
|
+
for (const { path, inside: list } of rulePaths(rule)) {
|
|
117
|
+
let from = row;
|
|
118
|
+
if (list !== undefined) {
|
|
119
|
+
const found = walk(row, list, definitions);
|
|
120
|
+
from = "node" in found ? itemOf(found.node, definitions) : undefined;
|
|
121
|
+
if (from === undefined)
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const found = walk(from, path, definitions);
|
|
125
|
+
if ("missing" in found)
|
|
126
|
+
problem(`${where}.${field}`, missingText(found, call.operation));
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
for (const [kind, entity] of Object.entries(manifest.entities)) {
|
|
130
|
+
if (!entity)
|
|
131
|
+
continue;
|
|
132
|
+
const rules = {
|
|
133
|
+
...entity.map,
|
|
134
|
+
...(entity.custom ? { "(custom)": entity.custom.from } : {}),
|
|
135
|
+
};
|
|
136
|
+
for (const call of [entity.list, entity.changes, entity.get])
|
|
137
|
+
if (call)
|
|
138
|
+
check(`entities.${kind}.map`, call, rules);
|
|
139
|
+
}
|
|
140
|
+
for (const [kind, pipelines] of Object.entries(manifest.pipelines ?? {})) {
|
|
141
|
+
if (!pipelines)
|
|
142
|
+
continue;
|
|
143
|
+
check(`pipelines.${kind}.map`, pipelines.call, { ...pipelines.map, "(stages)": pipelines.stages.each });
|
|
144
|
+
const { outcome } = pipelines.stages;
|
|
145
|
+
check(`pipelines.${kind}.stages.map`, pipelines.call, {
|
|
146
|
+
...pipelines.stages.map,
|
|
147
|
+
...(typeof outcome === "object" && "path" in outcome ? { outcome: outcome.path } : {}),
|
|
148
|
+
}, pipelines.stages.each);
|
|
149
|
+
}
|
|
150
|
+
for (const [kind, fields] of Object.entries(manifest.fields ?? {})) {
|
|
151
|
+
if (!fields)
|
|
152
|
+
continue;
|
|
153
|
+
const { options, ...map } = fields.map;
|
|
154
|
+
check(`fields.${kind}.map`, fields.call, map);
|
|
155
|
+
if (options && typeof options === "object")
|
|
156
|
+
check(`fields.${kind}.map.options`, fields.call, { id: options.id, label: options.label }, options.each);
|
|
157
|
+
}
|
|
158
|
+
if (manifest.users)
|
|
159
|
+
check("users.map", manifest.users.call, manifest.users.map);
|
|
160
|
+
return problems;
|
|
161
|
+
};
|
|
@@ -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;
|