conduyt 1.61.0 → 1.63.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/README.md CHANGED
@@ -32,15 +32,28 @@ The saved config lives at `~/.conduyt/config.json` and is written owner-only (`c
32
32
  ```bash
33
33
  conduyt whoami # show the authenticated user
34
34
  conduyt contacts list --limit 25 # list contacts (supports --cursor, --query)
35
- conduyt contacts get <id> # fetch one contact
35
+ conduyt contacts get <id> # fetch one contact (carries `revision`)
36
+ conduyt contacts update <id> --first Ann --expected-revision <n> # PATCH; a contact changed since revision n is refused: 409 contact_changed, exit 1, code and current revision printed
37
+ conduyt contacts collaborators add <contactId> <userId> [--expected-revision <n>] # POST /contacts/{id}/collaborators; prints { added, revision }
38
+ conduyt contacts collaborators remove <contactId> <userId> [--expected-revision <n>] # DELETE with a body; prints { removed, revision }; 404 when not a collaborator
36
39
  conduyt deals list --pipeline <id> # list deals
37
40
  conduyt deals list --health-summary --pipeline <id> # Pipeline health strip for the filtered set (totalOpenDeals, atRiskValue, checks[]); add --health-check stale --health-limit 20 for one check's deals, --health-cursor <nextCursor> to page, --health-rows-only for just the page
38
41
  conduyt deals health --pipeline <id> --check needs_action # GET /deals/inspection: the six checks over open deals; --check adds its deals, --cursor/--offset pages
39
42
  conduyt deals card-fields set value,contact,custom:next_contact_at # the kanban card fields (1-8, built-ins or custom:<fieldKey>); `card-fields get` reads them
40
- conduyt pipelines stage-rules set <pipelineId> <stageId> --required-fields contactId,custom:loan_amount --required-documents 2 # what a deal needs to enter the stage; other stages untouched; `stage-rules get [pipelineId] [stageId]` reads
43
+ conduyt pipelines stage-rules set <pipelineId> <stageId> --required-fields contactId,custom:loan_amount --required-documents 2 [--lost-reason-allow-other true] # what a deal needs to enter the stage; other stages untouched; `stage-rules get [pipelineId] [stageId]` reads
41
44
  conduyt deals bulk-update --file updates.json # update up to 100 deals at once ([{id, stageId, value, ...}]); per-item results, exit 1 if any failed
42
- conduyt pipelines # list pipelines and stages
43
- conduyt pipelines update <id> --automation-only true # only automations, API keys and owners / admins move or edit its cards (owner / admin key)
45
+ conduyt pipelines # list pipelines and stages (each carries color, automationOnly, sortOrder)
46
+ conduyt pipelines list --archived # the archived pipelines (owner / admin key): name, archivedName, openDeals, stageCount
47
+ conduyt pipelines archive <id> --move-open-deals-to <pipelineId|none> [--expected-settings-revision N] # archive + move the open deals in one transaction; refusals print their code (stale_settings_revision, target_not_open, dpp_post_close, archive_too_large, target_archived, intake_target, pipeline_archived) and exit 1
48
+ conduyt pipelines settings-revision # the account settingsRevision to pass as --expected-settings-revision to archive / delete-stage (409 stale_settings_revision when settings changed since)
49
+ conduyt pipelines restore <id> # bring an archived pipeline back (last in the menu, never the default; 409 name_taken)
50
+ conduyt pipelines reorder --order id1,id2 --expected-revision id1,id2 # board-menu order in one transaction (409 order_changed prints the current revision); `reorder-stages <pipelineId>` does the same for a pipeline's columns
51
+ conduyt pipelines delete-stage <pipelineId> <stageId> [--move-to <stageId>] [--expected-settings-revision N] # move the live deals to another stage and delete this one; a stale revision is 409 stale_settings_revision
52
+ conduyt pipelines rot-days set <pipelineId> 21 # days without activity (1-90) before a deal reads "Stale in stage"; `rot-days get [pipelineId]` reads
53
+ conduyt status-metadata list --stage-id <id> # the status codes + buckets attached to stages; `get | create | update | delete | import` (update / delete take --expected-updated-at; 409 metadata_changed)
54
+ conduyt status-metadata import --file rows.json --mode replace # set-based import (max 1000; an item key outside stageId, code, bucket, lifecycleStage, dripEligible, dripTrackName, isTerminal, notes is refused before any request); per-item errors print and exit 1; `--mode replace` with no items is refused unless `--confirm-empty-replace` (it deletes every row). Timeouts: archive 75 s, import and the Mailchimp write / action commands 60 s; on a timeout the server may have applied it, so read the state first
55
+ conduyt integrations mailchimp settings # the Mailchimp audience sync (API key scope integrations); `set | audiences | push | retry-unsubscribes | reconcile-statuses [--restart] | confirm-reconciliation`. Connecting is browser-only (OAuth): do it in the app
56
+ conduyt pipelines update <id> --automation-only true # only automations, API keys and owners / admins move or edit its cards (owner / admin key); also --color <palette hex> and --sort-order
44
57
  conduyt search "acme corp" # search across the CRM
45
58
  conduyt insights summary # run an AI insight query
46
59
  conduyt insights saved_report --report "Lead Activity" --period last_7_days # run any saved report as a tool
@@ -11,7 +11,7 @@ export const MAX_STAGE_REQUIRED_FIELDS = 25;
11
11
  export const MAX_STAGE_REQUIRED_DOCUMENTS = 20;
12
12
  export const MAX_LOST_REASON_OPTIONS = 50;
13
13
  const CUSTOM_FIELD_RE = /^custom:[a-zA-Z_][a-zA-Z0-9_]*$/;
14
- export const RULE_KEYS = ["requiredFields", "requiredDocuments", "lostReasonLabel", "lostReasonOptions"];
14
+ export const RULE_KEYS = ["requiredFields", "requiredDocuments", "lostReasonLabel", "lostReasonOptions", "lostReasonAllowOther"];
15
15
  const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
16
16
  /** "a,b,custom:x" → ["a","b","custom:x"]; blank items are dropped, an all-blank value is an empty list */
17
17
  export function splitList(raw) {
@@ -64,6 +64,11 @@ export function validateRuleChange(raw) {
64
64
  throw new Error("lostReasonLabel must be 1-60 characters.");
65
65
  out[k] = t;
66
66
  }
67
+ else if (k === "lostReasonAllowOther") {
68
+ if (typeof v !== "boolean")
69
+ throw new Error("lostReasonAllowOther must be true or false.");
70
+ out[k] = v;
71
+ }
67
72
  else {
68
73
  if (!Array.isArray(v) || v.some((o) => typeof o !== "string"))
69
74
  throw new Error("lostReasonOptions must be a list of strings.");
package/dist/client.js CHANGED
@@ -1,4 +1,12 @@
1
1
  import { requireAuth } from "./config.js";
2
+ /** A deadline hit (only when the call set one) is "the server may have applied it", for every method: read the state first. */
3
+ function ambiguousTimeout(err, method, path, timeoutMs, what) {
4
+ const name = err?.name;
5
+ if (timeoutMs !== undefined && (name === "TimeoutError" || name === "AbortError")) {
6
+ return new Error(`Conduyt API timeout: ${what} within ${timeoutMs / 1000}s for ${method} ${path}. The server may have applied it: read the current state before repeating it.`);
7
+ }
8
+ return err;
9
+ }
2
10
  export class ConduytClient {
3
11
  baseUrl;
4
12
  apiKey;
@@ -7,17 +15,34 @@ export class ConduytClient {
7
15
  this.baseUrl = cfg.apiUrl.replace(/\/+$/, "");
8
16
  this.apiKey = cfg.apiKey;
9
17
  }
10
- async request(method, path, body) {
18
+ /** timeoutMs: a per-call deadline for the routes whose server budget is long (archive 75 s, Mailchimp admin and
19
+ * status-metadata import 60 s). Without it the request has no client-side deadline. A call that hits it may still have
20
+ * been applied by the server, and the error says so. */
21
+ async request(method, path, body, opts) {
11
22
  const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
12
- const res = await fetch(url, {
13
- method,
14
- headers: {
15
- Authorization: `Bearer ${this.apiKey}`,
16
- "Content-Type": "application/json",
17
- },
18
- body: body !== undefined ? JSON.stringify(body) : undefined,
19
- });
20
- const text = await res.text();
23
+ let res;
24
+ try {
25
+ res = await fetch(url, {
26
+ method,
27
+ headers: {
28
+ Authorization: `Bearer ${this.apiKey}`,
29
+ "Content-Type": "application/json",
30
+ },
31
+ body: body !== undefined ? JSON.stringify(body) : undefined,
32
+ ...(opts?.timeoutMs !== undefined ? { signal: AbortSignal.timeout(opts.timeoutMs) } : {}),
33
+ });
34
+ }
35
+ catch (err) {
36
+ throw ambiguousTimeout(err, method, path, opts?.timeoutMs, "no answer");
37
+ }
38
+ // the headers can arrive and the body then stall until the deadline: the same ambiguity, not a raw TimeoutError
39
+ let text;
40
+ try {
41
+ text = await res.text();
42
+ }
43
+ catch (err) {
44
+ throw ambiguousTimeout(err, method, path, opts?.timeoutMs, "the response body did not finish");
45
+ }
21
46
  const json = text ? safeParse(text) : null;
22
47
  if (!res.ok) {
23
48
  // Preserve structured non-2xx bodies: several endpoints return the data
@@ -32,7 +57,14 @@ export class ConduytClient {
32
57
  // STAGE_REQUIREMENTS 422 carries lostReasonOptions) keep the context —
33
58
  // same principle as `structured` above, bounded against huge bodies.
34
59
  if (json && typeof json === "object" && json.error) {
35
- const extras = Object.fromEntries(Object.entries(json).filter(([k]) => k !== "error"));
60
+ // Scalars first (code, revision), nested objects last: a 409 contact_changed also carries the whole current
61
+ // `contact`, and the bound below may cut that, never the code or the current revision.
62
+ const isScalar = (v) => v === null || typeof v !== "object";
63
+ const entries = Object.entries(json).filter(([k]) => k !== "error");
64
+ const extras = Object.fromEntries([
65
+ ...entries.filter(([, v]) => isScalar(v)),
66
+ ...entries.filter(([, v]) => !isScalar(v)),
67
+ ]);
36
68
  if (Object.keys(extras).length > 0) {
37
69
  msg = `${msg} ${JSON.stringify(extras).slice(0, 1000)}`;
38
70
  }
@@ -44,17 +76,18 @@ export class ConduytClient {
44
76
  get(path) {
45
77
  return this.request("GET", path);
46
78
  }
47
- post(path, body) {
48
- return this.request("POST", path, body);
79
+ post(path, body, opts) {
80
+ return this.request("POST", path, body, opts);
49
81
  }
50
82
  patch(path, body) {
51
83
  return this.request("PATCH", path, body);
52
84
  }
53
- put(path, body) {
54
- return this.request("PUT", path, body);
85
+ put(path, body, opts) {
86
+ return this.request("PUT", path, body, opts);
55
87
  }
56
- del(path) {
57
- return this.request("DELETE", path);
88
+ /** `body` is for the few DELETE routes that take one (contact collaborators with an --expected-revision pin). */
89
+ del(path, body) {
90
+ return this.request("DELETE", path, body);
58
91
  }
59
92
  /** A POST whose body comes back as text (a CSV or XLSX export), not JSON. */
60
93
  async postText(path, body) {
package/dist/index.js CHANGED
@@ -6,8 +6,11 @@ import { dirname, join } from "node:path";
6
6
  import { Command } from "commander";
7
7
  import { ConduytClient, buildQuery } from "./client.js";
8
8
  import { splitList, stageRulePatch, validateCardFields, validateRuleChange } from "./board-settings.js";
9
+ import { ARCHIVE_PIPELINE_TIMEOUT_MS, MAILCHIMP_ADMIN_TIMEOUT_MS, STATUS_METADATA_IMPORT_TIMEOUT_MS, PIPELINE_COLORS, boolFlag, intFlag, isoDate, lifecycleStage as lifecycleStageArg, MAX_PIPELINE_ROT_DAYS, MIN_PIPELINE_ROT_DAYS, pipelineColor, settingsRevision, slug as slugArg, uuid as uuidOf, uuidList, validateImportItems, validateStatusMetadataBody } from "./pipeline-settings.js";
9
10
  import { saveConfig, resolveConfig, configPath } from "./config.js";
10
11
  import { print, fail, unwrap } from "./output.js";
12
+ /** the contact save revision bound (catalog: integer 0..2147483647) */
13
+ const CONTACT_REVISION_MAX = 2147483647;
11
14
  // Exit cleanly when a downstream pipe closes early (e.g. `conduyt deals list |
12
15
  // head`). Without this, the stdout write after the reader is gone throws an
13
16
  // unhandled EPIPE and prints a Node stack trace — broken-pipe is normal Unix
@@ -76,7 +79,7 @@ contacts
76
79
  .action(run(async (client, opts) => client.get(`/api/v1/contacts${buildQuery({ limit: opts.limit, cursor: opts.cursor, query: opts.query, master_status: opts.masterStatus, exclude_master_status: opts.excludeMasterStatus })}`)));
77
80
  contacts
78
81
  .command("get <id>")
79
- .description("Get a single contact by id")
82
+ .description("Get a single contact by id (includes `revision`: pass it as --expected-revision on `contacts update` / `contacts collaborators`)")
80
83
  .action(run(async (client, id) => client.get(`/api/v1/contacts/${encodeURIComponent(id)}`)));
81
84
  contacts
82
85
  .command("create")
@@ -134,10 +137,13 @@ contacts
134
137
  .option("--company <company>", "company name (auto-creates/links a company; pass '' to clear)")
135
138
  .option("--source <source>", "correct the lead's first-touch source (normally set once at creation — update only to fix bad attribution; pass 'null' to clear)")
136
139
  .option("--master-status <status>", "lead lifecycle status: open|won|lost|abandoned|disqualified or an account custom (terminal statuses silence all outbound automation)")
140
+ .option("--expected-revision <n>", "the contact's `revision` as you read it (contacts get / list; 0-2147483647): a contact changed since is refused with 409 contact_changed, nothing is written, exit 1 with the code and the current revision printed")
137
141
  .option("--json <json>", "full JSON body, merged over the flags above (for any field)")
138
142
  .action(run(async (client, id, opts) => {
139
143
  assertUuid(id, "contact id");
140
144
  const body = {};
145
+ if (opts.expectedRevision !== undefined)
146
+ body.expectedRevision = intFlag(opts.expectedRevision, "--expected-revision", 0, CONTACT_REVISION_MAX);
141
147
  if (opts.first !== undefined)
142
148
  body.firstName = opts.first;
143
149
  if (opts.last !== undefined)
@@ -174,6 +180,25 @@ contacts
174
180
  assertContactSource(body.source, { allowNull: true });
175
181
  return client.patch(`/api/v1/contacts/${encodeURIComponent(id)}`, body);
176
182
  }));
183
+ const collaborators = contacts.command("collaborators").description("Team members collaborating on a contact");
184
+ for (const [verb, method] of [["add", "post"], ["remove", "del"]]) {
185
+ collaborators
186
+ .command(`${verb} <contactId> <userId>`)
187
+ .description(verb === "add"
188
+ ? "Add a team member as a collaborator (POST /contacts/{id}/collaborators; needs edit authority). Prints { added, revision } with the contact's NEW revision. A stale --expected-revision is 409 contact_changed (exit 1, code and current revision printed); 409 without a code: already a collaborator"
189
+ : "Remove a collaborator (DELETE /contacts/{id}/collaborators with a body; needs edit authority). Prints { removed, revision } with the contact's NEW revision. A stale --expected-revision is 409 contact_changed (exit 1, code and current revision printed); 404 when the user is not a collaborator")
190
+ .option("--expected-revision <n>", "the contact's `revision` as you read it (0-2147483647); omit for no pin")
191
+ .action(run(async (client, contactId, userId, opts) => {
192
+ assertUuid(contactId, "contact id");
193
+ if (userId.trim() === "")
194
+ throw new Error("userId must not be blank.");
195
+ const body = { userId };
196
+ if (opts.expectedRevision !== undefined)
197
+ body.expectedRevision = intFlag(opts.expectedRevision, "--expected-revision", 0, CONTACT_REVISION_MAX);
198
+ const path = `/api/v1/contacts/${encodeURIComponent(contactId)}/collaborators`;
199
+ return method === "post" ? client.post(path, body) : client.del(path, body);
200
+ }));
201
+ }
177
202
  contacts
178
203
  .command("delete <id>")
179
204
  .description("Delete a contact by id (soft-delete; retained for audit, the contact's deals are unaffected)")
@@ -758,18 +783,22 @@ const pipelines = program
758
783
  .action(run(async (client) => client.get("/api/v1/pipelines")));
759
784
  pipelines
760
785
  .command("list")
761
- .description("List pipelines and their stages")
762
- .action(run(async (client) => client.get("/api/v1/pipelines")));
786
+ .description("List pipelines and their stages (each pipeline carries color, automationOnly, sortOrder). --archived lists the ARCHIVED pipelines instead (owner / admin key): id, name (the pre-archive name), archivedName, color, archivedAt, openDeals, stageCount")
787
+ .option("--archived", "list the archived pipelines (GET /pipelines?archived=true) instead of the active ones")
788
+ .action(run(async (client, opts) => client.get(opts.archived ? "/api/v1/pipelines?archived=true" : "/api/v1/pipelines")));
763
789
  pipelines
764
790
  .command("create")
765
791
  .description("Create a pipeline with stages")
766
792
  .option("--name <name>", "pipeline name")
767
793
  .option("--stages <json>", "JSON array of stages, e.g. '[{\"name\":\"Lead\"},{\"name\":\"Won\",\"isWon\":true}]'")
794
+ .option("--color <hex>", `pipeline colour, one of the palette: ${PIPELINE_COLORS.join(" ")}`)
768
795
  .option("--json <json>", "full JSON body, merged over the flags")
769
796
  .action(run(async (client, opts) => {
770
797
  const body = {};
771
798
  if (opts.name !== undefined)
772
799
  body.name = opts.name;
800
+ if (opts.color !== undefined)
801
+ body.color = pipelineColor(opts.color);
773
802
  if (opts.stages !== undefined) {
774
803
  if (opts.stages.trim() === "")
775
804
  throw new Error("--stages must be valid JSON (got an empty string).");
@@ -803,6 +832,7 @@ pipelines
803
832
  .option("--is-default <bool>", "true|false: the account's default pipeline")
804
833
  .option("--automation-only <bool>", "true|false: only automations, API keys and owners / admins move or edit its cards")
805
834
  .option("--sort-order <n>", "position among the pipelines (integer)")
835
+ .option("--color <hex>", `pipeline colour, one of the palette: ${PIPELINE_COLORS.join(" ")}`)
806
836
  .option("--json <json>", "full JSON body, merged over the flags")
807
837
  .action(run(async (client, id, opts) => {
808
838
  assertUuid(id, "pipeline id");
@@ -841,6 +871,8 @@ pipelines
841
871
  throw new Error("--sort-order must be an integer.");
842
872
  body.sortOrder = n;
843
873
  }
874
+ if (opts.color !== undefined && unlessJson("color"))
875
+ body.color = pipelineColor(opts.color);
844
876
  Object.assign(body, fromJson);
845
877
  if (Object.keys(body).length === 0)
846
878
  throw new Error("Nothing to update. Pass at least one field flag or --json.");
@@ -853,7 +885,7 @@ const stageRules = pipelines
853
885
  .description("Per-stage rules (settings.pipelineStageRules): the fields and documents a deal needs before it may enter a stage");
854
886
  stageRules
855
887
  .command("get [pipelineId] [stageId]")
856
- .description("Read the stage rules as { pipelineId: { stageId: { requiredFields, requiredDocuments, lostReasonLabel, lostReasonOptions } } }, for everything, one pipeline, or one stage")
888
+ .description("Read the stage rules as { pipelineId: { stageId: { requiredFields, requiredDocuments, lostReasonLabel, lostReasonOptions, lostReasonAllowOther } } }, for everything, one pipeline, or one stage")
857
889
  .action(run(async (client, pipelineId, stageId) => {
858
890
  if (pipelineId !== undefined)
859
891
  assertUuid(pipelineId, "pipeline id");
@@ -876,7 +908,8 @@ stageRules
876
908
  .option("--required-documents <n>", "integer 0-20")
877
909
  .option("--lost-reason-label <text>", "label of the stage's lost-reason prompt (1-60 chars)")
878
910
  .option("--lost-reason-options <list>", "comma-separated dropdown options of the lost-reason prompt (max 50; empty clears)")
879
- .option("--json <json>", "the rule fields as a JSON object ({requiredFields, requiredDocuments, lostReasonLabel, lostReasonOptions}), merged over the flags")
911
+ .option("--lost-reason-allow-other <bool>", "true|false: the rep may also pick \"Other\" and type the reason (stored as the reason text; takes effect while the stage has lost-reason options)")
912
+ .option("--json <json>", "the rule fields as a JSON object ({requiredFields, requiredDocuments, lostReasonLabel, lostReasonOptions, lostReasonAllowOther}), merged over the flags")
880
913
  .action(run(async (client, pipelineId, stageId, opts) => {
881
914
  assertUuid(pipelineId, "pipeline id");
882
915
  assertUuid(stageId, "stage id");
@@ -891,11 +924,13 @@ stageRules
891
924
  raw.lostReasonLabel = opts.lostReasonLabel;
892
925
  if (opts.lostReasonOptions !== undefined)
893
926
  raw.lostReasonOptions = splitList(opts.lostReasonOptions);
927
+ if (opts.lostReasonAllowOther !== undefined)
928
+ raw.lostReasonAllowOther = boolFlag(opts.lostReasonAllowOther, "--lost-reason-allow-other");
894
929
  if (opts.json !== undefined)
895
930
  Object.assign(raw, jsonArg(opts.json, "--json"));
896
931
  const change = validateRuleChange(raw);
897
932
  if (Object.keys(change).length === 0)
898
- throw new Error("Nothing to set. Pass --required-fields, --required-documents, --lost-reason-label, --lost-reason-options or --json.");
933
+ throw new Error("Nothing to set. Pass --required-fields, --required-documents, --lost-reason-label, --lost-reason-options, --lost-reason-allow-other or --json.");
899
934
  return patchGeneralSettingsMerged(client, (settings) => stageRulePatch(settings, pipelineId, stageId, change));
900
935
  }));
901
936
  // (system stages 2026-09-24) tri-surface parity: the stage flags the API takes on PATCH /pipelines/:id/stages/:stageId,
@@ -951,6 +986,245 @@ pipelines
951
986
  throw new Error("Nothing to update. Pass at least one field flag or --json.");
952
987
  return client.patch(`/api/v1/pipelines/${encodeURIComponent(pipelineId)}/stages/${encodeURIComponent(stageId)}`, body);
953
988
  }));
989
+ // (pipeline settings 10-08) archive / restore / reorder, stage delete with a move, the stale-in-stage days.
990
+ pipelines
991
+ .command("archive <id>")
992
+ .description("Archive a pipeline (owner / admin key): renamed with the archived prefix, never deleted; its closed deals stay as history and `pipelines restore` brings it back. Every OPEN deal moves in the same transaction to --move-open-deals-to's first stage through the normal stage-entry rules; any refusal aborts all of it. Pass --move-open-deals-to none only when there are no open deals. Waits up to 75 s; if it times out the archive may have committed, so run `pipelines list` / `pipelines list --archived` before retrying. The default pipeline cannot be archived. Refusal codes are printed with the error and the command exits 1: stale_settings_revision, target_not_open, dpp_post_close, archive_too_large, target_archived, intake_target, pipeline_archived, open_deals, default_pipeline, stage_requirements, archive_raced, pipeline_automation_only. An already-archived pipeline answers { archived: true, alreadyArchived: true }")
993
+ .requiredOption("--move-open-deals-to <pipelineId|none>", "the active pipeline the open deals move to (its first stage must be open), or none when the pipeline has no open deals")
994
+ .option("--expected-settings-revision <n>", "the settingsRevision from `pipelines settings-revision`; refused 409 stale_settings_revision when settings changed since")
995
+ .action(run(async (client, id, opts) => {
996
+ const pid = uuidOf(id, "pipeline id");
997
+ const target = opts.moveOpenDealsTo.trim().toLowerCase();
998
+ const moveOpenDealsTo = target === "none" ? null : uuidOf(opts.moveOpenDealsTo, "--move-open-deals-to");
999
+ const body = { moveOpenDealsTo };
1000
+ if (opts.expectedSettingsRevision !== undefined)
1001
+ body.expectedSettingsRevision = settingsRevision(opts.expectedSettingsRevision);
1002
+ return client.post(`/api/v1/pipelines/${pid}/archive`, body, { timeoutMs: ARCHIVE_PIPELINE_TIMEOUT_MS });
1003
+ }));
1004
+ pipelines
1005
+ .command("restore <id>")
1006
+ .description("Restore an ARCHIVED pipeline (owner / admin key): it loses the archived prefix, goes last in the board menu and is never the default; its stages and closed deals come back with it. 404 when it is not an archived pipeline of this account; 409 name_taken when an active pipeline has its name (rename that one first); 403 PLAN_LIMIT_REACHED when the plan's pipeline limit is full")
1007
+ .action(run(async (client, id) => client.post(`/api/v1/pipelines/${uuidOf(id, "pipeline id")}/restore`, {})));
1008
+ pipelines
1009
+ .command("reorder")
1010
+ .description("Set the board-menu order of the active pipelines in one transaction (owner / admin key). --order must list EVERY active pipeline exactly once; --expected-revision is the order you last read (the pipeline ids by position, comma-joined). 409 order_changed (with the current revision) when the order moved since; nothing is written. Prints { order, revision }")
1011
+ .requiredOption("--order <ids>", "comma-separated pipeline ids in the new order")
1012
+ .requiredOption("--expected-revision <revision>", "the current order: the pipeline ids by position, comma-joined")
1013
+ .action(run(async (client, opts) => {
1014
+ const order = uuidList(opts.order, "--order");
1015
+ if (opts.expectedRevision.trim() === "")
1016
+ throw new Error("--expected-revision must be the current order (the pipeline ids by position, comma-joined).");
1017
+ return client.post("/api/v1/pipelines/reorder", { order, expectedRevision: opts.expectedRevision.trim().toLowerCase() });
1018
+ }));
1019
+ pipelines
1020
+ .command("reorder-stages <pipelineId>")
1021
+ .description("Set a pipeline's column order in one transaction (owner / admin key). --order must list EVERY stage of the pipeline exactly once and may not put a system holding stage first that was not first; --expected-revision is the stage ids by position, comma-joined. 409 order_changed (with the current revision) when it moved since, 409 pipeline_archived when the pipeline was archived meanwhile. Prints { order, revision }")
1022
+ .requiredOption("--order <ids>", "comma-separated stage ids in the new order")
1023
+ .requiredOption("--expected-revision <revision>", "the current order: the stage ids by position, comma-joined")
1024
+ .action(run(async (client, pipelineId, opts) => {
1025
+ const pid = uuidOf(pipelineId, "pipeline id");
1026
+ const order = uuidList(opts.order, "--order");
1027
+ if (opts.expectedRevision.trim() === "")
1028
+ throw new Error("--expected-revision must be the current order (the stage ids by position, comma-joined).");
1029
+ return client.post(`/api/v1/pipelines/${pid}/stages/reorder`, { order, expectedRevision: opts.expectedRevision.trim().toLowerCase() });
1030
+ }));
1031
+ pipelines
1032
+ .command("delete-stage <pipelineId> <stageId>")
1033
+ .description("Delete a stage (owner / admin key). Without --move-to the stage must have no deals; with it the live deals move to another stage of the SAME pipeline (same won / lost setting, not a system stage) and the stage is deleted in one transaction. A stage a soft-deleted deal still points at is refused. With --expected-settings-revision the answer is { id, deleted: true, settingsRevision }. Refusals exit 1 with the code printed: stale_settings_revision, pipeline_archived, intake_target (other 409s name the cause)")
1034
+ .option("--move-to <stageId>", "another stage of the same pipeline the live deals move to")
1035
+ .option("--expected-settings-revision <n>", "the settingsRevision from `pipelines settings-revision`; refused 409 stale_settings_revision when settings changed since")
1036
+ .action(run(async (client, pipelineId, stageId, opts) => {
1037
+ const qs = new URLSearchParams();
1038
+ if (opts.moveTo !== undefined)
1039
+ qs.set("move_to", uuidOf(opts.moveTo, "--move-to"));
1040
+ if (opts.expectedSettingsRevision !== undefined)
1041
+ qs.set("expected_settings_revision", settingsRevision(opts.expectedSettingsRevision));
1042
+ const q = qs.toString();
1043
+ const res = await client.del(`/api/v1/pipelines/${uuidOf(pipelineId, "pipeline id")}/stages/${uuidOf(stageId, "stage id")}${q ? `?${q}` : ""}`);
1044
+ return res ?? { data: { deleted: true, id: stageId } };
1045
+ }));
1046
+ pipelines
1047
+ .command("settings-revision")
1048
+ .description("The account settingsRevision (plus the stored stage rules and rot days): pass it as --expected-settings-revision to `pipelines archive` / `pipelines delete-stage` so they are refused (409 stale_settings_revision) when settings changed after you read it. Read it right before the mutation")
1049
+ .action(run(async (client) => {
1050
+ const res = (await client.get("/api/v1/settings"));
1051
+ const d = res?.data ?? {};
1052
+ return { data: { settingsRevision: typeof d.settingsRevision === "string" ? d.settingsRevision : null, pipelineStageRules: d.pipelineStageRules ?? null, pipelineRotDays: d.pipelineRotDays ?? null } };
1053
+ }));
1054
+ // settings.pipelineRotDays: days without activity before a deal reads "Stale in stage" (per pipeline, 1-90)
1055
+ const rotDays = pipelines
1056
+ .command("rot-days")
1057
+ .description("Stale-in-stage threshold per pipeline (settings.pipelineRotDays): days without activity (1-90) before a deal reads \"Stale in stage\"");
1058
+ rotDays
1059
+ .command("get [pipelineId]")
1060
+ .description("Read the thresholds as { pipelineId: days }, for every pipeline that has one or just the one given")
1061
+ .action(run(async (client, pipelineId) => {
1062
+ const pid = pipelineId === undefined ? undefined : uuidOf(pipelineId, "pipeline id");
1063
+ const res = (await client.get("/api/v1/settings"));
1064
+ const all = res?.data?.pipelineRotDays && typeof res.data.pipelineRotDays === "object" ? res.data.pipelineRotDays : {};
1065
+ return { data: { pipelineRotDays: pid === undefined ? all : all[pid] !== undefined ? { [pid]: all[pid] } : {} } };
1066
+ }));
1067
+ rotDays
1068
+ .command("set <pipelineId> <days>")
1069
+ .description(`Set one pipeline's threshold (admin key, settings:edit): an integer ${MIN_PIPELINE_ROT_DAYS}-${MAX_PIPELINE_ROT_DAYS}. Only that pipeline changes. The pipeline must be an ACTIVE pipeline of the account (422 for an unknown or archived one). Saved with the settings revision; a 409 is re-read and retried once`)
1070
+ .action(run(async (client, pipelineId, days) => {
1071
+ const pid = uuidOf(pipelineId, "pipeline id");
1072
+ const n = intFlag(days, "days", MIN_PIPELINE_ROT_DAYS, MAX_PIPELINE_ROT_DAYS);
1073
+ return patchGeneralSettingsMerged(client, () => ({ pipelineRotDays: { [pid]: n } }));
1074
+ }));
1075
+ // ---- status metadata (app 10-08): the status taxonomy rows attached to a pipeline stage ----
1076
+ const statusMetadata = program
1077
+ .command("status-metadata")
1078
+ .description("Status metadata: the status codes and buckets attached to pipeline stages (one row per stage and code). update / delete take --expected-updated-at (the row's updatedAt as read): 409 metadata_changed (with the current row) when it changed or moved since, 404 status_metadata_not_found");
1079
+ statusMetadata
1080
+ .command("list")
1081
+ .description("List the rows (settings:view); updatedAt is the version for --expected-updated-at")
1082
+ .option("--stage-id <id>", "only this stage's rows")
1083
+ .option("--bucket <bucket>", "only this bucket")
1084
+ .option("--code <code>", "only this code")
1085
+ .action(run(async (client, opts) => client.get(`/api/v1/status-metadata${buildQuery({ stageId: opts.stageId === undefined ? undefined : uuidOf(opts.stageId, "--stage-id"), bucket: opts.bucket, code: opts.code })}`)));
1086
+ statusMetadata
1087
+ .command("get <id>")
1088
+ .description("One row with its stage and drip track")
1089
+ .action(run(async (client, id) => client.get(`/api/v1/status-metadata/${uuidOf(id, "id")}`)));
1090
+ /** the row fields shared by create and update; "null" clears a nullable one */
1091
+ function statusMetadataFields(opts) {
1092
+ const body = {};
1093
+ if (opts.stageId !== undefined)
1094
+ body.stageId = uuidOf(opts.stageId, "--stage-id");
1095
+ if (opts.code !== undefined)
1096
+ body.code = slugArg(opts.code, "--code");
1097
+ if (opts.bucket !== undefined)
1098
+ body.bucket = slugArg(opts.bucket, "--bucket");
1099
+ if (opts.lifecycleStage !== undefined)
1100
+ body.lifecycleStage = opts.lifecycleStage === "null" ? null : lifecycleStageArg(opts.lifecycleStage);
1101
+ if (opts.dripEligible !== undefined)
1102
+ body.dripEligible = boolFlag(opts.dripEligible, "--drip-eligible");
1103
+ if (opts.dripTrackId !== undefined)
1104
+ body.dripTrackId = opts.dripTrackId === "null" ? null : uuidOf(opts.dripTrackId, "--drip-track-id");
1105
+ if (opts.isTerminal !== undefined)
1106
+ body.isTerminal = boolFlag(opts.isTerminal, "--is-terminal");
1107
+ if (opts.notes !== undefined) {
1108
+ if (opts.notes !== "null" && opts.notes.length > 5000)
1109
+ throw new Error("--notes must be at most 5000 characters.");
1110
+ body.notes = opts.notes === "null" ? null : opts.notes;
1111
+ }
1112
+ return body;
1113
+ }
1114
+ statusMetadata
1115
+ .command("create")
1116
+ .description("Create a row (settings:edit, active billing). --code and --bucket are lowercase slugs (letters, numbers, underscores, max 80); one row per stage and code (a duplicate is a 409)")
1117
+ .requiredOption("--stage-id <id>", "pipeline stage the row attaches to")
1118
+ .requiredOption("--code <slug>", "status code, e.g. appt_set")
1119
+ .requiredOption("--bucket <slug>", "bucket, e.g. working")
1120
+ .option("--lifecycle-stage <stage>", `one of ${["pre_sale", "sale", "underwriting", "active", "resolution", "terminal"].join(", ")}, or null`)
1121
+ .option("--drip-eligible <bool>", "true|false")
1122
+ .option("--drip-track-id <id>", "drip track id, or null")
1123
+ .option("--is-terminal <bool>", "true|false")
1124
+ .option("--notes <text>", "free text (max 5000), or null")
1125
+ .option("--json <json>", "full JSON body, merged over the flags")
1126
+ .action(run(async (client, opts) => {
1127
+ const body = statusMetadataFields(opts);
1128
+ if (opts.json !== undefined)
1129
+ Object.assign(body, jsonArg(opts.json, "--json"));
1130
+ // flags + --json together, against the exact field list and types: the API ignores a misspelled key and applies the rest
1131
+ return client.post("/api/v1/status-metadata", validateStatusMetadataBody(body, "create"));
1132
+ }));
1133
+ statusMetadata
1134
+ .command("update <id>")
1135
+ .description("Update a row (settings:edit, active billing): only the fields you pass change. --expected-updated-at refuses the update when the row was changed or moved since you read it (409 metadata_changed, the current row is in the error)")
1136
+ .option("--expected-updated-at <iso>", "the row's updatedAt as you read it")
1137
+ .option("--stage-id <id>", "move the row to another stage")
1138
+ .option("--code <slug>", "status code")
1139
+ .option("--bucket <slug>", "bucket")
1140
+ .option("--lifecycle-stage <stage>", "lifecycle stage, or null")
1141
+ .option("--drip-eligible <bool>", "true|false")
1142
+ .option("--drip-track-id <id>", "drip track id, or null")
1143
+ .option("--is-terminal <bool>", "true|false")
1144
+ .option("--notes <text>", "free text (max 5000), or null")
1145
+ .option("--json <json>", "full JSON body, merged over the flags")
1146
+ .action(run(async (client, id, opts) => {
1147
+ const rowId = uuidOf(id, "id");
1148
+ const body = statusMetadataFields(opts);
1149
+ if (opts.expectedUpdatedAt !== undefined)
1150
+ body.expectedUpdatedAt = isoDate(opts.expectedUpdatedAt, "--expected-updated-at");
1151
+ if (opts.json !== undefined)
1152
+ Object.assign(body, jsonArg(opts.json, "--json"));
1153
+ validateStatusMetadataBody(body, "update");
1154
+ if (Object.keys(body).filter((k) => k !== "expectedUpdatedAt").length === 0)
1155
+ throw new Error("Nothing to update. Pass at least one field flag or --json.");
1156
+ return client.patch(`/api/v1/status-metadata/${rowId}`, body);
1157
+ }));
1158
+ statusMetadata
1159
+ .command("delete <id>")
1160
+ .description("Delete a row (settings:edit, active billing). --expected-updated-at refuses the delete when the row changed or moved since you read it (409 metadata_changed)")
1161
+ .option("--expected-updated-at <iso>", "the row's updatedAt as you read it")
1162
+ .action(run(async (client, id, opts) => {
1163
+ const rowId = uuidOf(id, "id");
1164
+ const q = opts.expectedUpdatedAt === undefined ? "" : `?expected_updated_at=${encodeURIComponent(isoDate(opts.expectedUpdatedAt, "--expected-updated-at"))}`;
1165
+ const res = await client.del(`/api/v1/status-metadata/${rowId}${q}`);
1166
+ return res ?? { data: { deleted: true, id: rowId } };
1167
+ }));
1168
+ statusMetadata
1169
+ .command("import")
1170
+ .description(`Set-based import (owner / admin key, active billing; max 1000 items) from a JSON array of { stageId, code, bucket, lifecycleStage?, dripEligible?, dripTrackName?, isTerminal?, notes? } via --items or --file. merge (default) upserts the valid items and reports the rest in errors[]; replace replaces the rows of the ACTIVE pipelines and imports nothing if any item is invalid (rows of archived pipelines are kept). With --mode replace and NO items nothing is sent unless --confirm-empty-replace is given (it would delete every row). Prints { imported, skipped, errors } and exits 1 when errors is not empty (the full result is still printed). 409 pipeline_archived when an item names a stage of an archived pipeline`)
1171
+ .option("--mode <mode>", "merge (default) | replace")
1172
+ .option("--items <json>", "the items as a JSON array (or @file)")
1173
+ .option("--file <path>", "read the items JSON array from a file")
1174
+ .option("--confirm-empty-replace", "allow --mode replace with NO items, which deletes every status metadata row of the active pipelines")
1175
+ .action(async (opts) => {
1176
+ try {
1177
+ if (opts.items !== undefined && opts.file !== undefined)
1178
+ throw new Error("Pass either --items or --file, not both.");
1179
+ if (opts.mode !== undefined && opts.mode !== "merge" && opts.mode !== "replace")
1180
+ throw new Error("--mode must be merge or replace.");
1181
+ let raw;
1182
+ if (opts.file !== undefined) {
1183
+ try {
1184
+ raw = readFileSync(opts.file, "utf8");
1185
+ }
1186
+ catch {
1187
+ throw new Error(`--file could not be read: ${opts.file}`);
1188
+ }
1189
+ }
1190
+ else if (opts.items !== undefined) {
1191
+ raw = opts.items.startsWith("@") ? readFileSync(opts.items.slice(1), "utf8") : opts.items;
1192
+ }
1193
+ else {
1194
+ throw new Error("The items are required. Pass --items '<json array>' or --file <path>.");
1195
+ }
1196
+ let parsed;
1197
+ try {
1198
+ parsed = JSON.parse(raw);
1199
+ }
1200
+ catch {
1201
+ throw new Error("The items must be valid JSON.");
1202
+ }
1203
+ const items = validateImportItems(parsed);
1204
+ // checked before any request; the flag is only a local confirmation and is never sent
1205
+ if (opts.mode === "replace" && items.length === 0 && !opts.confirmEmptyReplace) {
1206
+ throw new Error("replace with no items would delete every status metadata row; pass --confirm-empty-replace to do that on purpose");
1207
+ }
1208
+ const client = new ConduytClient();
1209
+ const res = await client.post("/api/v1/status-metadata/import", { ...(opts.mode !== undefined ? { mode: opts.mode } : {}), items }, { timeoutMs: STATUS_METADATA_IMPORT_TIMEOUT_MS });
1210
+ print(res);
1211
+ // a 200 can still carry per-item errors (merge) or a refused replace (imported 0): that is a refusal, exit 1
1212
+ const data = unwrap(res);
1213
+ if (!data || typeof data !== "object" || typeof data.imported !== "number" || !Array.isArray(data.errors)) {
1214
+ process.stderr.write("Error: Unexpected response shape from the API: expected { imported, skipped, errors }.\n");
1215
+ process.exitCode = 1;
1216
+ }
1217
+ else if (data.errors.length > 0) {
1218
+ for (const e of data.errors)
1219
+ process.stderr.write(`Skipped ${String(e?.stageId ?? "?")}: ${String(e?.reason ?? "unknown reason")}\n`);
1220
+ process.stderr.write(`Error: ${data.errors.length} item(s) were not imported (${data.imported} imported).\n`);
1221
+ process.exitCode = 1;
1222
+ }
1223
+ }
1224
+ catch (err) {
1225
+ fail(err);
1226
+ }
1227
+ });
954
1228
  // ---- search ----
955
1229
  program
956
1230
  .command("search <query>")
@@ -2473,6 +2747,69 @@ wordpressForms
2473
2747
  .command("revoke <id>")
2474
2748
  .description("Revoke an intake address: submissions to it answer 404 from now on. The row is kept (status revoked) for history")
2475
2749
  .action(run(async (client, id) => client.del(`/api/v1/integrations/wordpress-forms/intakes/${uuidArg(id, "id")}`)));
2750
+ // Integrations -> Mailchimp (app 10-07/10-08, API key scope `integrations`): the audience sync. The OAuth connect and
2751
+ // callback are browser-only (connect Mailchimp in the app: Settings > Integrations), so there is no `connect` here.
2752
+ const mailchimp = integrations
2753
+ .command("mailchimp")
2754
+ .description("Mailchimp audience sync (API key scope integrations). Connecting is browser-only (OAuth): do it in the app, then configure it here. Errors exit 1 with the server's message and code (404 not connected, 409 revoked: reconnect in the app)");
2755
+ mailchimp
2756
+ .command("settings")
2757
+ .description("The Mailchimp connection: the audience, the source (one smart list or one tag), statusIfNew, unsubscribeSetsOptOut and the sync status (backfill progress, pending pushes, last pushed, last webhook, the last Mailchimp error, statusSweepBlocked). connected: false when there is none")
2758
+ .action(run(async (client) => client.get("/api/v1/integrations/mailchimp/settings")));
2759
+ mailchimp
2760
+ .command("set")
2761
+ .description("Configure the sync (PUT; settings:edit, active billing): only the flags you pass change. A new audience gets Conduyt's webhook and starts the backfill; a new source starts the backfill. --source-type and --source-id go together")
2762
+ .option("--list-id <id>", "Mailchimp audience id (see `audiences`)")
2763
+ .option("--source-type <type>", "smart_list | tag")
2764
+ .option("--source-id <id>", "the smart list or tag UUID")
2765
+ .option("--status-if-new <status>", "subscribed (default) | pending (Mailchimp sends a confirmation email)")
2766
+ .option("--unsubscribe-sets-opt-out <bool>", "true|false (default true): a Mailchimp unsubscribe also opts the contact out of Conduyt email")
2767
+ .action(run(async (client, opts) => {
2768
+ const body = {};
2769
+ if (opts.listId !== undefined) {
2770
+ if (opts.listId.trim() === "")
2771
+ throw new Error("--list-id was provided but is blank.");
2772
+ body.listId = opts.listId.trim();
2773
+ }
2774
+ if ((opts.sourceType === undefined) !== (opts.sourceId === undefined))
2775
+ throw new Error("--source-type and --source-id go together.");
2776
+ if (opts.sourceType !== undefined) {
2777
+ if (opts.sourceType !== "smart_list" && opts.sourceType !== "tag")
2778
+ throw new Error('--source-type must be "smart_list" or "tag".');
2779
+ body.source = { type: opts.sourceType, id: uuidOf(opts.sourceId, "--source-id") };
2780
+ }
2781
+ if (opts.statusIfNew !== undefined) {
2782
+ if (opts.statusIfNew !== "subscribed" && opts.statusIfNew !== "pending")
2783
+ throw new Error('--status-if-new must be "subscribed" or "pending".');
2784
+ body.statusIfNew = opts.statusIfNew;
2785
+ }
2786
+ if (opts.unsubscribeSetsOptOut !== undefined)
2787
+ body.unsubscribeSetsOptOut = boolFlag(opts.unsubscribeSetsOptOut, "--unsubscribe-sets-opt-out");
2788
+ if (Object.keys(body).length === 0)
2789
+ throw new Error("Nothing to set. Pass --list-id, --source-type with --source-id, --status-if-new or --unsubscribe-sets-opt-out.");
2790
+ return client.put("/api/v1/integrations/mailchimp/settings", body, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS });
2791
+ }));
2792
+ mailchimp
2793
+ .command("audiences")
2794
+ .description("The connected account's audiences: id, name, memberCount (use an id as --list-id)")
2795
+ .action(run(async (client) => client.get("/api/v1/integrations/mailchimp/audiences")));
2796
+ mailchimp
2797
+ .command("push")
2798
+ .description("Run one sync pass now instead of waiting for the next minute (settings:edit, active billing): queue the contacts newly in the source, take a backfill step, send due pushes. Waits up to 60 s (if it times out the server may have applied it: read `settings`). Prints { ran, result, settings }; ran false means another pass holds the connection or Mailchimp asked to slow down")
2799
+ .action(run(async (client) => client.post("/api/v1/integrations/mailchimp/push", {}, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS })));
2800
+ mailchimp
2801
+ .command("retry-unsubscribes")
2802
+ .description("Try again, in one pass now, the unsubscribes Conduyt could not deliver to Mailchimp (also retried daily). Prints { ran, pending, delivered, undelivered, result, settings }; pending true = nothing was tried. One retry per account per 10 minutes: otherwise exit 1 with 429 retry_cooldown")
2803
+ .action(run(async (client) => client.post("/api/v1/integrations/mailchimp/unsubscribes/retry", {}, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS })));
2804
+ mailchimp
2805
+ .command("reconcile-statuses")
2806
+ .description("Full reconciliation when Conduyt's check of Mailchimp's unsubscribes is blocked (statusSweepBlocked in `settings`; owner / admin key): reads every member Mailchimp shows as unsubscribed or cleaned up to the blocked second and applies them (it only ever OPTS OUT), then records a report; it never resumes the check on its own, review the report and run `confirm-reconciliation`. Starts or resumes the run and runs one pass: repeat until done is true. --restart replaces a completed run's report with a new run; without it a completed run exits 1 with 409 reconciliation_completed")
2807
+ .option("--restart", "replace a completed run's report with a new run")
2808
+ .action(run(async (client, opts) => client.post("/api/v1/integrations/mailchimp/reconcile-statuses", opts.restart ? { restart: true } : {}, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS })));
2809
+ mailchimp
2810
+ .command("confirm-reconciliation")
2811
+ .description("Confirm the completed reconciliation's report and resume the unsubscribe check after the blocked second (owner / admin key; audited with the report's counts). 409 when nothing is blocked, a reconciliation is still running, or none completed since the block began")
2812
+ .action(run(async (client) => client.post("/api/v1/integrations/mailchimp/confirm-reconciliation", {}, { timeoutMs: MAILCHIMP_ADMIN_TIMEOUT_MS })));
2476
2813
  // ---------------------------------------------------------------------------
2477
2814
  // Sequences (one model for Email and SMS since 2026-09-30): steps send saved templates of the sequence's channel a
2478
2815
  // number of days apart inside a send window; a run stops on a reply, a booked meeting, an opt-out, a closed deal or a
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Pipeline settings release (app 10-08), status metadata and Mailchimp: the validators the commands run before any
3
+ * request. They mirror the API (the source of truth) so a bad value fails locally with the same words; the API still
4
+ * re-checks everything and its refusal codes are printed with the error.
5
+ */
6
+ export const PIPELINE_COLORS = ["#3845C9", "#43DFF6", "#2DD6B5", "#22C58B", "#9BD13B", "#F2B544", "#F07A2F", "#E6465A", "#FD88C0", "#956EFA"];
7
+ export const LIFECYCLE_STAGES = ["pre_sale", "sale", "underwriting", "active", "resolution", "terminal"];
8
+ export const MAX_STATUS_METADATA_IMPORT = 1000;
9
+ /** per-call deadlines above the server budgets (archive tx 60 s; Mailchimp admin 60 s; import tx 20 s plus locks) */
10
+ export const ARCHIVE_PIPELINE_TIMEOUT_MS = 75_000;
11
+ export const MAILCHIMP_ADMIN_TIMEOUT_MS = 60_000;
12
+ export const STATUS_METADATA_IMPORT_TIMEOUT_MS = 60_000;
13
+ /** the exact fields an import item takes; anything else (a misspelled isTerminal, say) would be dropped by the API and stored as defaults */
14
+ export const IMPORT_ITEM_KEYS = ["stageId", "code", "bucket", "lifecycleStage", "dripEligible", "dripTrackName", "isTerminal", "notes"];
15
+ export const MIN_PIPELINE_ROT_DAYS = 1;
16
+ export const MAX_PIPELINE_ROT_DAYS = 90;
17
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
+ const SLUG_RE = /^[a-z0-9][a-z0-9_]{0,79}$/;
19
+ const SETTINGS_REVISION_RE = /^\d+$/;
20
+ export const isUuid = (v) => typeof v === "string" && UUID_RE.test(v.trim());
21
+ export function uuid(raw, name) {
22
+ if (!isUuid(raw))
23
+ throw new Error(`${name} must be a UUID.`);
24
+ return raw.trim().toLowerCase();
25
+ }
26
+ /** true | false (any case) */
27
+ export function boolFlag(raw, name) {
28
+ const v = raw.trim().toLowerCase();
29
+ if (v === "true")
30
+ return true;
31
+ if (v === "false")
32
+ return false;
33
+ throw new Error(`${name} must be true or false.`);
34
+ }
35
+ export function intFlag(raw, name, min, max) {
36
+ const t = raw.trim();
37
+ const n = Number(t);
38
+ if (t === "" || !Number.isInteger(n) || n < min || n > max)
39
+ throw new Error(`${name} must be an integer ${min}-${max}.`);
40
+ return n;
41
+ }
42
+ /** A pipeline colour is one of the 10 palette colours (case-insensitive); the API answers 400 for anything else. */
43
+ export function pipelineColor(raw, name = "--color") {
44
+ const upper = raw.trim().toUpperCase();
45
+ const hit = PIPELINE_COLORS.find((c) => c === upper);
46
+ if (!hit)
47
+ throw new Error(`${name} must be one of the pipeline palette colours: ${PIPELINE_COLORS.join(", ")}.`);
48
+ return hit;
49
+ }
50
+ /** The settingsRevision a settings-backed write was read at: digits only (the API's pattern). */
51
+ export function settingsRevision(raw, name = "--expected-settings-revision") {
52
+ const t = raw.trim();
53
+ if (!SETTINGS_REVISION_RE.test(t))
54
+ throw new Error(`${name} must be the settingsRevision you read (digits only).`);
55
+ return t;
56
+ }
57
+ /** An ISO date (the row's updatedAt as read); the API answers 400 for anything else. */
58
+ export function isoDate(raw, name) {
59
+ const t = raw.trim();
60
+ if (t === "" || Number.isNaN(new Date(t).getTime()))
61
+ throw new Error(`${name} must be the updatedAt you read (an ISO date).`);
62
+ return t;
63
+ }
64
+ export function slug(raw, name) {
65
+ if (!SLUG_RE.test(raw))
66
+ throw new Error(`${name} must be a lowercase machine slug using letters, numbers and underscores (max 80).`);
67
+ return raw;
68
+ }
69
+ export function lifecycleStage(raw, name = "--lifecycle-stage") {
70
+ if (!LIFECYCLE_STAGES.includes(raw))
71
+ throw new Error(`${name} must be one of: ${LIFECYCLE_STAGES.join(", ")}.`);
72
+ return raw;
73
+ }
74
+ /** A comma-separated order list of UUIDs, no duplicates. */
75
+ export function uuidList(raw, name) {
76
+ const ids = raw.split(",").map((s) => s.trim()).filter((s) => s !== "").map((s) => uuid(s, `${name} entry`));
77
+ if (ids.length === 0)
78
+ throw new Error(`${name} needs at least one id.`);
79
+ if (new Set(ids).size !== ids.length)
80
+ throw new Error(`${name} lists an id more than once.`);
81
+ return ids;
82
+ }
83
+ /** The fields of a status metadata row for create / update / get (a drip track is named by id); import names it by dripTrackName instead. */
84
+ export const ROW_FIELD_KEYS = IMPORT_ITEM_KEYS.map((k) => (k === "dripTrackName" ? "dripTrackId" : k));
85
+ /**
86
+ * THE one definition of a status metadata row's fields and types, shared by import items and the create / update bodies:
87
+ * unknown keys are refused naming the key (the API drops them and applies the rest of the call), and each present value is
88
+ * type-checked like the API does. `required`: stageId, code and bucket must be present. `trackKey` is the drip track field.
89
+ */
90
+ function checkRowFields(o, at, allowed, required, trackKey, what) {
91
+ for (const k of Object.keys(o)) {
92
+ if (!allowed.includes(k))
93
+ throw new Error(`${at}: unknown field "${k}". ${what} takes ${allowed.join(", ")}; nothing was sent.`);
94
+ }
95
+ const has = (k) => o[k] !== undefined;
96
+ if (required || has("stageId")) {
97
+ if (typeof o.stageId !== "string" || !isUuid(o.stageId))
98
+ throw new Error(`${at}.stageId must be a UUID.`);
99
+ }
100
+ for (const k of ["code", "bucket"]) {
101
+ if (required || has(k)) {
102
+ if (typeof o[k] !== "string")
103
+ throw new Error(`${at}.${k} must be a slug.`);
104
+ slug(o[k], `${at}.${k}`);
105
+ }
106
+ }
107
+ if (has("lifecycleStage") && o.lifecycleStage !== null) {
108
+ if (typeof o.lifecycleStage !== "string")
109
+ throw new Error(`${at}.lifecycleStage must be one of: ${LIFECYCLE_STAGES.join(", ")}, or null.`);
110
+ lifecycleStage(o.lifecycleStage, `${at}.lifecycleStage`);
111
+ }
112
+ if (has("dripEligible") && typeof o.dripEligible !== "boolean")
113
+ throw new Error(`${at}.dripEligible must be a boolean.`);
114
+ if (has("isTerminal") && typeof o.isTerminal !== "boolean")
115
+ throw new Error(`${at}.isTerminal must be a boolean.`);
116
+ if (has(trackKey) && o[trackKey] !== null) {
117
+ const v = o[trackKey];
118
+ if (typeof v !== "string")
119
+ throw new Error(`${at}.${trackKey} must be ${trackKey === "dripTrackId" ? "a UUID" : "a slug"} or null.`);
120
+ if (trackKey === "dripTrackId") {
121
+ if (!isUuid(v))
122
+ throw new Error(`${at}.dripTrackId must be a UUID or null.`);
123
+ }
124
+ else
125
+ slug(v, `${at}.dripTrackName`);
126
+ }
127
+ if (has("notes") && o.notes !== null && (typeof o.notes !== "string" || o.notes.trim().length > 5000))
128
+ throw new Error(`${at}.notes must be text of at most 5000 characters.`);
129
+ }
130
+ /** One status metadata item, as the import route takes it. */
131
+ export function validateImportItem(raw, index) {
132
+ const at = `items[${index}]`;
133
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
134
+ throw new Error(`${at} must be an object.`);
135
+ checkRowFields(raw, at, IMPORT_ITEM_KEYS, true, "dripTrackName", "An import item");
136
+ return raw;
137
+ }
138
+ /** The COMPLETE body of `status-metadata create` / `update` (flags + --json merged), checked before any request. */
139
+ export function validateStatusMetadataBody(body, mode) {
140
+ const allowed = mode === "update" ? [...ROW_FIELD_KEYS, "expectedUpdatedAt"] : ROW_FIELD_KEYS;
141
+ checkRowFields(body, "body", allowed, mode === "create", "dripTrackId", mode === "create" ? "A status metadata row" : "A status metadata update");
142
+ if (body.expectedUpdatedAt !== undefined) {
143
+ if (typeof body.expectedUpdatedAt !== "string")
144
+ throw new Error("body.expectedUpdatedAt must be the updatedAt you read (an ISO date).");
145
+ isoDate(body.expectedUpdatedAt, "body.expectedUpdatedAt");
146
+ }
147
+ return body;
148
+ }
149
+ export function validateImportItems(raw) {
150
+ if (!Array.isArray(raw))
151
+ throw new Error("items must be a JSON array.");
152
+ if (raw.length > MAX_STATUS_METADATA_IMPORT)
153
+ throw new Error(`items takes at most ${MAX_STATUS_METADATA_IMPORT} entries (got ${raw.length}).`);
154
+ return raw.map((item, i) => validateImportItem(item, i));
155
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conduyt",
3
- "version": "1.61.0",
3
+ "version": "1.63.0",
4
4
  "description": "Command-line interface for Conduyt CRM — manage contacts, deals, pipelines, and run insight queries from your terminal.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",