@wirecat/cli-core 0.691.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,176 @@
1
+ import type { ServiceApiCall } from "../../cli/service-api-call.js";
2
+ import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
+ import { type CrmKind, type CrmRecords } from "../../domain/crm.js";
4
+ import { type DealKind, type StageOutcome } from "../../domain/deals.js";
5
+ import type { CrmSource } from "../source.js";
6
+ import type { CrmRaw } from "../values.js";
7
+ /**
8
+ * Where one of our fields comes from in a row the service answered. A path is dotted (`properties.firstname`); the
9
+ * engine converts the value by the field it fills (an id to a string, a time to epoch ms, a day to `YYYY-MM-DD`).
10
+ */
11
+ export type CrmRule = string | {
12
+ first: readonly string[];
13
+ } | {
14
+ join: readonly string[];
15
+ } | {
16
+ all: readonly string[];
17
+ split?: string;
18
+ } | {
19
+ path: string;
20
+ split?: string;
21
+ } | {
22
+ path: string;
23
+ map: Readonly<Record<string, unknown>>;
24
+ } | {
25
+ each: string;
26
+ id: string;
27
+ primary?: string;
28
+ } | {
29
+ each: string;
30
+ value: string;
31
+ } | {
32
+ value: unknown;
33
+ } | ((raw: CrmRaw) => unknown);
34
+ /**
35
+ * One request to the service: an operation of the generated API manifest by its id, with fixed parameters. A string
36
+ * value `"{since}"`, `"{select}"` or `"{id}"` anywhere in `path`, `query` or `body` is filled in by the engine; an empty
37
+ * `"{select}"` leaves the parameter out.
38
+ */
39
+ export interface CrmOperationCall {
40
+ operation: string;
41
+ path?: Readonly<Record<string, string>>;
42
+ query?: Readonly<Record<string, string | number | boolean>>;
43
+ body?: unknown;
44
+ /** Where the answer's rows are when the operation has no `pagination`; absent, the answer itself is the list. */
45
+ items?: string;
46
+ }
47
+ export interface CrmChangesCall extends CrmOperationCall {
48
+ /** How `{since}` is written: epoch ms or seconds as digits, ISO, or `YYYY-MM-DD HH:MM:SS` in UTC. */
49
+ since: "ms" | "seconds" | "iso" | "datetime";
50
+ /**
51
+ * The answer is sorted by `field`, a time, ascending: pages go on from the last row's time, so a row that changes
52
+ * mid-round moves nothing under the next page. Past `cap` rows at one time the round answers `reset`.
53
+ */
54
+ keyset?: {
55
+ field: string;
56
+ cap?: number;
57
+ };
58
+ }
59
+ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
60
+ /** Every row of the kind, page by page by the operation's own `pagination`. */
61
+ list: CrmOperationCall;
62
+ /** Rows changed since `{since}`, the last cursor less the overlap; absent, every sync lists in full. */
63
+ changes?: CrmChangesCall;
64
+ /** Every id, to find deletions; absent, `list` with an empty `{select}`. */
65
+ ids?: CrmOperationCall;
66
+ /** One row by `{id}`, for a live read of a contact or company; a 403 or 404 is no row. */
67
+ get?: CrmOperationCall;
68
+ /**
69
+ * The service names the fields a read returns (HubSpot `properties=`, Bitrix24 `select`): `{select}` becomes the
70
+ * names under `from` that `map` reads, the custom field codes, and `also`.
71
+ */
72
+ select?: {
73
+ from: string;
74
+ also?: readonly string[];
75
+ };
76
+ map: {
77
+ readonly [F in keyof CrmRecords[K]]?: CrmRule;
78
+ } & {
79
+ amount?: CrmRule;
80
+ currency?: CrmRule;
81
+ };
82
+ /** The account's own fields' values, by the codes `fields` lists, under this object of the row. */
83
+ custom?: {
84
+ from: string;
85
+ split?: string;
86
+ };
87
+ }
88
+ export interface CrmManifestPipelines {
89
+ call: CrmOperationCall;
90
+ map: {
91
+ externalId: CrmRule;
92
+ name: CrmRule;
93
+ };
94
+ stages: {
95
+ each: string;
96
+ map: {
97
+ externalId: CrmRule;
98
+ name: CrmRule;
99
+ position?: CrmRule;
100
+ };
101
+ /** Which stages are won or lost by one field; any other is open. A rule a field cannot say is a function. */
102
+ outcome: {
103
+ path: string;
104
+ won?: readonly string[];
105
+ lost?: readonly string[];
106
+ } | {
107
+ value: StageOutcome;
108
+ } | ((stage: CrmRaw, pipeline: CrmRaw) => StageOutcome);
109
+ };
110
+ }
111
+ export interface CrmManifestFields {
112
+ call: CrmOperationCall;
113
+ map: {
114
+ code: CrmRule;
115
+ label?: CrmRule;
116
+ type?: CrmRule;
117
+ multiple?: CrmRule;
118
+ filterable?: CrmRule;
119
+ options?: {
120
+ each: string;
121
+ id: string;
122
+ label: string;
123
+ } | ((raw: CrmRaw) => {
124
+ id: string;
125
+ label: string;
126
+ }[] | undefined);
127
+ };
128
+ /** Which listed fields are the account's own, not the service's built-in ones the map already reads. */
129
+ keep?: (raw: CrmRaw) => boolean;
130
+ }
131
+ /** A CRM account described as data: what to call for each kind and where each of our fields is in the answer. */
132
+ export interface CrmManifest {
133
+ /** The registry name: `hubspot`, `pipedrive`. */
134
+ provider: string;
135
+ /** Contacts and companies before the items on them. */
136
+ kinds: readonly CrmKind[];
137
+ /** Re-read before the last cursor: rows saved while the round ran, and a clock running ahead. Default 10 min. */
138
+ overlapMs?: number;
139
+ entities: {
140
+ readonly [K in CrmKind]?: CrmManifestEntity<K>;
141
+ };
142
+ pipelines?: {
143
+ readonly [K in DealKind]?: CrmManifestPipelines;
144
+ };
145
+ fields?: {
146
+ readonly [K in CrmKind]?: CrmManifestFields;
147
+ };
148
+ users?: {
149
+ call: CrmOperationCall;
150
+ map: {
151
+ externalId: CrmRule;
152
+ name?: CrmRule;
153
+ email?: CrmRule;
154
+ position?: CrmRule;
155
+ active?: CrmRule;
156
+ };
157
+ };
158
+ }
159
+ /** Corrects one record after the map; `call` reads more from the service, spent from the run's budget. */
160
+ export type CrmAfterHook<K extends CrmKind> = (record: CrmRecords[K], raw: CrmRaw, service: {
161
+ call: ServiceApiCall;
162
+ }) => CrmRecords[K] | Promise<CrmRecords[K]>;
163
+ /** Code a service needs beyond what the manifest says. */
164
+ export interface CrmManifestHooks {
165
+ /** Corrects one record after the map, such as a default the account keeps elsewhere. */
166
+ after?: {
167
+ readonly [K in CrmKind]?: CrmAfterHook<K>;
168
+ };
169
+ /** Adds or replaces source methods (`self`, `activities`, a live `list`); `base` is what the manifest built. */
170
+ extend?: (base: CrmSource) => Partial<CrmSource>;
171
+ }
172
+ /**
173
+ * The manifest checked against its shape and the generated API: each operation exists, a list pages or says where its
174
+ * rows are, a change call places `{since}`, a deal or lead kind has pipelines. Every error names where it is.
175
+ */
176
+ export declare const parseCrmManifest: (input: unknown, api: ServiceApiManifest) => CrmManifest;
@@ -0,0 +1,156 @@
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({ from: path, also: v.optional(v.array(v.string())) })),
38
+ map: v.record(v.string(), rule),
39
+ custom: v.optional(v.strictObject({ from: path, split: v.optional(v.string()) })),
40
+ });
41
+ const pipelines = v.strictObject({
42
+ call,
43
+ map: v.strictObject({ externalId: rule, name: rule }),
44
+ stages: v.strictObject({
45
+ each: path,
46
+ map: v.strictObject({ externalId: rule, name: rule, position: v.optional(rule) }),
47
+ outcome: v.union([
48
+ v.strictObject({ path, won: v.optional(v.array(v.string())), lost: v.optional(v.array(v.string())) }),
49
+ v.strictObject({ value: v.picklist(STAGE_OUTCOMES) }),
50
+ v.function(),
51
+ ]),
52
+ }),
53
+ });
54
+ const fields = v.strictObject({
55
+ call,
56
+ map: v.strictObject({
57
+ code: rule,
58
+ label: v.optional(rule),
59
+ type: v.optional(rule),
60
+ multiple: v.optional(rule),
61
+ filterable: v.optional(rule),
62
+ options: v.optional(v.union([v.strictObject({ each: path, id: path, label: path }), v.function()])),
63
+ }),
64
+ keep: v.optional(v.function()),
65
+ });
66
+ const kind = v.picklist(CRM_KINDS);
67
+ const schema = v.strictObject({
68
+ provider: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]*$/, "a registry name such as hubspot")),
69
+ kinds: v.pipe(v.array(kind), v.minLength(1)),
70
+ overlapMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
71
+ entities: v.record(kind, v.optional(entity)),
72
+ pipelines: v.optional(v.record(v.picklist(DEAL_KINDS), v.optional(pipelines))),
73
+ fields: v.optional(v.record(kind, v.optional(fields))),
74
+ users: v.optional(v.strictObject({
75
+ call,
76
+ map: v.strictObject({
77
+ externalId: rule,
78
+ name: v.optional(rule),
79
+ email: v.optional(rule),
80
+ position: v.optional(rule),
81
+ active: v.optional(rule),
82
+ }),
83
+ })),
84
+ });
85
+ const invalid = (where, message) => new CliError("configuration_error", `source manifest: ${where}: ${message}`, { reason: "manifest.invalid" });
86
+ /** The known name a typo most likely meant: at most two edits away, else none. */
87
+ const nearest = (wanted, known) => known
88
+ .map((one) => ({ one, edits: editDistance(wanted, one, 2) }))
89
+ .filter(({ edits }) => edits <= 2)
90
+ .sort((a, b) => a.edits - b.edits)[0]?.one;
91
+ const hasPlaceholder = (value, placeholder) => value === placeholder ||
92
+ (Array.isArray(value) && value.some((one) => hasPlaceholder(one, placeholder))) ||
93
+ (typeof value === "object" && value !== null && Object.values(value).some((one) => hasPlaceholder(one, placeholder)));
94
+ /**
95
+ * The manifest checked against its shape and the generated API: each operation exists, a list pages or says where its
96
+ * rows are, a change call places `{since}`, a deal or lead kind has pipelines. Every error names where it is.
97
+ */
98
+ export const parseCrmManifest = (input, api) => {
99
+ const parsed = v.safeParse(schema, input);
100
+ if (!parsed.success) {
101
+ const [issue] = parsed.issues;
102
+ throw invalid(v.getDotPath(issue) ?? "(root)", issue.message);
103
+ }
104
+ const manifest = parsed.output;
105
+ const operations = new Map(api.operations.map((one) => [one.id, one]));
106
+ const known = [...operations.keys()];
107
+ const checkCall = (where, one, pages) => {
108
+ const operation = operations.get(one.operation);
109
+ if (!operation) {
110
+ const near = nearest(one.operation, known);
111
+ throw invalid(`${where}.operation`, `no operation ${one.operation} in the API${near ? `; did you mean ${near}?` : ""}`);
112
+ }
113
+ if (operation.effect !== "read")
114
+ throw invalid(`${where}.operation`, `${one.operation} is a ${operation.effect}, and a source only reads`);
115
+ if (pages && operation.pagination?.style === "link")
116
+ throw invalid(`${where}.operation`, `${one.operation} pages by a link, which a source does not read yet`);
117
+ };
118
+ for (const kind of manifest.kinds) {
119
+ const one = manifest.entities[kind];
120
+ if (!one)
121
+ throw invalid(`entities.${kind}`, `${kind} is in kinds but has no entity`);
122
+ checkCall(`entities.${kind}.list`, one.list, true);
123
+ if (one.changes) {
124
+ checkCall(`entities.${kind}.changes`, one.changes, true);
125
+ if (!hasPlaceholder([one.changes.path, one.changes.query, one.changes.body], "{since}"))
126
+ throw invalid(`entities.${kind}.changes`, 'no "{since}" in its path, query or body');
127
+ }
128
+ if (one.ids)
129
+ checkCall(`entities.${kind}.ids`, one.ids, true);
130
+ if (one.get) {
131
+ checkCall(`entities.${kind}.get`, one.get, false);
132
+ if (!hasPlaceholder([one.get.path, one.get.query, one.get.body], "{id}"))
133
+ throw invalid(`entities.${kind}.get`, 'no "{id}" in its path, query or body');
134
+ }
135
+ if (one.map.externalId === undefined)
136
+ throw invalid(`entities.${kind}.map.externalId`, "every kind maps its id");
137
+ const fields = [...Object.keys(FIELDS[kind]), "amount", "currency"];
138
+ for (const field of Object.keys(one.map))
139
+ if (!fields.includes(field)) {
140
+ const near = nearest(field, fields);
141
+ throw invalid(`entities.${kind}.map.${field}`, `${kind} has no such field${near ? `; did you mean ${near}?` : ""}`);
142
+ }
143
+ }
144
+ for (const kind of DEAL_KINDS.filter((one) => manifest.kinds.includes(one))) {
145
+ const one = manifest.pipelines?.[kind];
146
+ if (!one)
147
+ throw invalid(`pipelines.${kind}`, `${kind} is in kinds, and every deal or lead stands in a pipeline`);
148
+ checkCall(`pipelines.${kind}.call`, one.call, true);
149
+ }
150
+ for (const [kind, one] of Object.entries(manifest.fields ?? {}))
151
+ if (one)
152
+ checkCall(`fields.${kind}.call`, one.call, true);
153
+ if (manifest.users)
154
+ checkCall("users.call", manifest.users.call, true);
155
+ return manifest;
156
+ };
@@ -0,0 +1,53 @@
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
+ /** The names under `from` that the rules read: what a service that names its returned fields is asked for. */
52
+ export declare const selectedOf: (rules: Readonly<Record<string, CrmRule | undefined>>, from: string) => string[];
53
+ export {};
@@ -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;