@koda-sl/baker-cli 0.863.0 → 0.865.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 +5 -3
- package/dist/{analytics-M4W62IFX.js → analytics-2JEGNTNZ.js} +2 -2
- package/dist/{chats-ZDCIXZVC.js → chats-UHN7JXOR.js} +2 -2
- package/dist/chats-UHN7JXOR.js.map +1 -0
- package/dist/{chunk-7TT2BHG5.js → chunk-NRU2A7TJ.js} +7 -3
- package/dist/chunk-NRU2A7TJ.js.map +1 -0
- package/dist/cli.js +3 -3
- package/dist/{hubspot-EQI27OIR.js → hubspot-72LKX7CR.js} +2 -2
- package/dist/{sources-EONNVSIV.js → sources-2TG66AZO.js} +10 -4
- package/dist/sources-2TG66AZO.js.map +1 -0
- package/package.json +1 -1
- package/dist/chats-ZDCIXZVC.js.map +0 -1
- package/dist/chunk-7TT2BHG5.js.map +0 -1
- package/dist/sources-EONNVSIV.js.map +0 -1
- /package/dist/{analytics-M4W62IFX.js.map → analytics-2JEGNTNZ.js.map} +0 -0
- /package/dist/{hubspot-EQI27OIR.js.map → hubspot-72LKX7CR.js.map} +0 -0
package/README.md
CHANGED
|
@@ -2171,7 +2171,7 @@ baker analytics sources --create-activecampaign --events subscribe,deal_update
|
|
|
2171
2171
|
|
|
2172
2172
|
**Sources: where events reach Baker from a server.** Measure → Sources is three built-in doors — the Baker landings, the website tag, and **the client's own server** — plus the connections Baker reads (HubSpot today). `--server` prints the server's one address: made once, the same for ever, `counting` at once, Baker's own format (`sending-events` is the contract; `X-Baker-Mode: test` rehearses). A HubSpot event is a trigger in HubSpot's own words, kept by HubSpot's journal each time the property changes and counted within a minute. `--create --name <tool>` still makes an address for a tool that cannot be told what to send — its first send is a masked sample counted as nothing until `--map` confirms the rows — but the dashboard no longer offers those; a tool worth reading is a connection, requested from the Sources page. Each `--field` is a **template**: text with `{{path}}` mentions, one thing per mention (`--field currency=EUR` types a value, `--field first_name="{{who.first}} {{who.last}}"` joins two; there is no `{{a|b}}` fallback); a bare path is read as its mention when the sample has it. From then on every arrival is an ordinary event carrying `baker_source: <name>`, listed by `feed --source <name>`, and `--pause`, `--resume` and `--remove` are by `--source <id>`.
|
|
2173
2173
|
|
|
2174
|
-
**`--preview` then `--create-hubspot --property <name> [--operator <op>] --value <value>… [--name <name>] [--field <field>=<template>…] [--amount-property <n> --currency <c>]`: a HubSpot event.** HubSpot keeps each change to the property for Baker, filtered to the condition — on any plan, nothing to set up in HubSpot, an account of any size — and every contact whose new value satisfies the condition is one event, within a minute, named after the source (default: the trigger's words). The condition is any a Form's filter can say, by the property's kind: `is` / `isNot` (a dropdown, `--value` repeated for several), `contains` / `startsWith` / `endsWith` (text), `greaterThan` / `lessThanOrEqual` … (numbers), `isAfter` / `isBetween` (dates, `YYYY-MM-DD`), `isEmpty` / `isNotEmpty` (any); `--operator` is `is` when unsaid. Names, kinds and operators come from `baker hubspot contacts properties` and row properties from `baker hubspot contacts fields`; `--preview --property … [--operator …] --value … [--field …] [--contact <id or email>]` says how many contacts satisfy it today (NOT counted — only contacts that come to satisfy it from now on are) and returns `preview.record`, the one most recently there or the one asked for, to check every row against before making anything. `--set-trigger --source <id> --property … [--operator …] --value …` changes what an event watches later: the rows stay and `countingSince` moves to now. The connection must be allowed to read contacts, and a refusal names the reconnect. `counting` at once, no URL; the source carries `hubspot { property, propertyLabel, kind, operator, values, valueLabels }`, `countingSince`, `listening` (whether HubSpot has been told to keep its changes: `listening`, `not_configured` or `failed`, with a `detail`), `lastError` and `mapping` — the same field → template table as an address, over the contact's properties plus `{{id}}`, defaulting to HubSpot's standard ones (email, phone, the contact id, name, address, `hs_google_click_id`, `hs_facebook_click_id`); a `--field` row at creation replaces the default it names, `--map --field` replaces the whole set later, and `--amount-property … --currency …` is the short spelling for the `value` and `currency` rows. `--field properties.<name>=<template>` adds an extra property of the event (`--field properties.plan={{plan_tier}}`): it breaks the event down on Measure → Events and a send reads it back as `{{properties.<name>}}`. A deal is watched the same way with `--object deal`, and a lead with `--object lead` (`baker hubspot leads properties|fields`) — where HubSpot records qualification and disqualification as the lead's stage. A deal's or a lead's event is about its contacts (`--contacts every|first`), read as `{{contact.<name>}}`; a lead has no amount. Leads need Sales Hub Professional or Enterprise. Where the event is sent on (Meta, Google Ads…) is `sends`, edited on the event's own card on the Sources page.
|
|
2174
|
+
**`--preview` then `--create-hubspot --property <name> [--operator <op>] --value <value>… [--name <name>] [--field <field>=<template>…] [--amount-property <n> --currency <c>]`: a HubSpot event.** HubSpot keeps each change to the property for Baker, filtered to the condition — on any plan, nothing to set up in HubSpot, an account of any size — and every contact whose new value satisfies the condition is one event, within a minute, named after the source (default: the trigger's words). The condition is any a Form's filter can say, by the property's kind: `is` / `isNot` (a dropdown, `--value` repeated for several), `contains` / `startsWith` / `endsWith` (text), `greaterThan` / `lessThanOrEqual` … (numbers), `isAfter` / `isBetween` (dates, `YYYY-MM-DD`), `isEmpty` / `isNotEmpty` (any); `--operator` is `is` when unsaid. Names, kinds and operators come from `baker hubspot contacts properties` and row properties from `baker hubspot contacts fields`; `--preview --property … [--operator …] --value … [--breakdown] [--field …] [--contact <id or email>]` says how many contacts satisfy it today (NOT counted — only contacts that come to satisfy it from now on are) — `--breakdown` adds `preview.counts`, a total for each `--value` of a dropdown `is`, in the same call — and returns `preview.record`, the one most recently there or the one asked for, to check every row against before making anything. `--set-trigger --source <id> --property … [--operator …] --value …` changes what an event watches later: the rows stay and `countingSince` moves to now. The connection must be allowed to read contacts, and a refusal names the reconnect. `counting` at once, no URL; the source carries `hubspot { property, propertyLabel, kind, operator, values, valueLabels }`, `countingSince`, `listening` (whether HubSpot has been told to keep its changes: `listening`, `not_configured` or `failed`, with a `detail`), `lastError` and `mapping` — the same field → template table as an address, over the contact's properties plus `{{id}}`, defaulting to HubSpot's standard ones (email, phone, the contact id, name, address, `hs_google_click_id`, `hs_facebook_click_id`); a `--field` row at creation replaces the default it names, `--map --field` replaces the whole set later, and `--amount-property … --currency …` is the short spelling for the `value` and `currency` rows. `--field properties.<name>=<template>` adds an extra property of the event (`--field properties.plan={{plan_tier}}`): it breaks the event down on Measure → Events and a send reads it back as `{{properties.<name>}}`. A deal is watched the same way with `--object deal`, and a lead with `--object lead` (`baker hubspot leads properties|fields`) — where HubSpot records qualification and disqualification as the lead's stage. A deal's or a lead's event is about its contacts (`--contacts every|first`), read as `{{contact.<name>}}`; a lead has no amount. Leads need Sales Hub Professional or Enterprise. Where the event is sent on (Meta, Google Ads…) is `sends`, edited on the event's own card on the Sources page.
|
|
2175
2175
|
|
|
2176
2176
|
Shared flags: `--days <n>` (default 30) or `--start-date` / `--end-date` (`YYYY-MM-DD`, end inclusive); `--full`; `--compare` to also return the preceding window of the same length; `--timezone <IANA>` and `--granularity hour|day|week|month` to shape a series. Every call reads live — there is no cache layer, so there is nothing to bypass.
|
|
2177
2177
|
|
|
@@ -5515,7 +5515,9 @@ baker chats list # other Sessions, newest first (all st
|
|
|
5515
5515
|
baker chats list --status active # only running Sessions
|
|
5516
5516
|
baker chats list --search "PMax Brasil" # Sessions whose title or conversation holds any of the words
|
|
5517
5517
|
baker chats view <id> # kickoff, outputs (changes), threads, commits
|
|
5518
|
-
baker chats transcript <id> --
|
|
5518
|
+
baker chats transcript <id> --turns --role user # what it was asked, request by request (a cheap recap)
|
|
5519
|
+
baker chats transcript <id> --turns --role assistant --limit 3 # how its last turns ended
|
|
5520
|
+
baker chats transcript <id> --search "<distinctive phrase>" --limit 1 --full # one message, verbatim
|
|
5519
5521
|
baker chats transcript --search "5.700" # this chat's own earlier messages holding the text
|
|
5520
5522
|
baker chats transcript --search lead --search GTM # messages holding any of them, in one call
|
|
5521
5523
|
baker chats view <id> --surface ads.google # one list: counted by kind and outcome, plus what did not apply
|
|
@@ -5529,7 +5531,7 @@ baker chats import --from-chat <id> --failed # a published Session's ad changes
|
|
|
5529
5531
|
**`list` flags:** `--status active|archived|all` (default `all`), `--limit` (1-100, default 20), `--full` (include each Session's full change list), `--search <words>` (Sessions whose title or conversation holds any of the words, newest first; each row carries the `match` it was found by).
|
|
5530
5532
|
**`view`:** returns the unified `effects` — git content (`content`, `creatives`) AND DB-only effects that never touch the repo (`actions`, `scheduledAgents`, `tags`, `ads.{google,meta,linkedin,x}`, `tagManager`, `ga4`, `shopify`, `activeCampaign`, `funnel` (with the ways in it added or removed, `triggersAdded`/`triggersRemoved`), `conversions`, `conversionSends`, `eventSources`), plus `otherChanges` for every other change the Session made (A/B tests, recipes, library images), each resolved to real detail and flagged `staged` (in-progress draft) vs applied. Plus `kickoff`, `outputs` counts, `threads`, `commits`, `diffAvailable`, and `publish` — what the Publish left behind (`failedTotal`) and the changes that went through but read back differently on the platform afterwards (`unconfirmedTotal`, `surfaces[].unconfirmedChanges`); a hint names either. Without `--full` each effect list shows at most 25 rows, and a list cut to fit is named in `truncated` (`list`, `shown`, `total`, and every row counted by `op`/`kind`/`outcome`); the chat's own timeline comes as `activitySummary` (`total`, `counts` by action, the `notable` rows — publish start/fail, status changes, recoveries, timeouts — and `capped: true` when the Session logged more than the newest 500 rows it counts). **Changed:** compact `view` no longer returns `activity`; `--full` returns it, with every effect row.
|
|
5531
5533
|
**`view` flags:** `--full` (every effect row and the whole `activity` timeline), `--surface <list>` (one list under `effects` — `content`, `actions`, `scheduledAgents`, `tags`, `ads.google|meta|linkedin|x|chatgpt`, `creatives`, `tagManager`, `ga4`, `shopify`, `activeCampaign`, `conversions`, `conversionSends`, `eventSources`, `siteSettings`, `otherChanges` — returned as `surface`: `total`, `counts` by `op`/`kind`/`outcome`, `notAppliedTotal` and the first 5 rows that did not apply in `notApplied`; with `--full`, all of them and every row in `rows`).
|
|
5532
|
-
**`transcript` flags:** no id reads this chat's own conversation; `--search <text>` (only messages holding it, case-insensitive, over the whole conversation; repeat it for any of several), `--role user|assistant`, `--turns` (each user message and the agent's closing message of that turn), `--limit` (1-1000, default 100, most recent), `--full` (untruncated text). Returns `entries` (`role` + `text`) and `truncated`.
|
|
5534
|
+
**`transcript` flags:** no id reads this chat's own conversation; `--search <text>` (only messages holding it, case-insensitive, over the whole conversation; repeat it for any of several), `--role user|assistant`, `--turns` (each user message and the agent's closing message of that turn), `--limit` (1-1000, default 100, most recent), `--full` (untruncated text — a whole chat verbatim runs to tens of KB, so pair it with `--search … --limit 1`; `--turns` alone still returns every closing reply, so recap with `--turns --role user`). Returns `entries` (`role` + `text`) and `truncated`.
|
|
5533
5535
|
**`diff` flags:** `--surface knowledge|company|brand|landings|flows|creatives`, `--full` (patch text per file), `--live` (read an in-progress Session's changes from its live workspace). The `/api/chats/diff` route also takes `gitPatch` with `live`, returning the whole change as one `git apply`-ready patch (binary files included) — what `import` applies. Returns `available`, `source` (`published`|`live`), `files` (`path`, `surface`, `status`, `additions`, `deletions`, `patch`), and `truncated` when a large live diff was capped.
|
|
5534
5536
|
|
|
5535
5537
|
**`import --from-chat <id> [--only <surfaces>] [--failed]`:** brings what another Session did and never published — open, its publish failed, or discarded — into this one (`BAKER_CHAT_ID`), exactly, and removes it from that Session, so publishing both can never apply a change twice. Its **file changes** are read from its workspace as one patch and applied here with `git apply` (all or none; a file both Sessions changed differently refuses the import and is named; a discarded Session's files are gone and the result says so). Every **staged surface** moves as staged — Google, Meta, LinkedIn, X and ChatGPT Ads, Shopify, Tag Manager, Google Analytics, tracking tags, Tasks, scheduled agents, ActiveCampaign, site settings, ad goals, the funnel, conversions, conversion sends, event sources and lead routes — or only those `--only` names (comma-separated, no files; surfaces whose changes name each other must be named together). A clash anywhere moves nothing, and the error names each one; when the staged move is refused, the applied files are taken back out. Returns `surfaces` (`surface`, `moved`, and `left: { count, reason }` for what stayed), `filesStayed`, and `carried` — the other Session (not an open one) held nothing more and can no longer be published. `--failed` takes a **published** Session instead: the Google Ads, Meta, LinkedIn, X and ChatGPT changes its publish could not apply (failed, or skipped behind a failure) are staged here as they were, naming a parent that did apply by its real id and renaming a temporary ref this chat already uses, and are removed from that Session so its Retry cannot apply them twice. A Session opened by a product running out of stock is refused: its ad pauses turn back on by themselves only when it publishes. To move only some Google Ads changes, use `baker ads google draft import --refs|--exclude`.
|
|
@@ -2770,7 +2770,7 @@ Full guide: __tooling__/docs/tools/baker/analytics.md`
|
|
|
2770
2770
|
tracking: trackingCommand,
|
|
2771
2771
|
arrivals: arrivalsCommand,
|
|
2772
2772
|
"sending-events": sendingEventsCommand,
|
|
2773
|
-
sources: () => import("./sources-
|
|
2773
|
+
sources: () => import("./sources-2TG66AZO.js").then((m) => m.sourcesCommand),
|
|
2774
2774
|
"website-tag": websiteTagCommand,
|
|
2775
2775
|
debug: debugCommand,
|
|
2776
2776
|
sites: sitesCommand,
|
|
@@ -2789,4 +2789,4 @@ export {
|
|
|
2789
2789
|
requestBody,
|
|
2790
2790
|
sendingEventsAddress
|
|
2791
2791
|
};
|
|
2792
|
-
//# sourceMappingURL=analytics-
|
|
2792
|
+
//# sourceMappingURL=analytics-2JEGNTNZ.js.map
|
|
@@ -300,7 +300,7 @@ registerSchema({
|
|
|
300
300
|
command: "chats.transcript",
|
|
301
301
|
routes: ["POST /api/chats/transcript"],
|
|
302
302
|
effect: "read",
|
|
303
|
-
description:
|
|
303
|
+
description: 'Start here: read a Session\'s conversation (user + agent turns), the most recent messages last. Leave out the id to read THIS chat \u2014 the way to recover its own earlier words after a context summary (never grep the raw logs on disk). `--search "5.700"` returns only the messages holding the text, from the whole conversation however long \u2014 repeat it for several (`--search lead --search GTM`: the messages holding any of them, in one call, never a loop); `--role user` keeps one side; `--turns` keeps each request and the agent\'s closing message of that turn (a recap). To recap an earlier Session, start with `--turns --role user` (its requests), then `--turns --role assistant --limit 3` or `--search` for how it went: `--turns` alone returns every closing reply. Compact truncates long messages (around the match when searching); add --full for verbatim text of one message found with `--search "<distinctive phrase>" --limit 1` \u2014 a whole chat verbatim runs to tens of KB. Read-only.',
|
|
304
304
|
args: {
|
|
305
305
|
id: {
|
|
306
306
|
type: "positional",
|
|
@@ -657,4 +657,4 @@ Full guide: __tooling__/docs/tools/baker/chats.md`
|
|
|
657
657
|
export {
|
|
658
658
|
chatsCommand
|
|
659
659
|
};
|
|
660
|
-
//# sourceMappingURL=chats-
|
|
660
|
+
//# sourceMappingURL=chats-UHN7JXOR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/chats/index.ts","../src/commands/chats/carry-files.ts","../src/commands/chats/publish-hints.ts"],"sourcesContent":["import type { ChatsDiffResponse, ChatsListResponse, ChatsTranscriptResponse, ChatsViewResponse } from \"@baker/api\";\nimport {\n CHAT_IMPORT_SURFACES,\n type ChatSurfaceDetail,\n type ChatsImportResponse,\n EFFECT_LISTS,\n type EffectList,\n} from \"@baker/api/chats\";\n\ntype ChatImportSurface = (typeof CHAT_IMPORT_SURFACES)[number];\n\nimport { defineCommand } from \"citty\";\nimport { apiPost } from \"../../client.ts\";\nimport { getEnv, requireChatId } from \"../../env.ts\";\nimport { repeatedValues } from \"../../lib/repeatedFlags.ts\";\nimport { rowsAsData, writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { failApi } from \"../actions/shared.ts\";\nimport { applyPatch, patchRefusal, readSourceFiles, revertPatch, type SourceFiles } from \"./carry-files.ts\";\nimport { publishHints, stillPublishingHints } from \"./publish-hints.ts\";\n\nconst STATUS_GROUPS = [\"active\", \"archived\", \"all\"] as const;\nconst REPO_SURFACES = [\"knowledge\", \"company\", \"brand\", \"landings\", \"flows\", \"creatives\"] as const;\n\nfunction parseBoundedInt(raw: string | undefined, name: string, min: number, max: number): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (Number.isNaN(value) || value < min || value > max) {\n throw new Error(`--${name} must be an integer between ${min} and ${max}`);\n }\n return value;\n}\n\nregisterSchema({\n command: \"chats.list\",\n description:\n 'Start here: list other Sessions on this account (newest first) so you can reuse what was done before. Each row shows the Session id, title, status, and a count of what it produced (creatives, landings, actions, flows, reports…). Looking for one? `--search \"PMax Brasil\"` finds the Sessions whose title or conversation holds any of the words, newest first, each with the `match` it was found by; read the match before trusting a row, since more words match more Sessions. Then drill in with `baker chats view <id>`, `baker chats transcript <id>`, or `baker chats diff <id>`. Read-only.',\n args: {\n status: { type: \"string\", description: \"Filter: active|archived|all (default: all)\", required: false },\n limit: { type: \"string\", description: \"Max Sessions to return, 1-100 (default: 20)\", required: false },\n full: { type: \"boolean\", description: \"Include each Session's full change list\", required: false, default: false },\n search: {\n type: \"string\",\n description:\n 'Sessions whose title or conversation holds any of these words, newest first, each with its `match` (e.g. --search \"PMax Brasil\")',\n required: false,\n },\n },\n});\n\nconst listCommand = defineCommand({\n meta: { name: \"list\", description: \"List other Sessions on this account, newest first.\" },\n args: {\n status: { type: \"string\", description: \"Filter: active|archived|all (default: all)\", required: false },\n limit: { type: \"string\", description: \"Max Sessions (1-100, default 20)\", required: false },\n full: { type: \"boolean\", description: \"Include each Session's full change list\", required: false, default: false },\n search: {\n type: \"string\",\n description: \"Sessions whose title or conversation holds any of these words\",\n required: false,\n },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = {};\n if (args.search) {\n body.search = args.search;\n }\n if (args.status) {\n if (!(STATUS_GROUPS as readonly string[]).includes(args.status)) {\n throw new Error(`--status must be one of: ${STATUS_GROUPS.join(\"|\")}`);\n }\n body.status = args.status;\n }\n const limit = parseBoundedInt(args.limit, \"limit\", 1, 100);\n if (limit !== undefined) {\n body.limit = limit;\n }\n if (args.full) {\n body.full = true;\n }\n // Exclude our own Session so we never list ourselves as a reusable \"other\".\n const selfChatId = getEnv().BAKER_CHAT_ID;\n if (selfChatId) {\n body.excludeChatId = selfChatId;\n }\n const response = await apiPost<ChatsListResponse>(\"/api/chats/list\", body);\n writeJson({\n ok: true,\n ...rowsAsData(response.data, \"chats\"),\n ...(response.data.chats.length === 0\n ? {\n hints: [\n args.search\n ? \"No Session's title or conversation holds any of those words. Try other words (a name, a figure), widen with --status all, or drop --search to list the newest.\"\n : \"No Sessions matched. Widen with --status all or a larger --limit.\",\n ],\n }\n : {\n hints: [\n \"Drill in: `baker chats view <id>` for outputs, `chats transcript <id>` for the conversation, `chats diff <id>` for the real file changes.\",\n ],\n }),\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nregisterSchema({\n command: \"chats.view\",\n routes: [\"POST /api/chats/view\"],\n effect: \"read\",\n description:\n \"Inspect one Session's FULL picture of what it changed — the unified `effects`: git content (landings, creatives, flows, knowledge, brand), plus DB-only effects that never touch the repo — Actions, Scheduled agents, Tags, Tag Manager, Google Analytics, ad-platform writes, the funnel (`funnel`: which steps it added, changed or removed, and which ways in it added or removed in `triggersAdded`/`triggersRemoved`), what counts as a conversion (`conversions`), conversion sends, event sources, and every other staged or already-applied change (`otherChanges`: A/B tests, recipes, library images) — each resolved to real detail (names, descriptions, priorities, tag types, ad operations) and, once published, its `outcome`. Also `publish` (what each external surface actually did, with the provider's own error), `activitySummary` (the chat's own timeline counted by action, with its notable rows: status changes, publish start/fail, workspace recoveries, timeouts; the rows whole as `activity` with --full), `usage` (per-thread cost and the Session's token totals), the kickoff (how it was asked), threads, and commits. Effects are `staged` (in-progress draft) or applied. Compact shows at most 25 rows per list; a list cut to fit is named in `truncated` with its total and every row counted by kind and outcome. `activitySummary.capped` true means the Session logged more than 500 timeline rows and the counts cover the newest 500. One surface: `--surface ads.google` returns only that list, every row counted by kind and outcome (`counts`) plus the first 5 rows that did not apply (`notApplied`: staged, failed, skipped, refused); add --full for all of its rows. A completed Session is NOT proof its external changes landed — read `publish`. Use after `baker chats list` to decide whether to reuse it. Read-only.\",\n args: {\n id: { type: \"positional\", description: \"The Session id (from `baker chats list`)\", required: true },\n full: {\n type: \"boolean\",\n description:\n \"Every effect row and the whole activity timeline (compact caps each list at 25 and counts the timeline)\",\n required: false,\n default: false,\n },\n surface: {\n type: \"string\",\n description: `One effect list only, counted by kind and outcome, with the rows that did not apply: ${EFFECT_LISTS.join(\"|\")}`,\n required: false,\n },\n },\n});\n\nfunction effectListArg(raw: string | undefined): EffectList | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const list = EFFECT_LISTS.find((name) => name === raw);\n if (!list) {\n throw new Error(`--surface must be one of: ${EFFECT_LISTS.join(\"|\")}`);\n }\n return list;\n}\n\nfunction surfaceHints(data: ChatSurfaceDetail, full: boolean): string[] {\n const { list, total, notApplied, notAppliedTotal } = data.surface;\n const hints: string[] = [];\n if (!full && notApplied.length < notAppliedTotal) {\n hints.push(\n `notApplied shows ${notApplied.length} of ${notAppliedTotal} rows that did not apply — \\`counts\\` has every one; read them all with \\`baker chats view <id> --surface ${list} --full\\`.`,\n );\n }\n if (!full && notApplied.length < total) {\n hints.push(\n `${list} shows ${notApplied.length} of its ${total} rows; read every row with \\`baker chats view <id> --surface ${list} --full\\`.`,\n );\n }\n hints.push(\"What each platform's Publish did overall, with its errors: `baker chats view <id> --fields publish`.\");\n return hints;\n}\n\nconst viewCommand = defineCommand({\n meta: {\n name: \"view\",\n description: \"Inspect one Session's full effects — git content + actions/tags/ads, kickoff, commits.\",\n },\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n full: { type: \"boolean\", description: \"Include full detail\", required: false, default: false },\n surface: { type: \"string\", description: \"One effect list only, e.g. ads.google\", required: false },\n },\n run: async ({ args }) => {\n try {\n const surface = effectListArg(args.surface);\n const response = await apiPost<ChatsViewResponse>(\"/api/chats/view\", {\n chatId: args.id,\n ...(args.full ? { full: true } : {}),\n ...(surface ? { surface } : {}),\n });\n if (\"surface\" in response.data) {\n writeJson({ ...response, hints: surfaceHints(response.data, args.full) });\n return;\n }\n const hints: string[] = response.data.publish ? publishHints(response.data.publish) : [];\n for (const cut of response.data.truncated ?? []) {\n hints.push(\n `effects.${cut.list} shows ${cut.shown} of ${cut.total} — \\`truncated\\` counts all ${cut.total} by kind and outcome; read that list alone with \\`baker chats view <id> --surface ${cut.list}\\`.`,\n );\n }\n if (response.data.activitySummary?.capped) {\n hints.push(\n \"activitySummary covers only the Session's newest 500 timeline rows: its total and counts leave the earlier ones out.\",\n );\n }\n if (response.data.diffAvailable) {\n hints.push(\"See the real file-level diff of the git content with `baker chats diff <id> --full`.\");\n } else if (response.data.status === \"in_progress\" || response.data.status === \"publishing\") {\n hints.push(\n \"This Session is still in progress — read its current file changes with `baker chats diff <id> --live`.\",\n );\n }\n hints.push(...stillPublishingHints(response.data.status));\n hints.push(\"Read the conversation with `baker chats transcript <id>`.\");\n writeJson({ ...response, hints });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nconst TRANSCRIPT_ROLES = [\"user\", \"assistant\"] as const;\n\n/** Every `--search` given (citty keeps only the last): one text as itself, several as a list matched as any of them. */\nfunction transcriptSearch(rawArgs: readonly string[], parsed: unknown): string | string[] | undefined {\n const texts = repeatedValues(rawArgs, \"search\", parsed).filter((text) => text.trim() !== \"\");\n return texts.length > 1 ? texts : texts[0];\n}\n\nregisterSchema({\n command: \"chats.transcript\",\n routes: [\"POST /api/chats/transcript\"],\n effect: \"read\",\n description:\n 'Start here: read a Session\\'s conversation (user + agent turns), the most recent messages last. Leave out the id to read THIS chat — the way to recover its own earlier words after a context summary (never grep the raw logs on disk). `--search \"5.700\"` returns only the messages holding the text, from the whole conversation however long — repeat it for several (`--search lead --search GTM`: the messages holding any of them, in one call, never a loop); `--role user` keeps one side; `--turns` keeps each request and the agent\\'s closing message of that turn (a recap). To recap an earlier Session, start with `--turns --role user` (its requests), then `--turns --role assistant --limit 3` or `--search` for how it went: `--turns` alone returns every closing reply. Compact truncates long messages (around the match when searching); add --full for verbatim text of one message found with `--search \"<distinctive phrase>\" --limit 1` — a whole chat verbatim runs to tens of KB. Read-only.',\n args: {\n id: {\n type: \"positional\",\n description: \"The Session id (from `baker chats list`). Default: this chat\",\n required: false,\n },\n search: {\n type: \"string\",\n description:\n 'Only messages containing this text, case-insensitive (e.g. --search \"5.700\"); repeat it for messages holding any of several (--search lead --search GTM)',\n required: false,\n },\n role: { type: \"string\", description: \"Only one side: user|assistant\", required: false },\n turns: {\n type: \"boolean\",\n description: \"Only each user message and the agent's closing message of that turn\",\n required: false,\n default: false,\n },\n limit: { type: \"string\", description: \"Max messages to return, 1-1000 (default: 100)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Return verbatim (untruncated) message text\",\n required: false,\n default: false,\n },\n },\n});\n\nconst transcriptCommand = defineCommand({\n meta: { name: \"transcript\", description: \"Read a Session's conversation — another one, or this chat's own.\" },\n args: {\n id: { type: \"positional\", description: \"The Session id (default: this chat)\", required: false },\n search: {\n type: \"string\",\n description: \"Only messages containing this text (repeatable: any of them)\",\n required: false,\n },\n role: { type: \"string\", description: \"Only one side: user|assistant\", required: false },\n turns: { type: \"boolean\", description: \"Each request + the closing reply\", required: false, default: false },\n limit: { type: \"string\", description: \"Max messages (1-1000, default 100)\", required: false },\n full: { type: \"boolean\", description: \"Verbatim message text\", required: false, default: false },\n },\n run: async ({ args, rawArgs }) => {\n try {\n // No id reads the caller's own chat, so its earlier words survive a context summary.\n const chatId = args.id ?? getEnv().BAKER_CHAT_ID;\n if (!chatId) {\n throw new Error(\"Pass the Session id: `baker chats transcript <id>` (find it with `baker chats list`).\");\n }\n const body: Record<string, unknown> = { chatId };\n const search = transcriptSearch(rawArgs, args.search);\n if (search !== undefined) body.search = search;\n if (args.role) {\n if (!(TRANSCRIPT_ROLES as readonly string[]).includes(args.role)) {\n throw new Error(`--role must be one of: ${TRANSCRIPT_ROLES.join(\"|\")}`);\n }\n body.role = args.role;\n }\n if (args.turns) {\n body.turns = true;\n }\n const limit = parseBoundedInt(args.limit, \"limit\", 1, 1000);\n if (limit !== undefined) {\n body.limit = limit;\n }\n if (args.full) {\n body.full = true;\n }\n const response = await apiPost<ChatsTranscriptResponse>(\"/api/chats/transcript\", body);\n const hints: string[] = [];\n if (response.data.truncated) {\n hints.push(\"Older messages were dropped to fit --limit. Raise --limit, or narrow with --search.\");\n }\n if (response.data.answersNotKept) {\n hints.push(\n \"A question card says `Answer no longer kept`: only the last 10 answers are kept, so no --limit brings it back. Read the user's reply from the messages after it.\",\n );\n }\n if (search !== undefined && response.data.entries.length === 0) {\n hints.push(\n \"No message holds that text. The whole conversation was searched — try a shorter or differently written piece of it.\",\n );\n }\n writeJson({ ...response, meta: { count: response.data.entries.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nregisterSchema({\n command: \"chats.diff\",\n description:\n \"See the real file-level changes a Session made (landings, creatives, brand, flows, knowledge). Published Sessions read from git; for an in-progress (unpublished) Session pass --live to read its changes straight from its running workspace. Without --live, an unpublished Session returns available:false — use `baker chats view` for the staged summary. Compact lists changed files with +/- counts; add --full for the actual diff text. Read-only.\",\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n surface: {\n type: \"string\",\n description: \"Filter to one surface: knowledge|company|brand|landings|flows|creatives\",\n required: false,\n },\n full: {\n type: \"boolean\",\n description: \"Include the unified-diff patch text per file\",\n required: false,\n default: false,\n },\n live: {\n type: \"boolean\",\n description:\n \"For an in-progress Session, read its changes from the live workspace (slower; resumes the paused Runtime). Ignored for published Sessions.\",\n required: false,\n default: false,\n },\n },\n});\n\nconst diffCommand = defineCommand({\n meta: { name: \"diff\", description: \"See a published Session's real file-level changes.\" },\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n surface: {\n type: \"string\",\n description: \"Filter: knowledge|company|brand|landings|flows|creatives\",\n required: false,\n },\n full: { type: \"boolean\", description: \"Include the diff patch text per file\", required: false, default: false },\n live: {\n type: \"boolean\",\n description: \"Read an in-progress Session's changes from its live workspace (slower)\",\n required: false,\n default: false,\n },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = { chatId: args.id };\n if (args.surface) {\n if (!(REPO_SURFACES as readonly string[]).includes(args.surface)) {\n throw new Error(`--surface must be one of: ${REPO_SURFACES.join(\"|\")}`);\n }\n body.surface = args.surface;\n }\n if (args.full) {\n body.full = true;\n }\n if (args.live) {\n body.live = true;\n }\n const response = await apiPost<ChatsDiffResponse>(\"/api/chats/diff\", body);\n writeJson({\n ...response,\n meta: { count: response.data.files.length },\n ...(!response.data.available && response.data.reason ? { hints: [response.data.reason] } : {}),\n ...(response.data.available && !args.full && response.data.files.length > 0\n ? { hints: [\"Add --full to read the actual diff text for each file.\"] }\n : {}),\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nconst IMPORT_DESCRIPTION = `Bring another chat's unpublished work into this chat, in one call — and take it out of that chat, so publishing both can never apply anything twice.\n\nStart here when the user wants another chat's work brought into this one (\"bring over\", \"merge the two\nchats\", \"its publish keeps failing — carry it over\", \"recover what the discarded chat did\"):\n baker chats import --from-chat <chat-id> # everything: files and staged changes\n baker chats import --from-chat <chat-id> --only meta-ads,tasks # only these staged surfaces, no files\n baker chats import --from-chat <chat-id> --failed # a PUBLISHED chat: the ad changes its publish could not apply\n baker chats import --from-chat $BAKER_CHAT_ID --failed # this chat's own last Publish: its failed ad changes, to fix and publish again\n\nThe other chat may be open, its publish may have failed, or it may be discarded. Its file changes (Knowledge,\npages, Forms, pictures) are applied in this workspace exactly as it made them, and every staged surface moves\nexactly as staged: ads (Google, Meta, LinkedIn, X, ChatGPT), Shopify, Tag Manager, Google Analytics, tracking\ntags, Tasks, scheduled agents, ActiveCampaign, site settings, ad goals, the funnel, conversions, conversion\nsends, event sources and lead routes. When both chats change the same file or the same thing, nothing moves\nand the refusal names each clash — ask the user which version wins. A chat whose publish failed is then closed\nto publishing, so the same work never goes live twice.\n--failed takes the Google Ads, Meta, LinkedIn, X and ChatGPT changes a published chat's publish could not\napply (failed, or skipped because what they needed failed), stages them here as they were — naming what did\napply by its real id — and takes them out of that chat, so its Retry cannot apply them twice. A chat goes on\nafter its Publish: naming this chat itself takes what its own last Publish could not apply into what it stages now.\nA change moved here cannot go back: to leave one behind, ask the user first and use --only (Google Ads alone\ncan pick single changes: \\`baker ads google draft import --from-chat <id> --refs|--exclude\\`).\nFind chat ids with \\`baker chats list\\`; see what one staged with \\`baker chats view <id>\\`.`;\n\nregisterSchema({\n command: \"chats.import\",\n description: IMPORT_DESCRIPTION,\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other chat — open, publish failed or discarded; published, or this chat itself, with --failed\",\n required: true,\n },\n only: {\n type: \"string\",\n description: `Comma-separated staged surfaces to move, leaving its files there (default: everything): ${CHAT_IMPORT_SURFACES.join(\", \")}`,\n required: false,\n },\n failed: {\n type: \"boolean\",\n description: \"The other chat is published: stage here the ad changes its publish could not apply\",\n required: false,\n default: false,\n },\n },\n});\n\n/** What became of the other chat's files, and of that chat itself. */\nfunction filesHints(data: ChatsImportResponse[\"data\"], files: SourceFiles | undefined): string[] {\n const hints: string[] = [];\n if (files?.kind === \"patch\") {\n hints.push(\n `Its ${files.paths.length} changed file(s) are now in this workspace, exactly as that chat left them: ${files.paths.join(\", \")}. Check them in the preview; never rebuild them by hand.`,\n );\n }\n if (files?.kind === \"stayed\") {\n hints.push(\n `Its file changes (Knowledge, pages, Forms…) did not come along: ${files.reason} Tell the user what is missing; do not rebuild it from memory.`,\n );\n } else if (data.filesStayed > 0) {\n hints.push(\n `Chat ${data.fromChatId} also changed ${data.filesStayed} file(s) (Knowledge, pages, Forms…) that did not come along. Run the import without --only to bring them.`,\n );\n }\n if (data.carried) {\n hints.push(\n \"That chat holds nothing of its own any more and can no longer be published, so the same work never goes live twice. This chat publishes all of it.\",\n );\n } else if (files?.kind === \"patch\") {\n hints.push(\n \"That chat still has its own copy of these files: tell the user to publish only this chat, or the same file changes would go live twice.\",\n );\n }\n return hints;\n}\n\n/** What the agent needs after a move: what stayed behind in the other chat, and what to check next. */\nfunction importHints(data: ChatsImportResponse[\"data\"], files: SourceFiles | undefined, failed: boolean): string[] {\n const hints: string[] = [];\n const moved = data.surfaces.reduce((sum, surface) => sum + surface.moved, 0);\n const stayed = data.surfaces.filter((surface) => surface.left);\n if (moved === 0 && stayed.length === 0 && files?.kind !== \"patch\") {\n hints.push(\n failed\n ? `Every ad change of chat ${data.fromChatId} applied, so there was nothing to bring over.`\n : `Chat ${data.fromChatId} had no unpublished changes, so nothing moved.`,\n );\n }\n for (const surface of stayed) {\n hints.push(\n `${surface.left?.count ? `${surface.left.count} ` : \"\"}${surface.surface} change(s) stayed in chat ${data.fromChatId}: ${surface.left?.reason}`,\n );\n }\n hints.push(...filesHints(data, files));\n if (moved > 0) {\n hints.push(\n \"The moved changes are this chat's now and publish with it; the other chat no longer holds them. Review them with each surface's `draft list` (and `baker ads google draft validate` when Google Ads changes moved).\",\n );\n }\n if (moved > 0 && stayed.length === 0 && !data.carried) {\n hints.push(\n \"Nothing staged stayed in the other chat. Never tell the user to discard it for this: its other work is still there.\",\n );\n }\n if (failed && moved > 0) {\n hints.push(\n \"They failed once for a reason: read each one's error with `baker chats view <id>` (publish) and amend it here before the user publishes, or it can fail the same way.\",\n );\n }\n return hints;\n}\n\ntype OnlyFlag = { surfaces?: ChatImportSurface[] } | { refusal: string };\n\n/** The surfaces `--only` names; absent means every surface, and a list naming none is refused. */\nfunction onlyFlag(value: unknown): OnlyFlag {\n if (typeof value !== \"string\") return {};\n const named = value\n .split(\",\")\n .map((surface) => surface.trim())\n .filter((surface) => surface.length > 0);\n if (named.length === 0) return { refusal: \"--only names no surface\" };\n const unknown = named.filter((surface) => !(CHAT_IMPORT_SURFACES as readonly string[]).includes(surface));\n if (unknown.length > 0) return { refusal: `--only names ${unknown.join(\", \")}, which is not a surface` };\n return { surfaces: named as ChatImportSurface[] };\n}\n\nfunction refuse(message: string, fix: string): never {\n writeJson({ ok: false, error: { code: \"VALIDATION_ERROR\", message, fix } });\n process.exit(1);\n}\n\n/** The other chat's files, applied here before its staged changes move — or why they stay there, or clash. */\nasync function carryFiles(fromChatId: string): Promise<SourceFiles | { kind: \"clash\"; paths: string[] }> {\n const files = await readSourceFiles(fromChatId);\n if (files.kind !== \"patch\") return files;\n const clashes = patchRefusal(files.patch);\n if (clashes) return { kind: \"clash\", paths: clashes };\n applyPatch(files.patch);\n return files;\n}\n\nconst importCommand = defineCommand({\n meta: { name: \"import\", description: IMPORT_DESCRIPTION },\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other chat whose work comes here — or, with --failed, this chat's own last Publish\",\n },\n only: { type: \"string\", description: \"Comma-separated staged surfaces to move, without files (default: all)\" },\n failed: {\n type: \"boolean\",\n description: \"From a published chat (this one included): the ad changes its publish could not apply\",\n default: false,\n },\n },\n run: async ({ args }) => {\n const fromChatId = typeof args[\"from-chat\"] === \"string\" ? args[\"from-chat\"].trim() : \"\";\n if (!fromChatId) {\n refuse(\n \"--from-chat is required\",\n \"Name the other chat: baker chats import --from-chat <chat-id> (ids from `baker chats list`).\",\n );\n }\n const only = onlyFlag(args.only);\n if (\"refusal\" in only) {\n // A list naming nothing must never widen to \"every surface\": the move takes them out of the other chat.\n refuse(\n only.refusal,\n `Name surfaces from: ${CHAT_IMPORT_SURFACES.join(\", \")} — or leave --only off to move them all.`,\n );\n }\n if (args.failed && only.surfaces) {\n refuse(\"--failed takes every ad platform's failed changes\", \"Leave --only off with --failed.\");\n }\n const chatId = requireChatId();\n let files: Awaited<ReturnType<typeof carryFiles>> | undefined;\n try {\n files = args.failed || only.surfaces ? undefined : await carryFiles(fromChatId);\n } catch (err) {\n failApi(err);\n }\n if (files?.kind === \"clash\") {\n refuse(\n `Nothing moved: these files changed in both chats, differently: ${files.paths.join(\", \")}.`,\n \"Ask the user which version should win. To bring only the other chat's staged changes and leave its files there, run the import again with --only and the surfaces it staged.\",\n );\n }\n try {\n const response = await apiPost<ChatsImportResponse>(\"/api/chats/import\", {\n chatId,\n fromChatId,\n ...(only.surfaces ? { surfaces: only.surfaces } : {}),\n ...(files?.kind === \"patch\" ? { filesCarried: true } : {}),\n ...(args.failed ? { failed: true } : {}),\n });\n writeJson({ ...response, hints: importHints(response.data, files, Boolean(args.failed)) });\n } catch (err) {\n // All or nothing: the files go back out when the staged changes could not come with them.\n if (files?.kind === \"patch\") revertPatch(files.patch);\n failApi(err);\n }\n },\n});\n\nexport const chatsCommand = defineCommand({\n meta: {\n name: \"chats\",\n description: `Inspect other Sessions on this account: list them, view what they produced, read their conversation, and see their real file changes — so you can reuse past work for a new goal. \\`import --from-chat <id>\\` moves another open Session's staged changes into this one.\nFull guide: __tooling__/docs/tools/baker/chats.md`,\n },\n subCommands: {\n list: listCommand,\n view: viewCommand,\n transcript: transcriptCommand,\n diff: diffCommand,\n import: importCommand,\n },\n});\n","/**\n * The file half of `baker chats import`: the other chat's changes to its files (Knowledge, pages,\n * Forms, pictures…), read from its workspace as one patch (`chats diff --live`'s `gitPatch`) and\n * applied here with `git apply` — exactly, or not at all.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport type { ChatsDiffResponse } from \"@baker/api\";\nimport { apiPost } from \"../../client.ts\";\n\nexport type SourceFiles =\n | { kind: \"none\" }\n | { kind: \"patch\"; patch: string; paths: string[] }\n | { kind: \"stayed\"; reason: string };\n\n/** What the other chat changed in its files, as something this workspace can apply — or why not. */\nexport async function readSourceFiles(fromChatId: string): Promise<SourceFiles> {\n const response = await apiPost<ChatsDiffResponse>(\"/api/chats/diff\", {\n chatId: fromChatId,\n live: true,\n gitPatch: true,\n });\n const { data } = response;\n if (!data.available) {\n return { kind: \"stayed\", reason: data.reason ?? \"its files could not be read.\" };\n }\n if (data.source === \"published\") {\n // Its changes reached the live site already, so there is nothing of them to carry.\n return { kind: \"none\" };\n }\n if (data.files.length === 0) {\n return { kind: \"none\" };\n }\n if (data.gitPatch === undefined) {\n return {\n kind: \"stayed\",\n reason: \"its file changes are too large to bring over in one piece, so none of them came along.\",\n };\n }\n return { kind: \"patch\", patch: data.gitPatch, paths: data.files.map((file) => file.path) };\n}\n\nfunction repoRoot(): string {\n return execFileSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], { encoding: \"utf8\" }).trim();\n}\n\n/** `git apply` of the patch at this workspace's root; `check` changes nothing, `reverse` takes it back out. */\nfunction gitApply(patch: string, mode: \"check\" | \"apply\" | \"reverse\"): void {\n const flags = mode === \"check\" ? [\"--check\"] : mode === \"reverse\" ? [\"--reverse\"] : [];\n execFileSync(\"git\", [\"apply\", \"--whitespace=nowarn\", ...flags, \"-\"], {\n cwd: repoRoot(),\n input: patch,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n}\n\n/** The files `git apply --check` named as not applying here, or the whole message when it named none. */\nexport function clashingFiles(stderr: string): string[] {\n const named = [...stderr.matchAll(/^error: ([^:\\n]+): /gm)]\n .map((match) => match[1])\n .filter((path): path is string => path !== undefined && path !== \"patch failed\");\n return named.length > 0 ? [...new Set(named)] : [stderr.trim()];\n}\n\n/** Why the patch cannot apply here — the files this chat also changed — or undefined when it applies cleanly. */\nexport function patchRefusal(patch: string): string[] | undefined {\n try {\n gitApply(patch, \"check\");\n return undefined;\n } catch (error) {\n const stderr = (error as { stderr?: Buffer | string }).stderr;\n return clashingFiles(stderr === undefined ? String(error) : String(stderr));\n }\n}\n\nexport function applyPatch(patch: string): void {\n gitApply(patch, \"apply\");\n}\n\nexport function revertPatch(patch: string): void {\n gitApply(patch, \"reverse\");\n}\n","import type { ChatPublishSummary } from \"@baker/api/chats\";\n\n/**\n * What a reader must not conclude from a completed Session: that it published\n * everything it staged (better than one published draft in three did not), or\n * that every change it sent is now what the platform holds.\n */\nexport function publishHints(publish: ChatPublishSummary): string[] {\n const hints: string[] = [];\n // Not `complete`: a change a person chose not to send leaves the publish complete, and still never went live.\n const failed = publish.failedTotal;\n if (failed > 0) {\n hints.push(\n `This Session's publish left ${failed} change${failed === 1 ? \"\" : \"s\"} behind — see \\`publish.surfaces\\` for why each did not apply. Do not report those changes as live.`,\n );\n }\n const unconfirmed = publish.unconfirmedTotal ?? 0;\n if (unconfirmed > 0) {\n hints.push(\n `${unconfirmed} change${unconfirmed === 1 ? \"\" : \"s\"} went through but could not be confirmed when read back from the platform — \\`publish.surfaces[].unconfirmedChanges\\` says what it shows instead. Check before reporting them as done.`,\n );\n }\n return hints;\n}\n\n/**\n * A Session still publishing is not live yet, and nothing in this chat runs\n * once it is: work that has to wait for it is a Scheduled agent (BAKER-1743).\n */\nexport function stillPublishingHints(status: string): string[] {\n if (status !== \"publishing\") return [];\n return [\n \"This Session is still publishing: its changes are not live yet. Work that has to wait for it (a check on the live page, a test lead) is a Scheduled agent staged now with `baker scheduled-agents create --run-at <time>`, whose brief first checks this Session went live. It exists only once your own chat is published: a page trigger staged now misses this Session's publish, and a `--run-at` that has passed by then is created switched off, so leave hours of headroom, not minutes, and tell the user it runs only once they publish this chat. Never ask the user to come back and tell you when it is done.\",\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,qBAAqB;;;ACL9B,SAAS,oBAAoB;AAU7B,eAAsB,gBAAgB,YAA0C;AAC9E,QAAM,WAAW,MAAM,QAA2B,mBAAmB;AAAA,IACnE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,UAAU;AAAA,EACZ,CAAC;AACD,QAAM,EAAE,KAAK,IAAI;AACjB,MAAI,CAAC,KAAK,WAAW;AACnB,WAAO,EAAE,MAAM,UAAU,QAAQ,KAAK,UAAU,+BAA+B;AAAA,EACjF;AACA,MAAI,KAAK,WAAW,aAAa;AAE/B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACA,MAAI,KAAK,MAAM,WAAW,GAAG;AAC3B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACA,MAAI,KAAK,aAAa,QAAW;AAC/B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ;AAAA,IACV;AAAA,EACF;AACA,SAAO,EAAE,MAAM,SAAS,OAAO,KAAK,UAAU,OAAO,KAAK,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,EAAE;AAC3F;AAEA,SAAS,WAAmB;AAC1B,SAAO,aAAa,OAAO,CAAC,aAAa,iBAAiB,GAAG,EAAE,UAAU,OAAO,CAAC,EAAE,KAAK;AAC1F;AAGA,SAAS,SAAS,OAAe,MAA2C;AAC1E,QAAM,QAAQ,SAAS,UAAU,CAAC,SAAS,IAAI,SAAS,YAAY,CAAC,WAAW,IAAI,CAAC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AAI,CAAC;AAAA,MACxD;AAAA,IACF;AACA,QAAI,KAAK,UAAU,KAAK,UAAU;AAChC,aAAO,qDAAqD,iCAAiC;AAAA,IAC/F;AACA,UAAM,SAAS,cAAc;AAC7B,QAAI;AACJ,QAAI;AACF,cAAQ,KAAK,UAAU,KAAK,WAAW,SAAY,MAAM,WAAW,UAAU;AAAA,IAChF,SAAS,KAAK;AACZ,cAAQ,GAAG;AAAA,IACb;AACA,QAAI,OAAO,SAAS,SAAS;AAC3B;AAAA,QACE,kEAAkE,MAAM,MAAM,KAAK,IAAI,CAAC;AAAA,QACxF;AAAA,MACF;AAAA,IACF;AACA,QAAI;AACF,YAAM,WAAW,MAAM,QAA6B,qBAAqB;AAAA,QACvE;AAAA,QACA;AAAA,QACA,GAAI,KAAK,WAAW,EAAE,UAAU,KAAK,SAAS,IAAI,CAAC;AAAA,QACnD,GAAI,OAAO,SAAS,UAAU,EAAE,cAAc,KAAK,IAAI,CAAC;AAAA,QACxD,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,IAAI,CAAC;AAAA,MACxC,CAAC;AACD,gBAAU,EAAE,GAAG,UAAU,OAAO,YAAY,SAAS,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,EAAE,CAAC;AAAA,IAC3F,SAAS,KAAK;AAEZ,UAAI,OAAO,SAAS,QAAS,aAAY,MAAM,KAAK;AACpD,cAAQ,GAAG;AAAA,IACb;AAAA,EACF;AACF,CAAC;AAEM,IAAM,eAAe,cAAc;AAAA,EACxC,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA,EAEf;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,EACV;AACF,CAAC;","names":[]}
|
|
@@ -179,7 +179,9 @@ var hubspotPreviewRequestSchema = z2.strictObject({
|
|
|
179
179
|
/** Property names to read off the sample; `id` is always there. On a deal or a lead, `contact.<name>` reads its first contact. */
|
|
180
180
|
properties: z2.array(z2.string().trim().min(1)).max(60).optional(),
|
|
181
181
|
/** The record to draw the preview from — an id, or text to search (an email or a name for a contact, a deal's or a lead's name). The one most recently at the trigger when unsaid. */
|
|
182
|
-
contact: z2.string().trim().min(1).max(200).optional()
|
|
182
|
+
contact: z2.string().trim().min(1).max(200).optional(),
|
|
183
|
+
/** A total for each value of the trigger's one dropdown `is` condition, beside the combined one — sizing a funnel in one call. */
|
|
184
|
+
breakdown: z2.boolean().optional()
|
|
183
185
|
});
|
|
184
186
|
var hubspotPreviewSchema = z2.strictObject({
|
|
185
187
|
/** Records satisfying the trigger today — the ones that will NOT be counted. */
|
|
@@ -195,7 +197,9 @@ var hubspotPreviewSchema = z2.strictObject({
|
|
|
195
197
|
* people the event is about. Three parallel nullable fields, exactly one of
|
|
196
198
|
* them ever set, would say the same thing and let a caller read the wrong one.
|
|
197
199
|
*/
|
|
198
|
-
record: sampleRecordSchema.extend({ contacts: z2.array(sampleRecordSchema) }).nullable()
|
|
200
|
+
record: sampleRecordSchema.extend({ contacts: z2.array(sampleRecordSchema) }).nullable(),
|
|
201
|
+
/** Only on a `breakdown`: each value of the condition with how many records are at it today, in the order asked. */
|
|
202
|
+
counts: z2.array(z2.strictObject({ value: z2.string(), total: z2.number() })).optional()
|
|
199
203
|
});
|
|
200
204
|
var sourcesRequestSchema = z2.strictObject({
|
|
201
205
|
/** The company's own server door: made once, `counting` from the start, the same address for ever after. */
|
|
@@ -389,4 +393,4 @@ export {
|
|
|
389
393
|
hubspotDefaultMapping,
|
|
390
394
|
hubspotTriggerInputSchema
|
|
391
395
|
};
|
|
392
|
-
//# sourceMappingURL=chunk-
|
|
396
|
+
//# sourceMappingURL=chunk-NRU2A7TJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../api/src/event-sources/hubspot.ts","../../api/src/event-sources/wire.ts","../../api/src/event-sources/activecampaign.ts"],"sourcesContent":["/**\n * What a HubSpot event reads by default, spelled as the same templates an\n * address's mapping uses — so the sheet shows one table for both, and a row\n * can be repointed at any property, or typed.\n *\n * ## Why defaults and not a fixed read\n *\n * The read used to be hard-wired: email from `email`, the Google click from\n * `hs_google_click_id`, and nothing anybody could change. Real accounts keep\n * the email under `work_email`, the deal value under a custom number\n * property, and a click id under whatever the tracking template wrote. The\n * defaults are HubSpot's standard names, which is where most accounts keep\n * them; every row is a template a person or the agent can change, and the\n * picker is the account's own property list, read live — never this table.\n *\n * An empty stored mapping means these — the same rule as an address, where\n * empty means \"the guess\".\n *\n * ## Three objects, one spelling\n *\n * A mention names a property of the object watched: `{{email}}` on a\n * contact source, `{{amount}}` on a deal source, `{{hs_pipeline_stage}}` on\n * a lead source, `{{id}}` the record's own id on any of them. A deal or a\n * lead source also reads the contact its record is about, through the\n * `contact.` namespace: `{{contact.email}}`, `{{contact.id}}`. The namespace\n * is what keeps the objects' properties apart in one table, and it is\n * spelled the way the Forms builder spells a nested field.\n */\n\nimport type { SourceField } from \"./fields\";\nimport type { HubspotObject } from \"./hubspotTrigger\";\nimport { mentionOf } from \"./template\";\n\n/** The variable that is the record's own id rather than a property: `{{id}}`. */\nexport const HUBSPOT_CONTACT_ID_VARIABLE = \"id\";\n\n/** On a deal source, the associated contact's properties are read as `{{contact.<property>}}`. */\nexport const HUBSPOT_CONTACT_PREFIX = \"contact.\";\n\n/** The path for a property of a deal's contact: `contact.email`. */\nexport function contactPath(property: string): string {\n return `${HUBSPOT_CONTACT_PREFIX}${property}`;\n}\n\n/** The contact property a `contact.<property>` path names, or null for a path of the record itself. */\nexport function contactPropertyOf(path: string): string | null {\n return path.startsWith(HUBSPOT_CONTACT_PREFIX) ? path.slice(HUBSPOT_CONTACT_PREFIX.length) : null;\n}\n\n/** HubSpot's standard contact property behind each field, where one exists. */\nexport const HUBSPOT_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = {\n email: \"email\",\n phone: \"phone\",\n external_id: HUBSPOT_CONTACT_ID_VARIABLE,\n first_name: \"firstname\",\n last_name: \"lastname\",\n city: \"city\",\n postal_code: \"zip\",\n country: \"country\",\n gclid: \"hs_google_click_id\",\n fbclid: \"hs_facebook_click_id\",\n};\n\n/**\n * The person's rows read off the record's associated contact, for an object\n * that is about somebody rather than being them.\n */\nconst throughContact: Readonly<Partial<Record<SourceField, string>>> = Object.fromEntries(\n Object.entries(HUBSPOT_DEFAULT_PROPERTIES).map(([field, property]) => [field, contactPath(property)]),\n);\n\n/**\n * The same for a deal: the person is the deal's contact, the amount is the\n * deal's own — HubSpot keeps it as `amount` in `deal_currency_code`, on\n * every account, which is the one row a contact source could never fill by\n * default.\n */\nexport const HUBSPOT_DEAL_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = {\n ...throughContact,\n value: \"amount\",\n currency: \"deal_currency_code\",\n};\n\n/**\n * The same for a lead. A lead is an interest in somebody, not an amount: it\n * has no `amount` and no currency of its own, so the value rows stay empty\n * and the funnel counts the step rather than money. Anyone who keeps a figure\n * on a custom lead property can still point `value` at it by hand.\n */\nexport const HUBSPOT_LEAD_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = throughContact;\n\nconst DEFAULTS: Readonly<Record<HubspotObject, Readonly<Partial<Record<SourceField, string>>>>> = {\n contact: HUBSPOT_DEFAULT_PROPERTIES,\n deal: HUBSPOT_DEAL_DEFAULT_PROPERTIES,\n lead: HUBSPOT_LEAD_DEFAULT_PROPERTIES,\n};\n\n/** The mapping a HubSpot event starts with: its name as the event, the standard properties for the rest. */\nexport function hubspotDefaultMapping(\n sourceName: string,\n object: HubspotObject = \"contact\",\n): Partial<Record<SourceField, string>> {\n const mapping: Partial<Record<SourceField, string>> = { event_name: sourceName };\n for (const [field, property] of Object.entries(DEFAULTS[object])) {\n mapping[field as SourceField] = mentionOf(property);\n }\n return mapping;\n}\n\n/**\n * The mapping in force for a HubSpot event: what was saved, else the defaults.\n * Keyed by field, or by `properties.<key>` for an extra property of the event.\n */\nexport function hubspotMappingInForce(\n sourceName: string,\n stored: Readonly<Record<string, string>>,\n object: HubspotObject = \"contact\",\n): Record<string, string> {\n const explicit = Object.entries(stored).filter(([, template]) => template.trim() !== \"\");\n if (explicit.length > 0) return Object.fromEntries(explicit);\n return hubspotDefaultMapping(sourceName, object);\n}\n","/**\n * The contract between `baker analytics sources` and `POST /api/analytics/sources`,\n * and the address a source is given.\n *\n * One request shape with one optional operation in it, and every call answers\n * with the full list afterwards — the CLI never has to make a second request\n * to see what it just did, and the \"what arrived\" question is answered by the\n * same read that answers \"what exists\".\n */\nimport { z } from \"zod\";\nimport { REJECTION_MESSAGES, validateEventName } from \"../event-ingest/validation\";\nimport { ACTIVECAMPAIGN_WEBHOOK_STATES, activeCampaignEventsSchema } from \"./activecampaign\";\nimport { mappingRowProblem } from \"./fields\";\nimport {\n CONDITION_LOGICS,\n HUBSPOT_DEAL_CONTACTS,\n HUBSPOT_OBJECTS,\n HUBSPOT_PROPERTY_KINDS,\n type HubspotTriggerInput,\n onlyCondition,\n TRIGGER_CONDITIONS_MAX,\n triggerProblem,\n} from \"./hubspotTrigger\";\n\n/** Mirrors `EVENT_SOURCE_KINDS` / the status validator in the backend schema; this package must not depend on convex. */\nexport const SOURCE_KINDS = [\"webhook\", \"hubspot\", \"activecampaign\"] as const;\nexport type SourceKind = (typeof SOURCE_KINDS)[number];\nexport const SOURCE_STATUSES = [\"learning\", \"counting\", \"paused\"] as const;\nexport type SourceStatus = (typeof SOURCE_STATUSES)[number];\n\nexport const SOURCE_NAME_MAX = 80;\n\n/**\n * What a source may be called — which is the ingest door's own rule, because a\n * source's name IS the `event_name` every event it raises carries.\n *\n * Held here rather than at each door, and that is the whole point of it being\n * here. A name this refuses is not a bad label, it is a **source that can\n * never count anything**: every arrival is rejected `invalid_name`, the card\n * goes on reading \"Counting\", and the only trace is one red line per event on\n * a feed somebody has to think to open. That happened — a HubSpot source\n * called \"Matrícula Realizada\", refused for ever by a rule that was ASCII-only\n * — and the reason it could happen is that three doors took a name and none of\n * them knew the rule.\n *\n * `MAX_EVENT_NAME` is the same 80 as {@link SOURCE_NAME_MAX} and\n * `validateEventName` checks it, so the bound is stated once even though both\n * constants exist.\n */\nexport const sourceNameSchema = z\n .string()\n .trim()\n .min(1)\n .max(SOURCE_NAME_MAX)\n .refine((name) => validateEventName(name) === null, REJECTION_MESSAGES.invalid_name);\n\n/** Where a source's arrivals go: the token is the whole path after this. */\nexport const EVENT_SOURCE_PATH_PREFIX = \"/v1/sources/\";\n\n/**\n * The address to hand a tool, given the branded host published for this\n * environment — the same fallback rule as `eventIngestUrl`.\n */\nexport function eventSourceUrl(brandedUrl: string | undefined, convexSiteUrl: string, token: string): string {\n const base = (brandedUrl || convexSiteUrl).replace(/\\/$/, \"\");\n return `${base}${EVENT_SOURCE_PATH_PREFIX}${token}`;\n}\n\nconst sourceIdSchema = z.string().min(1);\n\n/**\n * Canonical field → template (`template.ts`): literal text with `{{path}}`\n * mentions, or a bare path. A `properties.<key>` row is an extra property of\n * the event (`fields.ts`). Anything else is refused so a typo cannot become a\n * silent no-op.\n */\nexport const sourceMappingSchema = z.record(z.string(), z.string().min(1)).superRefine((mapping, ctx) => {\n for (const row of Object.keys(mapping)) {\n const problem = mappingRowProblem(row);\n if (problem !== null) ctx.addIssue({ code: \"custom\", message: problem, path: [row] });\n }\n});\n\n/** ISO 4217, upper case: what `POST /v1/events` accepts as `currency`. */\nexport const currencyCodeSchema = z\n .string()\n .trim()\n .toUpperCase()\n .regex(/^[A-Z]{3}$/, \"A currency is a three-letter code, like EUR or USD.\");\n\n/** What a HubSpot source is a trigger on: a contact (the default), a deal or a lead. */\nexport const hubspotObjectSchema = z.enum(HUBSPOT_OBJECTS);\n/** For a deal: whose event it is — the deal's first contact, or every contact on it. */\nexport const hubspotDealContactsSchema = z.enum(HUBSPOT_DEAL_CONTACTS);\n\n/**\n * One condition of a HubSpot trigger — *when a contact's* (or *a deal's*)\n * [property] [operator] [values] (`hubspotTrigger.ts`).\n */\nexport const hubspotConditionInputSchema = z.strictObject({\n property: z.string().trim().min(1),\n /** One of the property's kind's operators (`baker hubspot contacts properties` lists them); `is` when unsaid. */\n operator: z.string().trim().min(1).default(\"is\"),\n /** As HubSpot spells them: an option's internal value, a number, a `YYYY-MM-DD`, `true`/`false`. None for an empty check, two for a between, several for a list. */\n values: z.array(z.string().trim().min(1)).max(50).default([]),\n});\n\nconst conditionLogicSchema = z.enum(CONDITION_LOGICS);\n\nconst conditionGroupInputSchema = z.strictObject({\n logic: conditionLogicSchema,\n conditions: z.array(hubspotConditionInputSchema).min(1).max(TRIGGER_CONDITIONS_MAX),\n});\n\nconst combinedInputSchema = z\n .strictObject({\n /** How the rows combine: `And` (every one) or `Or` (any one) — a Form's filter's \"Match AND / OR\". */\n logic: conditionLogicSchema.default(\"And\"),\n /** Conditions, and groups of conditions with their own logic, one level deep. */\n conditions: z\n .array(z.union([hubspotConditionInputSchema, conditionGroupInputSchema]))\n .min(1)\n .max(TRIGGER_CONDITIONS_MAX),\n })\n .superRefine((trigger, context) => {\n const problem = triggerProblem(trigger);\n if (problem !== null) context.addIssue({ code: \"custom\", message: problem });\n });\n\n/**\n * What a HubSpot source watches: one condition, or several combined — the\n * way a Form's filter combines them. A single condition is the short\n * spelling, and is read as a trigger of that one condition.\n */\nexport const hubspotTriggerInputSchema = z\n .union([combinedInputSchema, hubspotConditionInputSchema])\n .transform((input): HubspotTriggerInput => (\"conditions\" in input ? input : onlyCondition(input)));\n\nconst hubspotConditionSchema = hubspotConditionInputSchema.extend({\n propertyLabel: z.string(),\n kind: z.enum(HUBSPOT_PROPERTY_KINDS),\n /** A select that holds several values at once (`a;b`); decides what HubSpot may filter on. */\n multiple: z.boolean().optional(),\n valueLabels: z.array(z.string()),\n});\n\nconst hubspotTriggerFields = {\n logic: conditionLogicSchema,\n conditions: z.array(\n z.union([\n hubspotConditionSchema,\n z.strictObject({ logic: conditionLogicSchema, conditions: z.array(hubspotConditionSchema) }),\n ]),\n ),\n};\n\n/** The trigger as stored on a source: every condition resolved, and on its object. */\nexport const hubspotWatchSchema = z.strictObject({\n ...hubspotTriggerFields,\n object: hubspotObjectSchema,\n contacts: hubspotDealContactsSchema.optional(),\n});\nexport type HubspotWatchView = z.infer<typeof hubspotWatchSchema>;\n\n/** A sample record as the preview shows it: its id and the properties it holds, empty ones dropped. */\nconst sampleRecordSchema = z.strictObject({ id: z.string(), properties: z.record(z.string(), z.string()) });\n\n/** What a HubSpot event would count today, asked before it is made: the trigger and the properties to read off the sample. */\nexport const hubspotPreviewRequestSchema = z.strictObject({\n object: hubspotObjectSchema.default(\"contact\"),\n trigger: hubspotTriggerInputSchema,\n /** Property names to read off the sample; `id` is always there. On a deal or a lead, `contact.<name>` reads its first contact. */\n properties: z.array(z.string().trim().min(1)).max(60).optional(),\n /** The record to draw the preview from — an id, or text to search (an email or a name for a contact, a deal's or a lead's name). The one most recently at the trigger when unsaid. */\n contact: z.string().trim().min(1).max(200).optional(),\n /** A total for each value of the trigger's one dropdown `is` condition, beside the combined one — sizing a funnel in one call. */\n breakdown: z.boolean().optional(),\n});\nexport type HubspotPreviewRequest = z.infer<typeof hubspotPreviewRequestSchema>;\n\nexport const hubspotPreviewSchema = z.strictObject({\n /** Records satisfying the trigger today — the ones that will NOT be counted. */\n total: z.number(),\n /** False when the trigger has more combinations than HubSpot's search takes, so `total` is only near. */\n exact: z.boolean().optional(),\n /**\n * The sample record the trigger is on, with the properties asked for and\n * the contacts behind it, first first; none when nothing fits.\n *\n * One field rather than one per object: a contact source's record *is* the\n * person and its `contacts` is empty, while a deal's and a lead's carry the\n * people the event is about. Three parallel nullable fields, exactly one of\n * them ever set, would say the same thing and let a caller read the wrong one.\n */\n record: sampleRecordSchema.extend({ contacts: z.array(sampleRecordSchema) }).nullable(),\n /** Only on a `breakdown`: each value of the condition with how many records are at it today, in the order asked. */\n counts: z.array(z.strictObject({ value: z.string(), total: z.number() })).optional(),\n});\nexport type HubspotPreview = z.infer<typeof hubspotPreviewSchema>;\n\nexport const sourcesRequestSchema = z.strictObject({\n /** The company's own server door: made once, `counting` from the start, the same address for ever after. */\n server: z.strictObject({}).optional(),\n create: z.strictObject({ name: sourceNameSchema }).optional(),\n /** A HubSpot event: read every five minutes, counting from now. The labels are looked up server-side. */\n createHubspot: z\n .strictObject({\n name: sourceNameSchema.optional(),\n /** A contact, a deal or a lead. A deal's and a lead's event is about its contact, read through `contact.<property>` rows. */\n object: hubspotObjectSchema.default(\"contact\"),\n trigger: hubspotTriggerInputSchema,\n /** On a deal: the deal's first contact (the default), or every contact on it, each its own event. */\n contacts: hubspotDealContactsSchema.optional(),\n /** Rows to read off the record, over the defaults; the same table `map` writes. */\n mapping: sourceMappingSchema.optional(),\n /** A number property on the record to read as the amount; needs `currency` beside it. Sugar over the mapping's `value` and `currency` rows. */\n amountProperty: z.string().trim().min(1).optional(),\n currency: currencyCodeSchema.optional(),\n })\n .optional(),\n /**\n * An ActiveCampaign source: ActiveCampaign's own webhook, made on the\n * account when this is applied, sending the events picked here. Each raises\n * `activecampaign.<type>` and counts from then on.\n */\n createActiveCampaign: z\n .strictObject({\n name: sourceNameSchema.optional(),\n /** ActiveCampaign's event names (`subscribe`, `deal_update`, …); the lead and deal moments when unsaid. */\n events: activeCampaignEventsSchema.optional(),\n /** Which connection, when the company has more than one. */\n account: z.string().trim().min(1).optional(),\n })\n .optional(),\n /** Change what a HubSpot event watches. It counts from now on under the new trigger; the rows stay. The object cannot change: the rows read it. */\n setTrigger: z\n .strictObject({\n sourceId: sourceIdSchema,\n trigger: hubspotTriggerInputSchema,\n contacts: hubspotDealContactsSchema.optional(),\n })\n .optional(),\n /** Ask HubSpot what a trigger would count today, and read one real record, without making anything. */\n preview: hubspotPreviewRequestSchema.optional(),\n /** Change where a HubSpot-read source takes its amount from; no `amountProperty` clears it. Sugar over `map`. */\n setAmount: z\n .strictObject({\n sourceId: sourceIdSchema,\n amountProperty: z.string().trim().min(1).optional(),\n currency: currencyCodeSchema.optional(),\n })\n .optional(),\n /**\n * Count a HubSpot event's history: every moment its trigger came to hold\n * since `since`, read out of HubSpot's own property history.\n *\n * Not the thing a source deliberately refuses to do. A source never\n * backfills the **present state** — somebody who already satisfies a\n * condition is not an event today — and this reports only moments HubSpot\n * has a timestamp for, so nothing is invented. Dry unless `write`.\n */\n backfill: z\n .strictObject({\n sourceId: sourceIdSchema,\n /** ISO instant, or Unix milliseconds. Bounded by the 400 days the store keeps. */\n since: z.union([z.string().trim().min(1), z.number()]),\n /**\n * Where a capped run carries on from: only records last changed at or\n * before this instant are read.\n *\n * The **read** is what it bounds, never the history. Records are chosen\n * most-recently-changed first, so a run that reaches its cap has covered\n * the newest of them and the rest are the ones nearest `since` — which\n * no shorter window can reach, because shortening one only drops\n * candidates from the old end and hands back the same newest records\n * again. `reachedBack` is the value to pass here, and the moments each\n * record is then judged on are still the whole of `since` to now.\n */\n before: z.union([z.string().trim().min(1), z.number()]).optional(),\n /** Without it, nothing is counted and the answer says what would be. */\n write: z.boolean().optional(),\n })\n .optional(),\n map: z.strictObject({ sourceId: sourceIdSchema, mapping: sourceMappingSchema }).optional(),\n pause: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n resume: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n remove: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n});\nexport type SourcesRequest = z.infer<typeof sourcesRequestSchema>;\n/** The request as a caller writes it, before the schema fills its defaults — what the CLI builds. */\nexport type SourcesRequestInput = z.input<typeof sourcesRequestSchema>;\n\n/** A delivery that arrived and was refused — mirrors `sourceRefusalValidator` in the backend schema. */\nexport const sourceRefusalSchema = z.strictObject({\n at: z.number(),\n count: z.number(),\n code: z.string(),\n reason: z.string(),\n});\n\nexport const detectedFieldSchema = z.strictObject({\n path: z.string(),\n confidence: z.enum([\"key\", \"value\"]),\n});\n\n/** Whether HubSpot's journal is being told to keep the changes a source watches. */\nexport const HUBSPOT_LISTENING_STATES = [\"listening\", \"not_configured\", \"failed\"] as const;\nexport type HubspotListeningState = (typeof HUBSPOT_LISTENING_STATES)[number];\n\nexport const sourceViewSchema = z.strictObject({\n id: z.string(),\n kind: z.enum(SOURCE_KINDS),\n name: z.string(),\n status: z.enum(SOURCE_STATUSES),\n /** The address a tool posts to. A HubSpot source has none: Baker calls HubSpot. */\n url: z.string().optional(),\n /** What a HubSpot source watches, and on which object. */\n hubspot: hubspotWatchSchema.optional(),\n /**\n * What an ActiveCampaign source listens to, and whether ActiveCampaign has\n * the webhook that sends it: `listening` once it is made, `not_configured`\n * until then, `failed` when ActiveCampaign refused it — `detail` says why.\n */\n activecampaign: z\n .strictObject({\n events: z.array(z.string()),\n webhook: z.strictObject({ state: z.enum(ACTIVECAMPAIGN_WEBHOOK_STATES), detail: z.string().optional() }),\n })\n .optional(),\n /** A HubSpot source counts changes from here on; one HubSpot reports from before it is dropped. Moves when the trigger changes. */\n countingSince: z.number().optional(),\n /**\n * Whether HubSpot is keeping this source's changes for Baker, as last\n * checked: `listening` when the app's journal subscription on the account\n * names the property; `not_configured` when the app has not been told yet\n * (or cannot be, with no credentials); `failed` when HubSpot refused the\n * subscription. `detail` says what to do.\n */\n listening: z.strictObject({ state: z.enum(HUBSPOT_LISTENING_STATES), detail: z.string().optional() }).optional(),\n /** Why the last delivery could not be counted, in product words; absent when the last one was. */\n lastError: z.string().optional(),\n lastArrivalAt: z.number().optional(),\n /**\n * What its last delivery **refused, event by event** — which `lastError` is\n * not and `lastArrivalAt` cannot be. A source refusing everything it\n * receives has no arrival and no read failure, so without this it reads as\n * one nobody has sent anything to. `refusalWords` turns it into the\n * sentence a person is shown. Cleared by the next delivery that counts.\n */\n lastRefusal: sourceRefusalSchema.optional(),\n /** The first send, masked, while learning. Kept once confirmed. */\n sample: z.strictObject({ receivedAt: z.number(), body: z.string() }).optional(),\n /** Field → template; empty means the guess (an address) or the defaults (a HubSpot read). */\n mapping: z.record(z.string(), z.string()),\n /** The guess over the sample, for the sheet to prefill and the CLI to suggest. */\n detected: z.record(z.string(), detectedFieldSchema).optional(),\n /** Every path the sample's first item holds, with its masked value — what the picker offers. */\n paths: z.array(z.strictObject({ path: z.string(), value: z.string() })).optional(),\n /** `baker` when the sample already parses as the `POST /v1/events` contract and needs no mapping. */\n format: z.enum([\"baker\", \"foreign\"]).optional(),\n});\nexport type SourceView = z.infer<typeof sourceViewSchema>;\n\n/**\n * One change to the company's sources, staged inside a chat and applied when\n * it is published. `ref` is the source's id, or a `src_temp_*` for one the\n * chat makes.\n */\nexport const stagedSourceOpSchema = z.strictObject({\n kind: z.enum([\"create\", \"setTrigger\", \"map\", \"status\", \"remove\"]),\n ref: z.string(),\n name: z.string(),\n summary: z.string(),\n /** On a create: what the source will watch and read. */\n hubspot: hubspotWatchSchema.optional(),\n /** On an ActiveCampaign create: the events its webhook will send. */\n activecampaign: z.strictObject({ events: z.array(z.string()) }).optional(),\n mapping: z.record(z.string(), z.string()).optional(),\n status: z.enum([\"paused\", \"counting\"]).optional(),\n});\nexport type StagedSourceOp = z.infer<typeof stagedSourceOpSchema>;\n\n/** What a backfill found, and — on a `write` run — what became of it. */\nexport const backfillResultSchema = z.strictObject({\n sourceId: z.string(),\n name: z.string(),\n since: z.number(),\n /** Records whose history was read. */\n examined: z.number(),\n /** Moments the trigger came to hold, across them. */\n entries: z.number(),\n /** Of those, already counted — the journal got there first, or a previous run did. */\n alreadyCounted: z.number(),\n /** What a `write` run would hand over, or did. */\n pending: z.number(),\n /** Whether the read stopped at its cap; {@link BackfillResult.reachedBack} is where to carry on from. */\n capped: z.boolean(),\n /**\n * How far back the read got: the instant the oldest record it examined was\n * last changed. Only on a capped run, and it is the next run's `before`.\n */\n reachedBack: z.number().optional(),\n counted: z.number().optional(),\n refused: z.number().optional(),\n refusedReason: z.string().optional(),\n});\nexport type BackfillResult = z.infer<typeof backfillResultSchema>;\n\nexport const sourcesResponseSchema = z.strictObject({\n ok: z.literal(true),\n data: z.strictObject({\n sources: z.array(sourceViewSchema),\n /** Only when the request carried `preview`. */\n preview: hubspotPreviewSchema.optional(),\n /** Only when the request carried `backfill`. */\n backfill: backfillResultSchema.optional(),\n /** What this chat has staged, when one is attached: applied at Publish, dropped with a discard. */\n staged: z.array(stagedSourceOpSchema).optional(),\n }),\n hints: z.array(z.string()).optional(),\n});\nexport type SourcesResponse = z.infer<typeof sourcesResponseSchema>;\n","/**\n * What an ActiveCampaign source can listen to: ActiveCampaign's own webhook\n * events, and the event name each one raises in Baker.\n *\n * The list is ActiveCampaign's, read from `GET /api/3/webhook/events` — an\n * account answers with exactly these 27 — and the words are ours, for the\n * picker and the change list. Every event a source raises is called\n * `activecampaign.<type>`, whatever the source is called, so a scheduled agent\n * narrowed to `activecampaign.deal_update` runs for any connected account and\n * `properties.baker_source` says which source it came through.\n */\nimport { z } from \"zod\";\n\nexport const ACTIVECAMPAIGN_WEBHOOK_EVENTS = {\n subscribe: \"A contact subscribes to a list\",\n unsubscribe: \"A contact unsubscribes\",\n update: \"A contact's details change\",\n contact_tag_added: \"A tag is added to a contact\",\n contact_tag_removed: \"A tag is removed from a contact\",\n subscriber_note: \"A note is added to a contact\",\n contact_task_add: \"A task is added to a contact\",\n sent: \"A campaign starts sending\",\n open: \"A contact opens a campaign\",\n click: \"A contact clicks a link in a campaign\",\n reply: \"A contact replies to a campaign\",\n forward: \"A contact forwards a campaign\",\n share: \"A contact shares a campaign\",\n bounce: \"A campaign email bounces\",\n list_add: \"A list is created\",\n deal_add: \"A deal is created\",\n deal_update: \"A deal changes\",\n deal_note_add: \"A note is added to a deal\",\n deal_task_add: \"A task is added to a deal\",\n deal_task_complete: \"A deal task is completed\",\n deal_pipeline_add: \"A pipeline is created\",\n deal_stage_add: \"A deal stage is created\",\n deal_tasktype_add: \"A deal task type is created\",\n account_add: \"An account is created\",\n account_update: \"An account changes\",\n account_contact_add: \"A contact is added to an account\",\n account_contact_update: \"A contact on an account changes\",\n} as const;\n\nexport type ActiveCampaignWebhookEvent = keyof typeof ACTIVECAMPAIGN_WEBHOOK_EVENTS;\n\nexport const ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES = Object.keys(\n ACTIVECAMPAIGN_WEBHOOK_EVENTS,\n) as readonly ActiveCampaignWebhookEvent[];\n\n/** Who may have caused an event: a contact, a user, an automation, the API — all of them, so nothing is missed. */\nexport const ACTIVECAMPAIGN_WEBHOOK_SOURCES = [\"public\", \"admin\", \"api\", \"system\"] as const;\n\n/** What a new source listens to when nobody says: the lead and deal moments a marketer asks about first. */\nexport const ACTIVECAMPAIGN_DEFAULT_EVENTS: readonly ActiveCampaignWebhookEvent[] = [\n \"subscribe\",\n \"contact_tag_added\",\n \"deal_add\",\n \"deal_update\",\n];\n\n/** The source's name when nobody gives one. */\nexport const ACTIVECAMPAIGN_SOURCE_NAME = \"ActiveCampaign\";\n\nconst EVENT_PREFIX = \"activecampaign.\";\n\n/** The Baker event an ActiveCampaign webhook event raises: `subscribe` → `activecampaign.subscribe`. */\nexport function activeCampaignEventName(type: string): string {\n return `${EVENT_PREFIX}${type}`;\n}\n\n/** The ActiveCampaign event behind a Baker event name, or null when it is not one. */\nexport function activeCampaignEventOf(eventName: string): ActiveCampaignWebhookEvent | null {\n if (!eventName.startsWith(EVENT_PREFIX)) return null;\n const type = eventName.slice(EVENT_PREFIX.length);\n return type in ACTIVECAMPAIGN_WEBHOOK_EVENTS ? (type as ActiveCampaignWebhookEvent) : null;\n}\n\n/** The words for one event, falling back to ActiveCampaign's own name for one this list does not know. */\nexport function activeCampaignEventLabel(type: string): string {\n return type in ACTIVECAMPAIGN_WEBHOOK_EVENTS\n ? ACTIVECAMPAIGN_WEBHOOK_EVENTS[type as ActiveCampaignWebhookEvent]\n : type;\n}\n\n/**\n * The events a source listens to, as the CLI and the dashboard hand them in:\n * ActiveCampaign's names, or Baker's `activecampaign.<type>` spelling of them,\n * deduplicated, in the catalogue's order.\n */\nexport const activeCampaignEventsSchema = z\n .array(z.string().trim().min(1))\n .min(1, \"Pick at least one ActiveCampaign event to listen to.\")\n .max(ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.length)\n .transform((raw, ctx) => {\n const picked = new Set<ActiveCampaignWebhookEvent>();\n for (const item of raw) {\n const type = activeCampaignEventOf(item) ?? (item in ACTIVECAMPAIGN_WEBHOOK_EVENTS ? item : null);\n if (type === null) {\n ctx.addIssue({\n code: \"custom\",\n message: `\"${item}\" is not an ActiveCampaign event. Pick from: ${ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.join(\", \")}.`,\n });\n return z.NEVER;\n }\n picked.add(type as ActiveCampaignWebhookEvent);\n }\n return ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.filter((type) => picked.has(type));\n });\n\n/** Whether ActiveCampaign has the webhook that sends a source its events, as last checked. */\nexport const ACTIVECAMPAIGN_WEBHOOK_STATES = [\"listening\", \"not_configured\", \"failed\"] as const;\nexport type ActiveCampaignWebhookState = (typeof ACTIVECAMPAIGN_WEBHOOK_STATES)[number];\n"],"mappings":";;;;;;;;;;;;;;;;;AAkCO,IAAM,8BAA8B;AAGpC,IAAM,yBAAyB;AAG/B,SAAS,YAAY,UAA0B;AACpD,SAAO,GAAG,sBAAsB,GAAG,QAAQ;AAC7C;AAQO,IAAM,6BAA6E;AAAA,EACxF,OAAO;AAAA,EACP,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AACV;AAMA,IAAM,iBAAiE,OAAO;AAAA,EAC5E,OAAO,QAAQ,0BAA0B,EAAE,IAAI,CAAC,CAAC,OAAO,QAAQ,MAAM,CAAC,OAAO,YAAY,QAAQ,CAAC,CAAC;AACtG;AAQO,IAAM,kCAAkF;AAAA,EAC7F,GAAG;AAAA,EACH,OAAO;AAAA,EACP,UAAU;AACZ;AAQO,IAAM,kCAAkF;AAE/F,IAAM,WAA4F;AAAA,EAChG,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AACR;AAGO,SAAS,sBAC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AAM,oBAAoB,EAAE,SAAS;AAAA,EACjD,CAAC;AAAA,EACD,OAAOA,GAAE,MAAMA,GAAE,OAAO,CAAC,EAAE,SAAS;AACtC,CAAC;","names":["z","z","z"]}
|
package/dist/cli.js
CHANGED
|
@@ -627,7 +627,7 @@ Introspection: Run 'baker schema <command>' to inspect argument schemas.`
|
|
|
627
627
|
"scheduled-agents": () => import("./scheduled-agents-7QQNV4N6.js").then((m) => m.scheduledAgentsCommand),
|
|
628
628
|
ads: () => import("./ads-F6IN27LX.js").then((m) => m.adsCommand),
|
|
629
629
|
brand: () => import("./brand-ARJMSWJA.js").then((m) => m.brandCommand),
|
|
630
|
-
analytics: () => import("./analytics-
|
|
630
|
+
analytics: () => import("./analytics-2JEGNTNZ.js").then((m) => m.analyticsCommand),
|
|
631
631
|
experiment: () => import("./experiment-KOCG7PPI.js").then((m) => m.experimentCommand),
|
|
632
632
|
ga4: () => import("./ga4-RWTSGUNB.js").then((m) => m.ga4Command),
|
|
633
633
|
gsc: () => import("./gsc-JYP4ZCSH.js").then((m) => m.gscCommand),
|
|
@@ -649,10 +649,10 @@ Introspection: Run 'baker schema <command>' to inspect argument schemas.`
|
|
|
649
649
|
canvas: () => import("./canvas-23IQXJEF.js").then((m) => m.canvasCommand),
|
|
650
650
|
tags: () => import("./tags-FAOFI4Y6.js").then((m) => m.tagsCommand),
|
|
651
651
|
"tag-manager": () => import("./tag-manager-UJDARCXH.js").then((m) => m.tagManagerCommand),
|
|
652
|
-
chats: () => import("./chats-
|
|
652
|
+
chats: () => import("./chats-UHN7JXOR.js").then((m) => m.chatsCommand),
|
|
653
653
|
history: () => import("./history-XIZQ7GK5.js").then((m) => m.historyCommand),
|
|
654
654
|
credentials: () => import("./credentials-TLN4MYX5.js").then((m) => m.credentialsCommand),
|
|
655
|
-
hubspot: () => import("./hubspot-
|
|
655
|
+
hubspot: () => import("./hubspot-72LKX7CR.js").then((m) => m.hubspotCommand),
|
|
656
656
|
activecampaign: () => import("./activecampaign-U4GIT3HE.js").then((m) => m.activecampaignCommand),
|
|
657
657
|
pipedrive: () => import("./pipedrive-SUYPR2EH.js").then((m) => m.pipedriveCommand),
|
|
658
658
|
accounts: () => import("./accounts-DBTLIKZI.js").then((m) => m.accountsCommand),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./chunk-
|
|
1
|
+
import "./chunk-NRU2A7TJ.js";
|
|
2
2
|
import {
|
|
3
3
|
failNotConnected
|
|
4
4
|
} from "./chunk-4XYYFIIL.js";
|
|
@@ -857,4 +857,4 @@ export {
|
|
|
857
857
|
hubspotCommand,
|
|
858
858
|
workflowViewHints
|
|
859
859
|
};
|
|
860
|
-
//# sourceMappingURL=hubspot-
|
|
860
|
+
//# sourceMappingURL=hubspot-72LKX7CR.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
hubspotDefaultMapping,
|
|
3
3
|
hubspotTriggerInputSchema
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-NRU2A7TJ.js";
|
|
5
5
|
import {
|
|
6
6
|
hubspotRefusal
|
|
7
7
|
} from "./chunk-4XYYFIIL.js";
|
|
@@ -94,6 +94,11 @@ var args = {
|
|
|
94
94
|
description: "Ask HubSpot what --property --operator --value would count today, and read one real contact \u2014 the one most recently there, or --contact \u2014 with the properties the --field rows mention (the defaults when none), to check every row against real data BEFORE --create-hubspot. Makes nothing",
|
|
95
95
|
required: false
|
|
96
96
|
},
|
|
97
|
+
breakdown: {
|
|
98
|
+
type: "boolean",
|
|
99
|
+
description: "With --preview on one dropdown --property (operator `is`) and several --value: also a total for each value, as `preview.counts: [{value, total}]` \u2014 sizing every stage of a funnel in one call: `--preview --object deal --property dealstage --value appointmentscheduled --value closedwon --breakdown`. Never loop --preview over values",
|
|
100
|
+
required: false
|
|
101
|
+
},
|
|
97
102
|
object: {
|
|
98
103
|
type: "string",
|
|
99
104
|
description: "With --create-hubspot or --preview: what the trigger is on \u2014 `contact` (the default), `deal` or `lead`. A deal's and a lead's event is about the contact the record is associated with: its rows read the record's own properties bare ({{amount}}, {{dealstage}}, {{hs_pipeline_stage}}) and the contact's as {{contact.<name>}} (`baker hubspot deals fields` / `baker hubspot leads fields`). A deal's amount defaults to its own amount in its currency; a lead has none, so it counts the step rather than money. Use `lead` for qualification and disqualification \u2014 HubSpot records both as a lead stage, and nothing on the contact or the deal says a lead was disqualified",
|
|
@@ -322,7 +327,8 @@ function previewArgs(raw, argv) {
|
|
|
322
327
|
...object === "contact" ? {} : { object },
|
|
323
328
|
trigger: triggerArgs(raw, argv, "preview"),
|
|
324
329
|
properties,
|
|
325
|
-
...contact === void 0 ? {} : { contact }
|
|
330
|
+
...contact === void 0 ? {} : { contact },
|
|
331
|
+
...raw.breakdown === true ? { breakdown: true } : {}
|
|
326
332
|
};
|
|
327
333
|
}
|
|
328
334
|
var VERBS = [
|
|
@@ -426,7 +432,7 @@ function handleError(err) {
|
|
|
426
432
|
var sourcesCommand = defineCommand({
|
|
427
433
|
meta: {
|
|
428
434
|
name: "sources",
|
|
429
|
-
description: 'Where events reach Baker from a server, and what each one reads. Two doors. **The client\'s own server**: `--server` prints one address for their developers \u2014 made once, the same for ever, counting at once, Baker\'s own `POST /v1/events` format (`baker analytics sending-events` has the contract, `X-Baker-Mode: test` rehearses). **HubSpot events**: HubSpot keeps each change to a watched property in a journal Baker reads every half minute \u2014 Baker\'s app subscribes the account to that one property with the condition as HubSpot\'s own filter, so an account with a million contacts costs nothing to watch \u2014 on every plan, nothing to set up in HubSpot. The trigger is *when a contact\'s* property satisfies a condition \u2014 the same conditions a Form\'s filters take: `--property lifecyclestage --value customer` (a dropdown; `--value lead --value customer` for either), `--property deal_value --operator greaterThan --value 1000`, `--property email --operator endsWith --value @acme.com`, `--property closed_at --operator isAfter --value 2026-01-01`, `--property phone --operator isEmpty`. Several conditions combine the way a Form\'s filter does \u2014 `--conditions \'{"logic":"And","conditions":[{"property":"lifecyclestage","values":["customer"]},{"property":"country","values":["Spain"]}]}\'` (AND / OR, groups one level deep, 10 conditions at most) in place of --property/--operator/--value, on --create-hubspot, --set-trigger and --preview; the event fires when a change to any named property makes the whole combination hold. `baker hubspot contacts properties` lists every property with its kind, the operators that kind takes and a dropdown\'s values; `baker hubspot contacts fields` every property a row can read. `--preview --property \u2026 [--operator \u2026] --value \u2026 [--field \u2026] [--contact <id or email>]` says how many contacts satisfy it today (NOT counted \u2014 only contacts that come to satisfy it from now on are) and reads one real contact so every row can be checked against real data; then `--create-hubspot --property \u2026 --value \u2026 --name "Deal won" --field email={{work_email}} --field value={{deal_value}} --field currency=EUR` makes the event, rows over the defaults (email, phone, the contact id, name, address, hs_google_click_id, hs_facebook_click_id). `--set-trigger --source <id> --property \u2026 --operator \u2026 --value \u2026` changes what an event watches later (rows kept, counting from now on). Every row is a template \u2014 text with {{property}} mentions, one thing per mention; `--map --source <id> --field \u2026` replaces the whole row set later, `--amount-property <number property> --currency EUR` is the short spelling for the amount rows. Each event is an ordinary event named after the source, carrying `baker_source`, listed by `feed --source <name>`, counted with `conversions` under `page:<name>`, and sent to the ad platforms with `sends`. **ActiveCampaign events**: `--create-activecampaign [--events subscribe,deal_update] [--name \u2026] [--account <id>]` stages a source that the ActiveCampaign webhook sends to once the chat is published; each arrival is an event called `activecampaign.<event>` \u2014 whatever the source is called \u2014 carrying the contact and the rest of the ActiveCampaign payload as `properties.*` (the stage of a deal, the tag, the campaign), which is what a scheduled agent on `event.received --event activecampaign.<event>` runs on. `--pause`, `--resume`, `--remove` by --source; removing an ActiveCampaign source deletes its webhook. `--create --name <tool>` still makes an address for a tool that cannot be told what to send; its first send is a masked sample counted as nothing until `--map` confirms the rows.'
|
|
435
|
+
description: 'Where events reach Baker from a server, and what each one reads. Two doors. **The client\'s own server**: `--server` prints one address for their developers \u2014 made once, the same for ever, counting at once, Baker\'s own `POST /v1/events` format (`baker analytics sending-events` has the contract, `X-Baker-Mode: test` rehearses). **HubSpot events**: HubSpot keeps each change to a watched property in a journal Baker reads every half minute \u2014 Baker\'s app subscribes the account to that one property with the condition as HubSpot\'s own filter, so an account with a million contacts costs nothing to watch \u2014 on every plan, nothing to set up in HubSpot. The trigger is *when a contact\'s* property satisfies a condition \u2014 the same conditions a Form\'s filters take: `--property lifecyclestage --value customer` (a dropdown; `--value lead --value customer` for either), `--property deal_value --operator greaterThan --value 1000`, `--property email --operator endsWith --value @acme.com`, `--property closed_at --operator isAfter --value 2026-01-01`, `--property phone --operator isEmpty`. Several conditions combine the way a Form\'s filter does \u2014 `--conditions \'{"logic":"And","conditions":[{"property":"lifecyclestage","values":["customer"]},{"property":"country","values":["Spain"]}]}\'` (AND / OR, groups one level deep, 10 conditions at most) in place of --property/--operator/--value, on --create-hubspot, --set-trigger and --preview; the event fires when a change to any named property makes the whole combination hold. `baker hubspot contacts properties` lists every property with its kind, the operators that kind takes and a dropdown\'s values; `baker hubspot contacts fields` every property a row can read. `--preview --property \u2026 [--operator \u2026] --value \u2026 [--breakdown] [--field \u2026] [--contact <id or email>]` says how many contacts satisfy it today (NOT counted \u2014 only contacts that come to satisfy it from now on are), `--breakdown` a total per --value in the same call, and reads one real contact so every row can be checked against real data; then `--create-hubspot --property \u2026 --value \u2026 --name "Deal won" --field email={{work_email}} --field value={{deal_value}} --field currency=EUR` makes the event, rows over the defaults (email, phone, the contact id, name, address, hs_google_click_id, hs_facebook_click_id). `--set-trigger --source <id> --property \u2026 --operator \u2026 --value \u2026` changes what an event watches later (rows kept, counting from now on). Every row is a template \u2014 text with {{property}} mentions, one thing per mention; `--map --source <id> --field \u2026` replaces the whole row set later, `--amount-property <number property> --currency EUR` is the short spelling for the amount rows. Each event is an ordinary event named after the source, carrying `baker_source`, listed by `feed --source <name>`, counted with `conversions` under `page:<name>`, and sent to the ad platforms with `sends`. **ActiveCampaign events**: `--create-activecampaign [--events subscribe,deal_update] [--name \u2026] [--account <id>]` stages a source that the ActiveCampaign webhook sends to once the chat is published; each arrival is an event called `activecampaign.<event>` \u2014 whatever the source is called \u2014 carrying the contact and the rest of the ActiveCampaign payload as `properties.*` (the stage of a deal, the tag, the campaign), which is what a scheduled agent on `event.received --event activecampaign.<event>` runs on. `--pause`, `--resume`, `--remove` by --source; removing an ActiveCampaign source deletes its webhook. `--create --name <tool>` still makes an address for a tool that cannot be told what to send; its first send is a masked sample counted as nothing until `--map` confirms the rows.'
|
|
430
436
|
},
|
|
431
437
|
args,
|
|
432
438
|
run: async ({ args: raw }) => {
|
|
@@ -461,4 +467,4 @@ export {
|
|
|
461
467
|
sourcesCommand,
|
|
462
468
|
sourcesRequest
|
|
463
469
|
};
|
|
464
|
-
//# sourceMappingURL=sources-
|
|
470
|
+
//# sourceMappingURL=sources-2TG66AZO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/analytics/sources.ts"],"sourcesContent":["import { REJECTION_MESSAGES, validateEventName } from \"@baker/api/event-ingest\";\nimport {\n HUBSPOT_DEAL_CONTACTS,\n HUBSPOT_OBJECTS,\n type HubspotDealContacts,\n type HubspotObject,\n hubspotDefaultMapping,\n hubspotTriggerInputSchema,\n mappingRowProblem,\n readsAssociatedContact,\n SOURCE_FIELD_NAMES,\n type SourcesRequestInput,\n type SourcesResponse,\n templateMentions,\n} from \"@baker/api/event-sources\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { hubspotRefusal } from \"../hubspot/refusal.ts\";\nimport { ConversionArgsError, onlyOnce } from \"./conversionArgs.ts\";\n\n/**\n * `baker analytics sources` — an address for each of the client's own tools to\n * send events to, and what each one's payloads are read as.\n *\n * ## Why a URL and not a key\n *\n * `POST /v1/events` needs the sender to write code to our contract. A CRM's\n * webhook, an automation platform, a billing system cannot be told what to\n * send — they post what they post, to a URL, and set nothing else. A source\n * is that URL: the token in it is the whole credential, the first send\n * teaches Baker the shape, and a person confirms once which path is the\n * email, which the amount. From then on every arrival is an ordinary event.\n *\n * ## `--field` and `--value` repeat, and citty keeps only the last\n *\n * citty hands the LAST value of a repeated flag over as a plain string, so\n * `--field email=a --field value=b` would map `value` and silently drop\n * `email`, and `--value lead --value customer` would watch `customer` alone.\n * Both are read off `process.argv` instead, the way `conversions` reads its\n * repeats.\n */\n\nconst args = {\n server: {\n type: \"boolean\",\n description:\n \"The client's own server door: one address for their developers, made once and the same for ever after, counting at once in Baker's own format (`baker analytics sending-events` has the contract). Prints it; nothing else to set\",\n required: false,\n },\n create: {\n type: \"boolean\",\n description:\n \"Make an address for a tool that cannot be told what to send (a CRM webhook, an automation step). Needs --name. Its first send is kept as a sample and counted as nothing until --map\",\n required: false,\n },\n \"create-hubspot\": {\n type: \"boolean\",\n description:\n \"Make a HubSpot event: HubSpot keeps each change to --property for Baker (Baker's app subscribes the account to that property with the condition as HubSpot's own filter, and nothing else), and every contact whose new value satisfies --operator --value is an event, counted within a minute. Needs --property (names, kinds and operators from `baker hubspot contacts properties`); --operator defaults to `is`; --value repeats for a list (`is` on a dropdown) or a between; --name is optional and defaults to the trigger's words; --field rows (names from `baker hubspot contacts fields`) replace the default rows they name. Counts from now on, never earlier contacts\",\n required: false,\n },\n \"create-activecampaign\": {\n type: \"boolean\",\n description:\n \"Make an ActiveCampaign event source: when this chat is published, ActiveCampaign's own webhook is set up on the account to send --events here, and each one counts as `activecampaign.<event>` (a contact subscribing is `activecampaign.subscribe`) from then on — a scheduled agent can run on any of them (`baker scheduled-agents create --trigger event.received --event activecampaign.deal_update`). --events defaults to subscribe,contact_tag_added,deal_add,deal_update; --name to ActiveCampaign; --account picks the connection when there are several. Removing the source takes the webhook off the account\",\n required: false,\n },\n events: {\n type: \"string\",\n description:\n \"With --create-activecampaign: ActiveCampaign's events, comma-separated — subscribe, unsubscribe, update, contact_tag_added, contact_tag_removed, subscriber_note, contact_task_add, sent, open, click, reply, forward, share, bounce, list_add, deal_add, deal_update, deal_note_add, deal_task_add, deal_task_complete, deal_pipeline_add, deal_stage_add, deal_tasktype_add, account_add, account_update, account_contact_add, account_contact_update\",\n required: false,\n },\n account: {\n type: \"string\",\n description:\n \"With --create-activecampaign: which ActiveCampaign connection, by id, when the company has more than one (the refusal lists them)\",\n required: false,\n },\n \"set-trigger\": {\n type: \"boolean\",\n description:\n \"Change what a HubSpot event watches. Needs --source and the same --property --operator --value as --create-hubspot. The rows stay; it counts from now on under the new trigger\",\n required: false,\n },\n preview: {\n type: \"boolean\",\n description:\n \"Ask HubSpot what --property --operator --value would count today, and read one real contact — the one most recently there, or --contact — with the properties the --field rows mention (the defaults when none), to check every row against real data BEFORE --create-hubspot. Makes nothing\",\n required: false,\n },\n breakdown: {\n type: \"boolean\",\n description:\n \"With --preview on one dropdown --property (operator `is`) and several --value: also a total for each value, as `preview.counts: [{value, total}]` — sizing every stage of a funnel in one call: `--preview --object deal --property dealstage --value appointmentscheduled --value closedwon --breakdown`. Never loop --preview over values\",\n required: false,\n },\n object: {\n type: \"string\",\n description:\n \"With --create-hubspot or --preview: what the trigger is on — `contact` (the default), `deal` or `lead`. A deal's and a lead's event is about the contact the record is associated with: its rows read the record's own properties bare ({{amount}}, {{dealstage}}, {{hs_pipeline_stage}}) and the contact's as {{contact.<name>}} (`baker hubspot deals fields` / `baker hubspot leads fields`). A deal's amount defaults to its own amount in its currency; a lead has none, so it counts the step rather than money. Use `lead` for qualification and disqualification — HubSpot records both as a lead stage, and nothing on the contact or the deal says a lead was disqualified\",\n required: false,\n },\n contacts: {\n type: \"string\",\n description:\n \"With --object deal or --object lead (on --create-hubspot or --set-trigger): whose event it is — `every` (the default: every contact on the record, each its own event; on a deal each worth the deal's amount) or `first` (the record's first contact only)\",\n required: false,\n },\n property: {\n type: \"string\",\n description:\n \"With --create-hubspot, --set-trigger or --preview: the property to watch, by HubSpot's internal name (lifecyclestage, hs_lead_status, a custom one on a contact; dealstage, amount, closedate on a deal; hs_pipeline_stage, hs_lead_label on a lead) — any property, whatever its kind\",\n required: false,\n },\n operator: {\n type: \"string\",\n description:\n \"With --property: how the property has to read. By the property's kind — select: is, isNot, isEmpty, isNotEmpty · text: is, isNot, contains, doesNotContain, startsWith, endsWith, isEmpty, isNotEmpty · number: equal, notEqual, lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual, isEmpty, isNotEmpty · date: is, isBefore, isAfter, isOnOrBefore, isOnOrAfter, isBetween, isEmpty, isNotEmpty · yes/no: is, isNot. `is` when unsaid\",\n required: false,\n },\n value: {\n type: \"string\",\n description:\n \"With --property: the value, as HubSpot spells it — a dropdown's internal value (customer, QUALIFIED…), a number, a YYYY-MM-DD, true/false. Repeat it for a list (--value lead --value customer) or the two ends of isBetween; none for isEmpty / isNotEmpty\",\n required: false,\n },\n conditions: {\n type: \"string\",\n description:\n 'With --create-hubspot, --set-trigger or --preview, instead of --property/--operator/--value: several conditions combined the way a Form\\'s filter combines them, as JSON — `{\"logic\":\"And\",\"conditions\":[{\"property\":\"lifecyclestage\",\"values\":[\"customer\"]},{\"logic\":\"Or\",\"conditions\":[{\"property\":\"country\",\"values\":[\"Spain\"]},{\"property\":\"amount\",\"operator\":\"greaterThan\",\"values\":[\"1000\"]}]}]}`. `logic` is And (every row) or Or (any row); a row is a condition or a group with its own logic, one level deep; at most 10 conditions. The event fires when a change to any named property makes the whole combination hold',\n required: false,\n },\n contact: {\n type: \"string\",\n description:\n \"With --preview: the record to draw the sample from — a HubSpot id, or text to search (an email or a name for a contact, a deal's or a lead's name). The one most recently satisfying the trigger when unsaid\",\n required: false,\n },\n \"amount-property\": {\n type: \"string\",\n description:\n \"With --create-hubspot or --set-amount: a NUMBER property of the watched object to read as the event's amount (a deal value synced onto the contact; a deal's own `amount` is read by default on a deal). Needs --currency beside it\",\n required: false,\n },\n currency: {\n type: \"string\",\n description: \"With --amount-property: the three-letter currency the property is in, like EUR or USD\",\n required: false,\n },\n \"set-amount\": {\n type: \"boolean\",\n description:\n \"Change where a HubSpot-read source takes its amount from. Needs --source; with --amount-property and --currency it reads them, with neither it stops reading an amount\",\n required: false,\n },\n backfill: {\n type: \"boolean\",\n description:\n \"Count a HubSpot event's history: every moment its trigger came to hold since --since, at the instant HubSpot says it did. Needs --source and --since. Nothing is invented — a record that merely satisfies the trigger today is not an event today, and only moments HubSpot has a timestamp for are counted. Dry without --write. Reach for it when an event was made after the deals it should have counted, or after fixing one that was refusing everything it received\",\n required: false,\n },\n since: {\n type: \"string\",\n description:\n \"With --backfill: the date to count this event's history from, `2026-09-19` or an ISO instant. At most 400 days back — the store keeps no more\",\n required: false,\n },\n before: {\n type: \"string\",\n description:\n \"With --backfill: carry on from where a capped run stopped, by passing back the `reachedBack` it returned. One run reads at most 500 records, most recently changed first, so a capped run has covered the newest and the rest are the ones nearest --since — narrowing --since cannot reach them, this can. Repeat until `capped` is false; nothing is counted twice. It bounds which records are read, never which of their moments count: those are still the whole of --since to now\",\n required: false,\n },\n write: {\n type: \"boolean\",\n description:\n \"With --backfill: actually count what it found. Without it nothing is counted and the answer says what would be. Events inside the last 72 hours are uploaded to this event's ad platforms within minutes of counting, which spends real budget\",\n required: false,\n },\n name: {\n type: \"string\",\n description:\n \"The tool the source is for — HubSpot, Zapier, Stripe. It is the event's name when the payload does not say one, and every event it sends carries it as `baker_source`\",\n required: false,\n },\n map: {\n type: \"boolean\",\n description:\n \"Set what each field is read from. For an address this starts counting; needs --source, and one --field per row. With no --field the guess is used, which is right for a tool already sending Baker's own format. For a HubSpot-read source it replaces the whole mapping (the row list is on the source as `mapping`; empty means HubSpot's standard properties), so repeat every row you want kept\",\n required: false,\n },\n source: { type: \"string\", description: \"The source id, from the list\", required: false },\n field: {\n type: \"string\",\n description: `<field>=<template>, repeatable. A template is text with {{path}} mentions, one thing per mention: --field email={{contact.email}} --field currency=EUR --field first_name=\"{{who.first}} {{who.last}}\". A bare path (--field email=contact.email) is read as its mention when the sample has that path, so the short spelling still works. Fields: ${SOURCE_FIELD_NAMES.join(\", \")}. An EXTRA PROPERTY of the event — a plan, a stage, anything Measure → Events should break it down by and a send may pass on to a platform — is --field properties.<name>=<template>, e.g. --field properties.plan={{plan_tier}}. Paths come from \\`paths\\` on the source's sample; for a HubSpot event they are contact property names (\\`baker hubspot contacts fields\\`) plus \\`id\\` for the contact id`,\n required: false,\n },\n pause: {\n type: \"boolean\",\n description: \"Stop counting a source's arrivals; they are answered and dropped. Needs --source\",\n required: false,\n },\n resume: { type: \"boolean\", description: \"Count a paused source's arrivals again. Needs --source\", required: false },\n remove: {\n type: \"boolean\",\n description: \"Delete a source; its address stops working at once. Needs --source\",\n required: false,\n },\n full: {\n type: \"boolean\",\n description:\n \"Also return each source's masked sample body. The paths and the guess are always returned; the body is only for reading what a path held\",\n required: false,\n },\n} as const;\n\nregisterSchema({\n command: \"analytics.sources\",\n routes: [\"POST /api/analytics/sources\"],\n effect: \"write\",\n description:\n \"Where events reach Baker from a server: the client's own server door, HubSpot events Baker reads, and ActiveCampaign events its webhook sends — what each one watches and reads, and how it is doing\",\n args,\n});\n\n/** The value a repeated flag carries at this position, in either spelling, or nothing. */\nfunction flagValueAt(argv: readonly string[], flag: string, index: number): string | undefined {\n const arg = argv[index] ?? \"\";\n if (arg === flag) return argv[index + 1];\n return arg.startsWith(`${flag}=`) ? arg.slice(flag.length + 1) : undefined;\n}\n\n/** Every value of a repeated flag on the command line, in order. */\nexport function parseRepeated(argv: readonly string[], flag: string): string[] {\n const values: string[] = [];\n for (let index = 0; index < argv.length; index += 1) {\n const value = flagValueAt(argv, flag, index);\n if (value !== undefined) values.push(value);\n }\n return values;\n}\n\n/** Every `--field k=v` on the command line, in order, refusing a malformed one. */\nexport function parseFieldArgs(argv: readonly string[]): Record<string, string> {\n const mapping: Record<string, string> = {};\n for (const pair of parseRepeated(argv, \"--field\")) {\n const eq = pair.indexOf(\"=\");\n const field = eq === -1 ? pair : pair.slice(0, eq);\n const path = eq === -1 ? \"\" : pair.slice(eq + 1).trim();\n const problem = mappingRowProblem(field);\n if (problem !== null) throw new ConversionArgsError(problem);\n if (path === \"\") throw new ConversionArgsError(`--field ${field} needs a path: --field ${field}=<dotted.path>.`);\n mapping[field] = path;\n }\n return mapping;\n}\n\n/** The amount pair, which travels together or not at all. */\nfunction amountArgs(raw: Record<string, unknown>, argv: readonly string[]) {\n const amountProperty = onlyOnce(raw[\"amount-property\"], \"--amount-property\", argv);\n const currency = onlyOnce(raw.currency, \"--currency\", argv);\n if ((amountProperty === undefined) !== (currency === undefined)) {\n throw new ConversionArgsError(\"--amount-property and --currency go together: name both or neither.\");\n }\n return {\n ...(amountProperty === undefined ? {} : { amountProperty }),\n ...(currency === undefined ? {} : { currency }),\n };\n}\n\nconst NO_VALUE_OPERATORS = new Set([\"isEmpty\", \"isNotEmpty\"]);\n\n/**\n * The trigger every HubSpot verb needs: the property, how it has to read,\n * and the values — repeated on the command line, read off argv. Refused with\n * where the names come from; what the property's kind allows is checked\n * against the account by the backend.\n */\nfunction triggerArgs(raw: Record<string, unknown>, argv: readonly string[], verb: string): TriggerInput {\n const conditions = onlyOnce(raw.conditions, \"--conditions\", argv);\n if (conditions !== undefined) return conditionsArg(conditions, raw, verb);\n const property = onlyOnce(raw.property, \"--property\", argv);\n const operator = onlyOnce(raw.operator, \"--operator\", argv) ?? \"is\";\n // The last --value is what citty kept; every one is what was typed.\n const values = argv.length === 0 && typeof raw.value === \"string\" ? [raw.value] : parseRepeated(argv, \"--value\");\n if (property === undefined) {\n throw new ConversionArgsError(\n `--${verb} needs --property <name> [--operator <op>] --value <value>…, from \\`baker hubspot contacts properties\\`.`,\n );\n }\n if (values.length === 0 && !NO_VALUE_OPERATORS.has(operator)) {\n throw new ConversionArgsError(\n `--${verb} needs --value <value> (repeat it for a list); only --operator isEmpty / isNotEmpty take none.`,\n );\n }\n return { property, operator, values };\n}\n\ntype TriggerInput = NonNullable<SourcesRequestInput[\"createHubspot\"]>[\"trigger\"];\n\n/** `--conditions <json>`: a combination, checked for shape here so a typo is refused before the call. */\nfunction conditionsArg(text: string, raw: Record<string, unknown>, verb: string): TriggerInput {\n if (raw.property !== undefined || raw.value !== undefined || raw.operator !== undefined) {\n throw new ConversionArgsError(`--${verb} takes --conditions or --property/--operator/--value, not both.`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new ConversionArgsError(\n '--conditions is JSON: {\"logic\":\"And\",\"conditions\":[{\"property\":\"lifecyclestage\",\"values\":[\"customer\"]}]}.',\n );\n }\n const checked = hubspotTriggerInputSchema.safeParse(parsed);\n if (!checked.success) {\n throw new ConversionArgsError(`--conditions: ${checked.error.issues.map((issue) => issue.message).join(\"; \")}`);\n }\n return parsed as TriggerInput;\n}\n\n/** `--object contact|deal`, spelled the two ways the wire takes and nothing else. */\nfunction objectArg(raw: Record<string, unknown>, argv: readonly string[]): HubspotObject {\n const object = onlyOnce(raw.object, \"--object\", argv) ?? \"contact\";\n if (!(HUBSPOT_OBJECTS as readonly string[]).includes(object)) {\n throw new ConversionArgsError(`--object is one of ${HUBSPOT_OBJECTS.join(\", \")}, not \"${object}\".`);\n }\n return object as HubspotObject;\n}\n\n/** `--contacts first|every`, which only means something on a deal or a lead. */\nfunction contactsArg(raw: Record<string, unknown>, argv: readonly string[]): HubspotDealContacts | undefined {\n const contacts = onlyOnce(raw.contacts, \"--contacts\", argv);\n if (contacts === undefined) return undefined;\n if (!(HUBSPOT_DEAL_CONTACTS as readonly string[]).includes(contacts)) {\n throw new ConversionArgsError(`--contacts is one of ${HUBSPOT_DEAL_CONTACTS.join(\", \")}, not \"${contacts}\".`);\n }\n return contacts as HubspotDealContacts;\n}\n\nfunction createHubspotArgs(\n raw: Record<string, unknown>,\n argv: readonly string[],\n name: string | undefined,\n): NonNullable<SourcesRequestInput[\"createHubspot\"]> {\n const mapping = parseFieldArgs(argv);\n const object = objectArg(raw, argv);\n const contacts = contactsArg(raw, argv);\n if (contacts !== undefined && !readsAssociatedContact(object)) {\n throw new ConversionArgsError(\n \"--contacts says whose event a deal's or a lead's is; it needs --object deal or --object lead.\",\n );\n }\n return {\n // A contact is the wire's default, so it is left unsaid — the way the schema reads it back.\n ...(object === \"contact\" ? {} : { object }),\n trigger: triggerArgs(raw, argv, \"create-hubspot\"),\n ...(contacts === undefined ? {} : { contacts }),\n ...(name === undefined ? {} : { name }),\n ...(Object.keys(mapping).length === 0 ? {} : { mapping }),\n ...amountArgs(raw, argv),\n };\n}\n\n/** What to read off the sample contact: whatever the rows mention, or the default rows' properties. */\nfunction previewArgs(\n raw: Record<string, unknown>,\n argv: readonly string[],\n): NonNullable<SourcesRequestInput[\"preview\"]> {\n const rows = parseFieldArgs(argv);\n const object = objectArg(raw, argv);\n const templates = Object.values(Object.keys(rows).length === 0 ? hubspotDefaultMapping(\"\", object) : rows);\n const properties = [...new Set(templates.flatMap((template) => templateMentions(template ?? \"\")))];\n const contact = onlyOnce(raw.contact, \"--contact\", argv);\n return {\n ...(object === \"contact\" ? {} : { object }),\n trigger: triggerArgs(raw, argv, \"preview\"),\n properties,\n ...(contact === undefined ? {} : { contact }),\n ...(raw.breakdown === true ? { breakdown: true } : {}),\n };\n}\n\nconst VERBS = [\n \"server\",\n \"create\",\n \"create-hubspot\",\n \"create-activecampaign\",\n \"set-trigger\",\n \"preview\",\n \"backfill\",\n \"set-amount\",\n \"map\",\n \"pause\",\n \"resume\",\n \"remove\",\n] as const;\n\n/**\n * The name, refused here when the ingest door could never accept it.\n *\n * A source's name is the `event_name` of every event it raises, so this is\n * not a label being tidied: a name outside the rule makes a source that\n * counts **nothing**, for ever, while `baker analytics sources` goes on\n * listing it as counting and the only trace is one red line per event on the\n * feed. The contract refuses it too (`sourceNameSchema`), but that comes back\n * as a wire-validation error; the agent is better served by the sentence.\n */\nfunction checkedName(raw: Record<string, unknown>, argv: readonly string[]): string | undefined {\n const name = onlyOnce(raw.name, \"--name\", argv);\n if (name === undefined || validateEventName(name) === null) return name;\n throw new ConversionArgsError(\n `\"${name}\" cannot be an event name, and the name is what every event this source raises will carry. ${REJECTION_MESSAGES.invalid_name}`,\n );\n}\n\n/** What a backfill reads back to, and whether it counts what it finds. */\nfunction backfillArgs(\n raw: Record<string, unknown>,\n argv: readonly string[],\n sourceId: string,\n): NonNullable<SourcesRequestInput[\"backfill\"]> {\n const since = onlyOnce(raw.since, \"--since\", argv);\n if (since === undefined) {\n throw new ConversionArgsError(\n \"--backfill needs --since <date>, e.g. --since 2026-09-19. Nothing before it is read.\",\n );\n }\n const before = onlyOnce(raw.before, \"--before\", argv);\n return {\n sourceId,\n since,\n ...(before === undefined ? {} : { before }),\n ...(raw.write === true ? { write: true } : {}),\n };\n}\n\nfunction createActiveCampaignArgs(\n raw: Record<string, unknown>,\n argv: readonly string[],\n name: string | undefined,\n): NonNullable<SourcesRequestInput[\"createActiveCampaign\"]> {\n const events = onlyOnce(raw.events, \"--events\", argv);\n const account = onlyOnce(raw.account, \"--account\", argv);\n return {\n ...(name === undefined ? {} : { name }),\n ...(events === undefined\n ? {}\n : {\n events: events\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item !== \"\"),\n }),\n ...(account === undefined ? {} : { account }),\n };\n}\n\n/** The three ways to make a source: an address for a tool, a HubSpot event, ActiveCampaign events. */\nfunction createRequest(\n verb: (typeof VERBS)[number],\n raw: Record<string, unknown>,\n argv: readonly string[],\n name: string | undefined,\n): SourcesRequestInput | null {\n if (verb === \"create\") {\n if (name === undefined) throw new ConversionArgsError(\"--create needs --name <tool>.\");\n return { create: { name } };\n }\n if (verb === \"create-hubspot\") return { createHubspot: createHubspotArgs(raw, argv, name) };\n if (verb === \"create-activecampaign\") return { createActiveCampaign: createActiveCampaignArgs(raw, argv, name) };\n return null;\n}\n\nexport function sourcesRequest(raw: Record<string, unknown>, argv: readonly string[]): SourcesRequestInput {\n const name = checkedName(raw, argv);\n const source = onlyOnce(raw.source, \"--source\", argv);\n const verbs = VERBS.filter((verb) => raw[verb] === true);\n if (verbs.length > 1) throw new ConversionArgsError(`One of --${verbs.join(\", --\")} per call.`);\n const verb = verbs[0];\n if (verb === undefined) return {};\n if (verb === \"server\") return { server: {} };\n const made = createRequest(verb, raw, argv, name);\n if (made !== null) return made;\n if (verb === \"preview\") return { preview: previewArgs(raw, argv) };\n if (source === undefined) throw new ConversionArgsError(`--${verb} needs --source <id>, from the list.`);\n if (verb === \"backfill\") return { backfill: backfillArgs(raw, argv, source) };\n if (verb === \"set-trigger\") {\n const contacts = contactsArg(raw, argv);\n return {\n setTrigger: {\n sourceId: source,\n trigger: triggerArgs(raw, argv, verb),\n ...(contacts === undefined ? {} : { contacts }),\n },\n };\n }\n if (verb === \"set-amount\") return { setAmount: { sourceId: source, ...amountArgs(raw, argv) } };\n if (verb === \"map\") return { map: { sourceId: source, mapping: parseFieldArgs(argv) } };\n return { [verb]: { sourceId: source } };\n}\n\nfunction handleError(err: unknown): never {\n if (err instanceof ApiError) {\n // A HubSpot event needs HubSpot connected, and allowed to read what it watches.\n const refusal = hubspotRefusal(err.code, err.message);\n writeJsonEnvelope({\n ok: false,\n error:\n refusal === null\n ? { code: err.code, message: err.message }\n : { code: refusal.code, message: err.message, fix: refusal.fix },\n });\n process.exit(1);\n }\n writeJsonEnvelope({\n ok: false,\n error: { code: \"NETWORK_ERROR\", message: err instanceof Error ? err.message : \"Unexpected error\" },\n });\n process.exit(1);\n}\n\nexport const sourcesCommand = defineCommand({\n meta: {\n name: \"sources\",\n description:\n 'Where events reach Baker from a server, and what each one reads. Two doors. **The client\\'s own server**: `--server` prints one address for their developers — made once, the same for ever, counting at once, Baker\\'s own `POST /v1/events` format (`baker analytics sending-events` has the contract, `X-Baker-Mode: test` rehearses). **HubSpot events**: HubSpot keeps each change to a watched property in a journal Baker reads every half minute — Baker\\'s app subscribes the account to that one property with the condition as HubSpot\\'s own filter, so an account with a million contacts costs nothing to watch — on every plan, nothing to set up in HubSpot. The trigger is *when a contact\\'s* property satisfies a condition — the same conditions a Form\\'s filters take: `--property lifecyclestage --value customer` (a dropdown; `--value lead --value customer` for either), `--property deal_value --operator greaterThan --value 1000`, `--property email --operator endsWith --value @acme.com`, `--property closed_at --operator isAfter --value 2026-01-01`, `--property phone --operator isEmpty`. Several conditions combine the way a Form\\'s filter does — `--conditions \\'{\"logic\":\"And\",\"conditions\":[{\"property\":\"lifecyclestage\",\"values\":[\"customer\"]},{\"property\":\"country\",\"values\":[\"Spain\"]}]}\\'` (AND / OR, groups one level deep, 10 conditions at most) in place of --property/--operator/--value, on --create-hubspot, --set-trigger and --preview; the event fires when a change to any named property makes the whole combination hold. `baker hubspot contacts properties` lists every property with its kind, the operators that kind takes and a dropdown\\'s values; `baker hubspot contacts fields` every property a row can read. `--preview --property … [--operator …] --value … [--breakdown] [--field …] [--contact <id or email>]` says how many contacts satisfy it today (NOT counted — only contacts that come to satisfy it from now on are), `--breakdown` a total per --value in the same call, and reads one real contact so every row can be checked against real data; then `--create-hubspot --property … --value … --name \"Deal won\" --field email={{work_email}} --field value={{deal_value}} --field currency=EUR` makes the event, rows over the defaults (email, phone, the contact id, name, address, hs_google_click_id, hs_facebook_click_id). `--set-trigger --source <id> --property … --operator … --value …` changes what an event watches later (rows kept, counting from now on). Every row is a template — text with {{property}} mentions, one thing per mention; `--map --source <id> --field …` replaces the whole row set later, `--amount-property <number property> --currency EUR` is the short spelling for the amount rows. Each event is an ordinary event named after the source, carrying `baker_source`, listed by `feed --source <name>`, counted with `conversions` under `page:<name>`, and sent to the ad platforms with `sends`. **ActiveCampaign events**: `--create-activecampaign [--events subscribe,deal_update] [--name …] [--account <id>]` stages a source that the ActiveCampaign webhook sends to once the chat is published; each arrival is an event called `activecampaign.<event>` — whatever the source is called — carrying the contact and the rest of the ActiveCampaign payload as `properties.*` (the stage of a deal, the tag, the campaign), which is what a scheduled agent on `event.received --event activecampaign.<event>` runs on. `--pause`, `--resume`, `--remove` by --source; removing an ActiveCampaign source deletes its webhook. `--create --name <tool>` still makes an address for a tool that cannot be told what to send; its first send is a masked sample counted as nothing until `--map` confirms the rows.',\n },\n args,\n run: async ({ args: raw }) => {\n try {\n const request = sourcesRequest(raw as Record<string, unknown>, process.argv);\n const response = await apiPost<SourcesResponse>(\"/api/analytics/sources\", request);\n const full = raw.full === true;\n const sources = response.data.sources.map((source) => {\n const { sample, ...rest } = source;\n return full || sample === undefined ? source : { ...rest, sample: { receivedAt: sample.receivedAt } };\n });\n writeJsonEnvelope({\n ok: true,\n data: {\n sources,\n ...(response.data.preview === undefined ? {} : { preview: response.data.preview }),\n ...(response.data.staged === undefined ? {} : { staged: response.data.staged }),\n },\n ...(response.hints && response.hints.length > 0 ? { hints: response.hints } : {}),\n });\n } catch (err) {\n if (err instanceof ConversionArgsError) {\n handleError(new ApiError(\"VALIDATION_ERROR\", err.message));\n }\n handleError(err);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,qBAAqB;AA6B9B,IAAM,OAAO;AAAA,EACX,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,kBAAkB;AAAA,IAChB,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,yBAAyB;AAAA,IACvB,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,SAAS;AAAA,IACP,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,eAAe;AAAA,IACb,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,SAAS;AAAA,IACP,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,WAAW;AAAA,IACT,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,QAAQ;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QAAQ;AAAA,UAChF,GAAI,SAAS,KAAK,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,SAAS,KAAK,OAAO;AAAA,QAC/E;AAAA,QACA,GAAI,SAAS,SAAS,SAAS,MAAM,SAAS,IAAI,EAAE,OAAO,SAAS,MAAM,IAAI,CAAC;AAAA,MACjF,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,UAAI,eAAe,qBAAqB;AACtC,oBAAY,IAAI,SAAS,oBAAoB,IAAI,OAAO,CAAC;AAAA,MAC3D;AACA,kBAAY,GAAG;AAAA,IACjB;AAAA,EACF;AACF,CAAC;","names":["verb"]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/chats/index.ts","../src/commands/chats/carry-files.ts","../src/commands/chats/publish-hints.ts"],"sourcesContent":["import type { ChatsDiffResponse, ChatsListResponse, ChatsTranscriptResponse, ChatsViewResponse } from \"@baker/api\";\nimport {\n CHAT_IMPORT_SURFACES,\n type ChatSurfaceDetail,\n type ChatsImportResponse,\n EFFECT_LISTS,\n type EffectList,\n} from \"@baker/api/chats\";\n\ntype ChatImportSurface = (typeof CHAT_IMPORT_SURFACES)[number];\n\nimport { defineCommand } from \"citty\";\nimport { apiPost } from \"../../client.ts\";\nimport { getEnv, requireChatId } from \"../../env.ts\";\nimport { repeatedValues } from \"../../lib/repeatedFlags.ts\";\nimport { rowsAsData, writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { failApi } from \"../actions/shared.ts\";\nimport { applyPatch, patchRefusal, readSourceFiles, revertPatch, type SourceFiles } from \"./carry-files.ts\";\nimport { publishHints, stillPublishingHints } from \"./publish-hints.ts\";\n\nconst STATUS_GROUPS = [\"active\", \"archived\", \"all\"] as const;\nconst REPO_SURFACES = [\"knowledge\", \"company\", \"brand\", \"landings\", \"flows\", \"creatives\"] as const;\n\nfunction parseBoundedInt(raw: string | undefined, name: string, min: number, max: number): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (Number.isNaN(value) || value < min || value > max) {\n throw new Error(`--${name} must be an integer between ${min} and ${max}`);\n }\n return value;\n}\n\nregisterSchema({\n command: \"chats.list\",\n description:\n 'Start here: list other Sessions on this account (newest first) so you can reuse what was done before. Each row shows the Session id, title, status, and a count of what it produced (creatives, landings, actions, flows, reports…). Looking for one? `--search \"PMax Brasil\"` finds the Sessions whose title or conversation holds any of the words, newest first, each with the `match` it was found by; read the match before trusting a row, since more words match more Sessions. Then drill in with `baker chats view <id>`, `baker chats transcript <id>`, or `baker chats diff <id>`. Read-only.',\n args: {\n status: { type: \"string\", description: \"Filter: active|archived|all (default: all)\", required: false },\n limit: { type: \"string\", description: \"Max Sessions to return, 1-100 (default: 20)\", required: false },\n full: { type: \"boolean\", description: \"Include each Session's full change list\", required: false, default: false },\n search: {\n type: \"string\",\n description:\n 'Sessions whose title or conversation holds any of these words, newest first, each with its `match` (e.g. --search \"PMax Brasil\")',\n required: false,\n },\n },\n});\n\nconst listCommand = defineCommand({\n meta: { name: \"list\", description: \"List other Sessions on this account, newest first.\" },\n args: {\n status: { type: \"string\", description: \"Filter: active|archived|all (default: all)\", required: false },\n limit: { type: \"string\", description: \"Max Sessions (1-100, default 20)\", required: false },\n full: { type: \"boolean\", description: \"Include each Session's full change list\", required: false, default: false },\n search: {\n type: \"string\",\n description: \"Sessions whose title or conversation holds any of these words\",\n required: false,\n },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = {};\n if (args.search) {\n body.search = args.search;\n }\n if (args.status) {\n if (!(STATUS_GROUPS as readonly string[]).includes(args.status)) {\n throw new Error(`--status must be one of: ${STATUS_GROUPS.join(\"|\")}`);\n }\n body.status = args.status;\n }\n const limit = parseBoundedInt(args.limit, \"limit\", 1, 100);\n if (limit !== undefined) {\n body.limit = limit;\n }\n if (args.full) {\n body.full = true;\n }\n // Exclude our own Session so we never list ourselves as a reusable \"other\".\n const selfChatId = getEnv().BAKER_CHAT_ID;\n if (selfChatId) {\n body.excludeChatId = selfChatId;\n }\n const response = await apiPost<ChatsListResponse>(\"/api/chats/list\", body);\n writeJson({\n ok: true,\n ...rowsAsData(response.data, \"chats\"),\n ...(response.data.chats.length === 0\n ? {\n hints: [\n args.search\n ? \"No Session's title or conversation holds any of those words. Try other words (a name, a figure), widen with --status all, or drop --search to list the newest.\"\n : \"No Sessions matched. Widen with --status all or a larger --limit.\",\n ],\n }\n : {\n hints: [\n \"Drill in: `baker chats view <id>` for outputs, `chats transcript <id>` for the conversation, `chats diff <id>` for the real file changes.\",\n ],\n }),\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nregisterSchema({\n command: \"chats.view\",\n routes: [\"POST /api/chats/view\"],\n effect: \"read\",\n description:\n \"Inspect one Session's FULL picture of what it changed — the unified `effects`: git content (landings, creatives, flows, knowledge, brand), plus DB-only effects that never touch the repo — Actions, Scheduled agents, Tags, Tag Manager, Google Analytics, ad-platform writes, the funnel (`funnel`: which steps it added, changed or removed, and which ways in it added or removed in `triggersAdded`/`triggersRemoved`), what counts as a conversion (`conversions`), conversion sends, event sources, and every other staged or already-applied change (`otherChanges`: A/B tests, recipes, library images) — each resolved to real detail (names, descriptions, priorities, tag types, ad operations) and, once published, its `outcome`. Also `publish` (what each external surface actually did, with the provider's own error), `activitySummary` (the chat's own timeline counted by action, with its notable rows: status changes, publish start/fail, workspace recoveries, timeouts; the rows whole as `activity` with --full), `usage` (per-thread cost and the Session's token totals), the kickoff (how it was asked), threads, and commits. Effects are `staged` (in-progress draft) or applied. Compact shows at most 25 rows per list; a list cut to fit is named in `truncated` with its total and every row counted by kind and outcome. `activitySummary.capped` true means the Session logged more than 500 timeline rows and the counts cover the newest 500. One surface: `--surface ads.google` returns only that list, every row counted by kind and outcome (`counts`) plus the first 5 rows that did not apply (`notApplied`: staged, failed, skipped, refused); add --full for all of its rows. A completed Session is NOT proof its external changes landed — read `publish`. Use after `baker chats list` to decide whether to reuse it. Read-only.\",\n args: {\n id: { type: \"positional\", description: \"The Session id (from `baker chats list`)\", required: true },\n full: {\n type: \"boolean\",\n description:\n \"Every effect row and the whole activity timeline (compact caps each list at 25 and counts the timeline)\",\n required: false,\n default: false,\n },\n surface: {\n type: \"string\",\n description: `One effect list only, counted by kind and outcome, with the rows that did not apply: ${EFFECT_LISTS.join(\"|\")}`,\n required: false,\n },\n },\n});\n\nfunction effectListArg(raw: string | undefined): EffectList | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const list = EFFECT_LISTS.find((name) => name === raw);\n if (!list) {\n throw new Error(`--surface must be one of: ${EFFECT_LISTS.join(\"|\")}`);\n }\n return list;\n}\n\nfunction surfaceHints(data: ChatSurfaceDetail, full: boolean): string[] {\n const { list, total, notApplied, notAppliedTotal } = data.surface;\n const hints: string[] = [];\n if (!full && notApplied.length < notAppliedTotal) {\n hints.push(\n `notApplied shows ${notApplied.length} of ${notAppliedTotal} rows that did not apply — \\`counts\\` has every one; read them all with \\`baker chats view <id> --surface ${list} --full\\`.`,\n );\n }\n if (!full && notApplied.length < total) {\n hints.push(\n `${list} shows ${notApplied.length} of its ${total} rows; read every row with \\`baker chats view <id> --surface ${list} --full\\`.`,\n );\n }\n hints.push(\"What each platform's Publish did overall, with its errors: `baker chats view <id> --fields publish`.\");\n return hints;\n}\n\nconst viewCommand = defineCommand({\n meta: {\n name: \"view\",\n description: \"Inspect one Session's full effects — git content + actions/tags/ads, kickoff, commits.\",\n },\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n full: { type: \"boolean\", description: \"Include full detail\", required: false, default: false },\n surface: { type: \"string\", description: \"One effect list only, e.g. ads.google\", required: false },\n },\n run: async ({ args }) => {\n try {\n const surface = effectListArg(args.surface);\n const response = await apiPost<ChatsViewResponse>(\"/api/chats/view\", {\n chatId: args.id,\n ...(args.full ? { full: true } : {}),\n ...(surface ? { surface } : {}),\n });\n if (\"surface\" in response.data) {\n writeJson({ ...response, hints: surfaceHints(response.data, args.full) });\n return;\n }\n const hints: string[] = response.data.publish ? publishHints(response.data.publish) : [];\n for (const cut of response.data.truncated ?? []) {\n hints.push(\n `effects.${cut.list} shows ${cut.shown} of ${cut.total} — \\`truncated\\` counts all ${cut.total} by kind and outcome; read that list alone with \\`baker chats view <id> --surface ${cut.list}\\`.`,\n );\n }\n if (response.data.activitySummary?.capped) {\n hints.push(\n \"activitySummary covers only the Session's newest 500 timeline rows: its total and counts leave the earlier ones out.\",\n );\n }\n if (response.data.diffAvailable) {\n hints.push(\"See the real file-level diff of the git content with `baker chats diff <id> --full`.\");\n } else if (response.data.status === \"in_progress\" || response.data.status === \"publishing\") {\n hints.push(\n \"This Session is still in progress — read its current file changes with `baker chats diff <id> --live`.\",\n );\n }\n hints.push(...stillPublishingHints(response.data.status));\n hints.push(\"Read the conversation with `baker chats transcript <id>`.\");\n writeJson({ ...response, hints });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nconst TRANSCRIPT_ROLES = [\"user\", \"assistant\"] as const;\n\n/** Every `--search` given (citty keeps only the last): one text as itself, several as a list matched as any of them. */\nfunction transcriptSearch(rawArgs: readonly string[], parsed: unknown): string | string[] | undefined {\n const texts = repeatedValues(rawArgs, \"search\", parsed).filter((text) => text.trim() !== \"\");\n return texts.length > 1 ? texts : texts[0];\n}\n\nregisterSchema({\n command: \"chats.transcript\",\n routes: [\"POST /api/chats/transcript\"],\n effect: \"read\",\n description:\n \"Start here: read a Session's conversation (user + agent turns), the most recent messages last. Leave out the id to read THIS chat — the way to recover its own earlier words after a context summary (never grep the raw logs on disk). `--search \\\"5.700\\\"` returns only the messages holding the text, from the whole conversation however long — repeat it for several (`--search lead --search GTM`: the messages holding any of them, in one call, never a loop); `--role user` keeps one side; `--turns` keeps each request and the agent's closing message of that turn (a recap). Compact truncates long messages (around the match when searching); add --full for verbatim text. Read-only.\",\n args: {\n id: {\n type: \"positional\",\n description: \"The Session id (from `baker chats list`). Default: this chat\",\n required: false,\n },\n search: {\n type: \"string\",\n description:\n 'Only messages containing this text, case-insensitive (e.g. --search \"5.700\"); repeat it for messages holding any of several (--search lead --search GTM)',\n required: false,\n },\n role: { type: \"string\", description: \"Only one side: user|assistant\", required: false },\n turns: {\n type: \"boolean\",\n description: \"Only each user message and the agent's closing message of that turn\",\n required: false,\n default: false,\n },\n limit: { type: \"string\", description: \"Max messages to return, 1-1000 (default: 100)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Return verbatim (untruncated) message text\",\n required: false,\n default: false,\n },\n },\n});\n\nconst transcriptCommand = defineCommand({\n meta: { name: \"transcript\", description: \"Read a Session's conversation — another one, or this chat's own.\" },\n args: {\n id: { type: \"positional\", description: \"The Session id (default: this chat)\", required: false },\n search: {\n type: \"string\",\n description: \"Only messages containing this text (repeatable: any of them)\",\n required: false,\n },\n role: { type: \"string\", description: \"Only one side: user|assistant\", required: false },\n turns: { type: \"boolean\", description: \"Each request + the closing reply\", required: false, default: false },\n limit: { type: \"string\", description: \"Max messages (1-1000, default 100)\", required: false },\n full: { type: \"boolean\", description: \"Verbatim message text\", required: false, default: false },\n },\n run: async ({ args, rawArgs }) => {\n try {\n // No id reads the caller's own chat, so its earlier words survive a context summary.\n const chatId = args.id ?? getEnv().BAKER_CHAT_ID;\n if (!chatId) {\n throw new Error(\"Pass the Session id: `baker chats transcript <id>` (find it with `baker chats list`).\");\n }\n const body: Record<string, unknown> = { chatId };\n const search = transcriptSearch(rawArgs, args.search);\n if (search !== undefined) body.search = search;\n if (args.role) {\n if (!(TRANSCRIPT_ROLES as readonly string[]).includes(args.role)) {\n throw new Error(`--role must be one of: ${TRANSCRIPT_ROLES.join(\"|\")}`);\n }\n body.role = args.role;\n }\n if (args.turns) {\n body.turns = true;\n }\n const limit = parseBoundedInt(args.limit, \"limit\", 1, 1000);\n if (limit !== undefined) {\n body.limit = limit;\n }\n if (args.full) {\n body.full = true;\n }\n const response = await apiPost<ChatsTranscriptResponse>(\"/api/chats/transcript\", body);\n const hints: string[] = [];\n if (response.data.truncated) {\n hints.push(\"Older messages were dropped to fit --limit. Raise --limit, or narrow with --search.\");\n }\n if (response.data.answersNotKept) {\n hints.push(\n \"A question card says `Answer no longer kept`: only the last 10 answers are kept, so no --limit brings it back. Read the user's reply from the messages after it.\",\n );\n }\n if (search !== undefined && response.data.entries.length === 0) {\n hints.push(\n \"No message holds that text. The whole conversation was searched — try a shorter or differently written piece of it.\",\n );\n }\n writeJson({ ...response, meta: { count: response.data.entries.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nregisterSchema({\n command: \"chats.diff\",\n description:\n \"See the real file-level changes a Session made (landings, creatives, brand, flows, knowledge). Published Sessions read from git; for an in-progress (unpublished) Session pass --live to read its changes straight from its running workspace. Without --live, an unpublished Session returns available:false — use `baker chats view` for the staged summary. Compact lists changed files with +/- counts; add --full for the actual diff text. Read-only.\",\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n surface: {\n type: \"string\",\n description: \"Filter to one surface: knowledge|company|brand|landings|flows|creatives\",\n required: false,\n },\n full: {\n type: \"boolean\",\n description: \"Include the unified-diff patch text per file\",\n required: false,\n default: false,\n },\n live: {\n type: \"boolean\",\n description:\n \"For an in-progress Session, read its changes from the live workspace (slower; resumes the paused Runtime). Ignored for published Sessions.\",\n required: false,\n default: false,\n },\n },\n});\n\nconst diffCommand = defineCommand({\n meta: { name: \"diff\", description: \"See a published Session's real file-level changes.\" },\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n surface: {\n type: \"string\",\n description: \"Filter: knowledge|company|brand|landings|flows|creatives\",\n required: false,\n },\n full: { type: \"boolean\", description: \"Include the diff patch text per file\", required: false, default: false },\n live: {\n type: \"boolean\",\n description: \"Read an in-progress Session's changes from its live workspace (slower)\",\n required: false,\n default: false,\n },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = { chatId: args.id };\n if (args.surface) {\n if (!(REPO_SURFACES as readonly string[]).includes(args.surface)) {\n throw new Error(`--surface must be one of: ${REPO_SURFACES.join(\"|\")}`);\n }\n body.surface = args.surface;\n }\n if (args.full) {\n body.full = true;\n }\n if (args.live) {\n body.live = true;\n }\n const response = await apiPost<ChatsDiffResponse>(\"/api/chats/diff\", body);\n writeJson({\n ...response,\n meta: { count: response.data.files.length },\n ...(!response.data.available && response.data.reason ? { hints: [response.data.reason] } : {}),\n ...(response.data.available && !args.full && response.data.files.length > 0\n ? { hints: [\"Add --full to read the actual diff text for each file.\"] }\n : {}),\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nconst IMPORT_DESCRIPTION = `Bring another chat's unpublished work into this chat, in one call — and take it out of that chat, so publishing both can never apply anything twice.\n\nStart here when the user wants another chat's work brought into this one (\"bring over\", \"merge the two\nchats\", \"its publish keeps failing — carry it over\", \"recover what the discarded chat did\"):\n baker chats import --from-chat <chat-id> # everything: files and staged changes\n baker chats import --from-chat <chat-id> --only meta-ads,tasks # only these staged surfaces, no files\n baker chats import --from-chat <chat-id> --failed # a PUBLISHED chat: the ad changes its publish could not apply\n baker chats import --from-chat $BAKER_CHAT_ID --failed # this chat's own last Publish: its failed ad changes, to fix and publish again\n\nThe other chat may be open, its publish may have failed, or it may be discarded. Its file changes (Knowledge,\npages, Forms, pictures) are applied in this workspace exactly as it made them, and every staged surface moves\nexactly as staged: ads (Google, Meta, LinkedIn, X, ChatGPT), Shopify, Tag Manager, Google Analytics, tracking\ntags, Tasks, scheduled agents, ActiveCampaign, site settings, ad goals, the funnel, conversions, conversion\nsends, event sources and lead routes. When both chats change the same file or the same thing, nothing moves\nand the refusal names each clash — ask the user which version wins. A chat whose publish failed is then closed\nto publishing, so the same work never goes live twice.\n--failed takes the Google Ads, Meta, LinkedIn, X and ChatGPT changes a published chat's publish could not\napply (failed, or skipped because what they needed failed), stages them here as they were — naming what did\napply by its real id — and takes them out of that chat, so its Retry cannot apply them twice. A chat goes on\nafter its Publish: naming this chat itself takes what its own last Publish could not apply into what it stages now.\nA change moved here cannot go back: to leave one behind, ask the user first and use --only (Google Ads alone\ncan pick single changes: \\`baker ads google draft import --from-chat <id> --refs|--exclude\\`).\nFind chat ids with \\`baker chats list\\`; see what one staged with \\`baker chats view <id>\\`.`;\n\nregisterSchema({\n command: \"chats.import\",\n description: IMPORT_DESCRIPTION,\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other chat — open, publish failed or discarded; published, or this chat itself, with --failed\",\n required: true,\n },\n only: {\n type: \"string\",\n description: `Comma-separated staged surfaces to move, leaving its files there (default: everything): ${CHAT_IMPORT_SURFACES.join(\", \")}`,\n required: false,\n },\n failed: {\n type: \"boolean\",\n description: \"The other chat is published: stage here the ad changes its publish could not apply\",\n required: false,\n default: false,\n },\n },\n});\n\n/** What became of the other chat's files, and of that chat itself. */\nfunction filesHints(data: ChatsImportResponse[\"data\"], files: SourceFiles | undefined): string[] {\n const hints: string[] = [];\n if (files?.kind === \"patch\") {\n hints.push(\n `Its ${files.paths.length} changed file(s) are now in this workspace, exactly as that chat left them: ${files.paths.join(\", \")}. Check them in the preview; never rebuild them by hand.`,\n );\n }\n if (files?.kind === \"stayed\") {\n hints.push(\n `Its file changes (Knowledge, pages, Forms…) did not come along: ${files.reason} Tell the user what is missing; do not rebuild it from memory.`,\n );\n } else if (data.filesStayed > 0) {\n hints.push(\n `Chat ${data.fromChatId} also changed ${data.filesStayed} file(s) (Knowledge, pages, Forms…) that did not come along. Run the import without --only to bring them.`,\n );\n }\n if (data.carried) {\n hints.push(\n \"That chat holds nothing of its own any more and can no longer be published, so the same work never goes live twice. This chat publishes all of it.\",\n );\n } else if (files?.kind === \"patch\") {\n hints.push(\n \"That chat still has its own copy of these files: tell the user to publish only this chat, or the same file changes would go live twice.\",\n );\n }\n return hints;\n}\n\n/** What the agent needs after a move: what stayed behind in the other chat, and what to check next. */\nfunction importHints(data: ChatsImportResponse[\"data\"], files: SourceFiles | undefined, failed: boolean): string[] {\n const hints: string[] = [];\n const moved = data.surfaces.reduce((sum, surface) => sum + surface.moved, 0);\n const stayed = data.surfaces.filter((surface) => surface.left);\n if (moved === 0 && stayed.length === 0 && files?.kind !== \"patch\") {\n hints.push(\n failed\n ? `Every ad change of chat ${data.fromChatId} applied, so there was nothing to bring over.`\n : `Chat ${data.fromChatId} had no unpublished changes, so nothing moved.`,\n );\n }\n for (const surface of stayed) {\n hints.push(\n `${surface.left?.count ? `${surface.left.count} ` : \"\"}${surface.surface} change(s) stayed in chat ${data.fromChatId}: ${surface.left?.reason}`,\n );\n }\n hints.push(...filesHints(data, files));\n if (moved > 0) {\n hints.push(\n \"The moved changes are this chat's now and publish with it; the other chat no longer holds them. Review them with each surface's `draft list` (and `baker ads google draft validate` when Google Ads changes moved).\",\n );\n }\n if (moved > 0 && stayed.length === 0 && !data.carried) {\n hints.push(\n \"Nothing staged stayed in the other chat. Never tell the user to discard it for this: its other work is still there.\",\n );\n }\n if (failed && moved > 0) {\n hints.push(\n \"They failed once for a reason: read each one's error with `baker chats view <id>` (publish) and amend it here before the user publishes, or it can fail the same way.\",\n );\n }\n return hints;\n}\n\ntype OnlyFlag = { surfaces?: ChatImportSurface[] } | { refusal: string };\n\n/** The surfaces `--only` names; absent means every surface, and a list naming none is refused. */\nfunction onlyFlag(value: unknown): OnlyFlag {\n if (typeof value !== \"string\") return {};\n const named = value\n .split(\",\")\n .map((surface) => surface.trim())\n .filter((surface) => surface.length > 0);\n if (named.length === 0) return { refusal: \"--only names no surface\" };\n const unknown = named.filter((surface) => !(CHAT_IMPORT_SURFACES as readonly string[]).includes(surface));\n if (unknown.length > 0) return { refusal: `--only names ${unknown.join(\", \")}, which is not a surface` };\n return { surfaces: named as ChatImportSurface[] };\n}\n\nfunction refuse(message: string, fix: string): never {\n writeJson({ ok: false, error: { code: \"VALIDATION_ERROR\", message, fix } });\n process.exit(1);\n}\n\n/** The other chat's files, applied here before its staged changes move — or why they stay there, or clash. */\nasync function carryFiles(fromChatId: string): Promise<SourceFiles | { kind: \"clash\"; paths: string[] }> {\n const files = await readSourceFiles(fromChatId);\n if (files.kind !== \"patch\") return files;\n const clashes = patchRefusal(files.patch);\n if (clashes) return { kind: \"clash\", paths: clashes };\n applyPatch(files.patch);\n return files;\n}\n\nconst importCommand = defineCommand({\n meta: { name: \"import\", description: IMPORT_DESCRIPTION },\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other chat whose work comes here — or, with --failed, this chat's own last Publish\",\n },\n only: { type: \"string\", description: \"Comma-separated staged surfaces to move, without files (default: all)\" },\n failed: {\n type: \"boolean\",\n description: \"From a published chat (this one included): the ad changes its publish could not apply\",\n default: false,\n },\n },\n run: async ({ args }) => {\n const fromChatId = typeof args[\"from-chat\"] === \"string\" ? args[\"from-chat\"].trim() : \"\";\n if (!fromChatId) {\n refuse(\n \"--from-chat is required\",\n \"Name the other chat: baker chats import --from-chat <chat-id> (ids from `baker chats list`).\",\n );\n }\n const only = onlyFlag(args.only);\n if (\"refusal\" in only) {\n // A list naming nothing must never widen to \"every surface\": the move takes them out of the other chat.\n refuse(\n only.refusal,\n `Name surfaces from: ${CHAT_IMPORT_SURFACES.join(\", \")} — or leave --only off to move them all.`,\n );\n }\n if (args.failed && only.surfaces) {\n refuse(\"--failed takes every ad platform's failed changes\", \"Leave --only off with --failed.\");\n }\n const chatId = requireChatId();\n let files: Awaited<ReturnType<typeof carryFiles>> | undefined;\n try {\n files = args.failed || only.surfaces ? undefined : await carryFiles(fromChatId);\n } catch (err) {\n failApi(err);\n }\n if (files?.kind === \"clash\") {\n refuse(\n `Nothing moved: these files changed in both chats, differently: ${files.paths.join(\", \")}.`,\n \"Ask the user which version should win. To bring only the other chat's staged changes and leave its files there, run the import again with --only and the surfaces it staged.\",\n );\n }\n try {\n const response = await apiPost<ChatsImportResponse>(\"/api/chats/import\", {\n chatId,\n fromChatId,\n ...(only.surfaces ? { surfaces: only.surfaces } : {}),\n ...(files?.kind === \"patch\" ? { filesCarried: true } : {}),\n ...(args.failed ? { failed: true } : {}),\n });\n writeJson({ ...response, hints: importHints(response.data, files, Boolean(args.failed)) });\n } catch (err) {\n // All or nothing: the files go back out when the staged changes could not come with them.\n if (files?.kind === \"patch\") revertPatch(files.patch);\n failApi(err);\n }\n },\n});\n\nexport const chatsCommand = defineCommand({\n meta: {\n name: \"chats\",\n description: `Inspect other Sessions on this account: list them, view what they produced, read their conversation, and see their real file changes — so you can reuse past work for a new goal. \\`import --from-chat <id>\\` moves another open Session's staged changes into this one.\nFull guide: __tooling__/docs/tools/baker/chats.md`,\n },\n subCommands: {\n list: listCommand,\n view: viewCommand,\n transcript: transcriptCommand,\n diff: diffCommand,\n import: importCommand,\n },\n});\n","/**\n * The file half of `baker chats import`: the other chat's changes to its files (Knowledge, pages,\n * Forms, pictures…), read from its workspace as one patch (`chats diff --live`'s `gitPatch`) and\n * applied here with `git apply` — exactly, or not at all.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport type { ChatsDiffResponse } from \"@baker/api\";\nimport { apiPost } from \"../../client.ts\";\n\nexport type SourceFiles =\n | { kind: \"none\" }\n | { kind: \"patch\"; patch: string; paths: string[] }\n | { kind: \"stayed\"; reason: string };\n\n/** What the other chat changed in its files, as something this workspace can apply — or why not. */\nexport async function readSourceFiles(fromChatId: string): Promise<SourceFiles> {\n const response = await apiPost<ChatsDiffResponse>(\"/api/chats/diff\", {\n chatId: fromChatId,\n live: true,\n gitPatch: true,\n });\n const { data } = response;\n if (!data.available) {\n return { kind: \"stayed\", reason: data.reason ?? \"its files could not be read.\" };\n }\n if (data.source === \"published\") {\n // Its changes reached the live site already, so there is nothing of them to carry.\n return { kind: \"none\" };\n }\n if (data.files.length === 0) {\n return { kind: \"none\" };\n }\n if (data.gitPatch === undefined) {\n return {\n kind: \"stayed\",\n reason: \"its file changes are too large to bring over in one piece, so none of them came along.\",\n };\n }\n return { kind: \"patch\", patch: data.gitPatch, paths: data.files.map((file) => file.path) };\n}\n\nfunction repoRoot(): string {\n return execFileSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], { encoding: \"utf8\" }).trim();\n}\n\n/** `git apply` of the patch at this workspace's root; `check` changes nothing, `reverse` takes it back out. */\nfunction gitApply(patch: string, mode: \"check\" | \"apply\" | \"reverse\"): void {\n const flags = mode === \"check\" ? [\"--check\"] : mode === \"reverse\" ? [\"--reverse\"] : [];\n execFileSync(\"git\", [\"apply\", \"--whitespace=nowarn\", ...flags, \"-\"], {\n cwd: repoRoot(),\n input: patch,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n}\n\n/** The files `git apply --check` named as not applying here, or the whole message when it named none. */\nexport function clashingFiles(stderr: string): string[] {\n const named = [...stderr.matchAll(/^error: ([^:\\n]+): /gm)]\n .map((match) => match[1])\n .filter((path): path is string => path !== undefined && path !== \"patch failed\");\n return named.length > 0 ? [...new Set(named)] : [stderr.trim()];\n}\n\n/** Why the patch cannot apply here — the files this chat also changed — or undefined when it applies cleanly. */\nexport function patchRefusal(patch: string): string[] | undefined {\n try {\n gitApply(patch, \"check\");\n return undefined;\n } catch (error) {\n const stderr = (error as { stderr?: Buffer | string }).stderr;\n return clashingFiles(stderr === undefined ? String(error) : String(stderr));\n }\n}\n\nexport function applyPatch(patch: string): void {\n gitApply(patch, \"apply\");\n}\n\nexport function revertPatch(patch: string): void {\n gitApply(patch, \"reverse\");\n}\n","import type { ChatPublishSummary } from \"@baker/api/chats\";\n\n/**\n * What a reader must not conclude from a completed Session: that it published\n * everything it staged (better than one published draft in three did not), or\n * that every change it sent is now what the platform holds.\n */\nexport function publishHints(publish: ChatPublishSummary): string[] {\n const hints: string[] = [];\n // Not `complete`: a change a person chose not to send leaves the publish complete, and still never went live.\n const failed = publish.failedTotal;\n if (failed > 0) {\n hints.push(\n `This Session's publish left ${failed} change${failed === 1 ? \"\" : \"s\"} behind — see \\`publish.surfaces\\` for why each did not apply. Do not report those changes as live.`,\n );\n }\n const unconfirmed = publish.unconfirmedTotal ?? 0;\n if (unconfirmed > 0) {\n hints.push(\n `${unconfirmed} change${unconfirmed === 1 ? \"\" : \"s\"} went through but could not be confirmed when read back from the platform — \\`publish.surfaces[].unconfirmedChanges\\` says what it shows instead. Check before reporting them as done.`,\n );\n }\n return hints;\n}\n\n/**\n * A Session still publishing is not live yet, and nothing in this chat runs\n * once it is: work that has to wait for it is a Scheduled agent (BAKER-1743).\n */\nexport function stillPublishingHints(status: string): string[] {\n if (status !== \"publishing\") return [];\n return [\n \"This Session is still publishing: its changes are not live yet. Work that has to wait for it (a check on the live page, a test lead) is a Scheduled agent staged now with `baker scheduled-agents create --run-at <time>`, whose brief first checks this Session went live. It exists only once your own chat is published: a page trigger staged now misses this Session's publish, and a `--run-at` that has passed by then is created switched off, so leave hours of headroom, not minutes, and tell the user it runs only once they publish this chat. Never ask the user to come back and tell you when it is done.\",\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,qBAAqB;;;ACL9B,SAAS,oBAAoB;AAU7B,eAAsB,gBAAgB,YAA0C;AAC9E,QAAM,WAAW,MAAM,QAA2B,mBAAmB;AAAA,IACnE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,UAAU;AAAA,EACZ,CAAC;AACD,QAAM,EAAE,KAAK,IAAI;AACjB,MAAI,CAAC,KAAK,WAAW;AACnB,WAAO,EAAE,MAAM,UAAU,QAAQ,KAAK,UAAU,+BAA+B;AAAA,EACjF;AACA,MAAI,KAAK,WAAW,aAAa;AAE/B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACA,MAAI,KAAK,MAAM,WAAW,GAAG;AAC3B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACA,MAAI,KAAK,aAAa,QAAW;AAC/B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ;AAAA,IACV;AAAA,EACF;AACA,SAAO,EAAE,MAAM,SAAS,OAAO,KAAK,UAAU,OAAO,KAAK,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,EAAE;AAC3F;AAEA,SAAS,WAAmB;AAC1B,SAAO,aAAa,OAAO,CAAC,aAAa,iBAAiB,GAAG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,MAAM;AAAA,IACN,QAAQ;AAAA,EACV;AACF,CAAC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../api/src/event-sources/hubspot.ts","../../api/src/event-sources/wire.ts","../../api/src/event-sources/activecampaign.ts"],"sourcesContent":["/**\n * What a HubSpot event reads by default, spelled as the same templates an\n * address's mapping uses — so the sheet shows one table for both, and a row\n * can be repointed at any property, or typed.\n *\n * ## Why defaults and not a fixed read\n *\n * The read used to be hard-wired: email from `email`, the Google click from\n * `hs_google_click_id`, and nothing anybody could change. Real accounts keep\n * the email under `work_email`, the deal value under a custom number\n * property, and a click id under whatever the tracking template wrote. The\n * defaults are HubSpot's standard names, which is where most accounts keep\n * them; every row is a template a person or the agent can change, and the\n * picker is the account's own property list, read live — never this table.\n *\n * An empty stored mapping means these — the same rule as an address, where\n * empty means \"the guess\".\n *\n * ## Three objects, one spelling\n *\n * A mention names a property of the object watched: `{{email}}` on a\n * contact source, `{{amount}}` on a deal source, `{{hs_pipeline_stage}}` on\n * a lead source, `{{id}}` the record's own id on any of them. A deal or a\n * lead source also reads the contact its record is about, through the\n * `contact.` namespace: `{{contact.email}}`, `{{contact.id}}`. The namespace\n * is what keeps the objects' properties apart in one table, and it is\n * spelled the way the Forms builder spells a nested field.\n */\n\nimport type { SourceField } from \"./fields\";\nimport type { HubspotObject } from \"./hubspotTrigger\";\nimport { mentionOf } from \"./template\";\n\n/** The variable that is the record's own id rather than a property: `{{id}}`. */\nexport const HUBSPOT_CONTACT_ID_VARIABLE = \"id\";\n\n/** On a deal source, the associated contact's properties are read as `{{contact.<property>}}`. */\nexport const HUBSPOT_CONTACT_PREFIX = \"contact.\";\n\n/** The path for a property of a deal's contact: `contact.email`. */\nexport function contactPath(property: string): string {\n return `${HUBSPOT_CONTACT_PREFIX}${property}`;\n}\n\n/** The contact property a `contact.<property>` path names, or null for a path of the record itself. */\nexport function contactPropertyOf(path: string): string | null {\n return path.startsWith(HUBSPOT_CONTACT_PREFIX) ? path.slice(HUBSPOT_CONTACT_PREFIX.length) : null;\n}\n\n/** HubSpot's standard contact property behind each field, where one exists. */\nexport const HUBSPOT_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = {\n email: \"email\",\n phone: \"phone\",\n external_id: HUBSPOT_CONTACT_ID_VARIABLE,\n first_name: \"firstname\",\n last_name: \"lastname\",\n city: \"city\",\n postal_code: \"zip\",\n country: \"country\",\n gclid: \"hs_google_click_id\",\n fbclid: \"hs_facebook_click_id\",\n};\n\n/**\n * The person's rows read off the record's associated contact, for an object\n * that is about somebody rather than being them.\n */\nconst throughContact: Readonly<Partial<Record<SourceField, string>>> = Object.fromEntries(\n Object.entries(HUBSPOT_DEFAULT_PROPERTIES).map(([field, property]) => [field, contactPath(property)]),\n);\n\n/**\n * The same for a deal: the person is the deal's contact, the amount is the\n * deal's own — HubSpot keeps it as `amount` in `deal_currency_code`, on\n * every account, which is the one row a contact source could never fill by\n * default.\n */\nexport const HUBSPOT_DEAL_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = {\n ...throughContact,\n value: \"amount\",\n currency: \"deal_currency_code\",\n};\n\n/**\n * The same for a lead. A lead is an interest in somebody, not an amount: it\n * has no `amount` and no currency of its own, so the value rows stay empty\n * and the funnel counts the step rather than money. Anyone who keeps a figure\n * on a custom lead property can still point `value` at it by hand.\n */\nexport const HUBSPOT_LEAD_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = throughContact;\n\nconst DEFAULTS: Readonly<Record<HubspotObject, Readonly<Partial<Record<SourceField, string>>>>> = {\n contact: HUBSPOT_DEFAULT_PROPERTIES,\n deal: HUBSPOT_DEAL_DEFAULT_PROPERTIES,\n lead: HUBSPOT_LEAD_DEFAULT_PROPERTIES,\n};\n\n/** The mapping a HubSpot event starts with: its name as the event, the standard properties for the rest. */\nexport function hubspotDefaultMapping(\n sourceName: string,\n object: HubspotObject = \"contact\",\n): Partial<Record<SourceField, string>> {\n const mapping: Partial<Record<SourceField, string>> = { event_name: sourceName };\n for (const [field, property] of Object.entries(DEFAULTS[object])) {\n mapping[field as SourceField] = mentionOf(property);\n }\n return mapping;\n}\n\n/**\n * The mapping in force for a HubSpot event: what was saved, else the defaults.\n * Keyed by field, or by `properties.<key>` for an extra property of the event.\n */\nexport function hubspotMappingInForce(\n sourceName: string,\n stored: Readonly<Record<string, string>>,\n object: HubspotObject = \"contact\",\n): Record<string, string> {\n const explicit = Object.entries(stored).filter(([, template]) => template.trim() !== \"\");\n if (explicit.length > 0) return Object.fromEntries(explicit);\n return hubspotDefaultMapping(sourceName, object);\n}\n","/**\n * The contract between `baker analytics sources` and `POST /api/analytics/sources`,\n * and the address a source is given.\n *\n * One request shape with one optional operation in it, and every call answers\n * with the full list afterwards — the CLI never has to make a second request\n * to see what it just did, and the \"what arrived\" question is answered by the\n * same read that answers \"what exists\".\n */\nimport { z } from \"zod\";\nimport { REJECTION_MESSAGES, validateEventName } from \"../event-ingest/validation\";\nimport { ACTIVECAMPAIGN_WEBHOOK_STATES, activeCampaignEventsSchema } from \"./activecampaign\";\nimport { mappingRowProblem } from \"./fields\";\nimport {\n CONDITION_LOGICS,\n HUBSPOT_DEAL_CONTACTS,\n HUBSPOT_OBJECTS,\n HUBSPOT_PROPERTY_KINDS,\n type HubspotTriggerInput,\n onlyCondition,\n TRIGGER_CONDITIONS_MAX,\n triggerProblem,\n} from \"./hubspotTrigger\";\n\n/** Mirrors `EVENT_SOURCE_KINDS` / the status validator in the backend schema; this package must not depend on convex. */\nexport const SOURCE_KINDS = [\"webhook\", \"hubspot\", \"activecampaign\"] as const;\nexport type SourceKind = (typeof SOURCE_KINDS)[number];\nexport const SOURCE_STATUSES = [\"learning\", \"counting\", \"paused\"] as const;\nexport type SourceStatus = (typeof SOURCE_STATUSES)[number];\n\nexport const SOURCE_NAME_MAX = 80;\n\n/**\n * What a source may be called — which is the ingest door's own rule, because a\n * source's name IS the `event_name` every event it raises carries.\n *\n * Held here rather than at each door, and that is the whole point of it being\n * here. A name this refuses is not a bad label, it is a **source that can\n * never count anything**: every arrival is rejected `invalid_name`, the card\n * goes on reading \"Counting\", and the only trace is one red line per event on\n * a feed somebody has to think to open. That happened — a HubSpot source\n * called \"Matrícula Realizada\", refused for ever by a rule that was ASCII-only\n * — and the reason it could happen is that three doors took a name and none of\n * them knew the rule.\n *\n * `MAX_EVENT_NAME` is the same 80 as {@link SOURCE_NAME_MAX} and\n * `validateEventName` checks it, so the bound is stated once even though both\n * constants exist.\n */\nexport const sourceNameSchema = z\n .string()\n .trim()\n .min(1)\n .max(SOURCE_NAME_MAX)\n .refine((name) => validateEventName(name) === null, REJECTION_MESSAGES.invalid_name);\n\n/** Where a source's arrivals go: the token is the whole path after this. */\nexport const EVENT_SOURCE_PATH_PREFIX = \"/v1/sources/\";\n\n/**\n * The address to hand a tool, given the branded host published for this\n * environment — the same fallback rule as `eventIngestUrl`.\n */\nexport function eventSourceUrl(brandedUrl: string | undefined, convexSiteUrl: string, token: string): string {\n const base = (brandedUrl || convexSiteUrl).replace(/\\/$/, \"\");\n return `${base}${EVENT_SOURCE_PATH_PREFIX}${token}`;\n}\n\nconst sourceIdSchema = z.string().min(1);\n\n/**\n * Canonical field → template (`template.ts`): literal text with `{{path}}`\n * mentions, or a bare path. A `properties.<key>` row is an extra property of\n * the event (`fields.ts`). Anything else is refused so a typo cannot become a\n * silent no-op.\n */\nexport const sourceMappingSchema = z.record(z.string(), z.string().min(1)).superRefine((mapping, ctx) => {\n for (const row of Object.keys(mapping)) {\n const problem = mappingRowProblem(row);\n if (problem !== null) ctx.addIssue({ code: \"custom\", message: problem, path: [row] });\n }\n});\n\n/** ISO 4217, upper case: what `POST /v1/events` accepts as `currency`. */\nexport const currencyCodeSchema = z\n .string()\n .trim()\n .toUpperCase()\n .regex(/^[A-Z]{3}$/, \"A currency is a three-letter code, like EUR or USD.\");\n\n/** What a HubSpot source is a trigger on: a contact (the default), a deal or a lead. */\nexport const hubspotObjectSchema = z.enum(HUBSPOT_OBJECTS);\n/** For a deal: whose event it is — the deal's first contact, or every contact on it. */\nexport const hubspotDealContactsSchema = z.enum(HUBSPOT_DEAL_CONTACTS);\n\n/**\n * One condition of a HubSpot trigger — *when a contact's* (or *a deal's*)\n * [property] [operator] [values] (`hubspotTrigger.ts`).\n */\nexport const hubspotConditionInputSchema = z.strictObject({\n property: z.string().trim().min(1),\n /** One of the property's kind's operators (`baker hubspot contacts properties` lists them); `is` when unsaid. */\n operator: z.string().trim().min(1).default(\"is\"),\n /** As HubSpot spells them: an option's internal value, a number, a `YYYY-MM-DD`, `true`/`false`. None for an empty check, two for a between, several for a list. */\n values: z.array(z.string().trim().min(1)).max(50).default([]),\n});\n\nconst conditionLogicSchema = z.enum(CONDITION_LOGICS);\n\nconst conditionGroupInputSchema = z.strictObject({\n logic: conditionLogicSchema,\n conditions: z.array(hubspotConditionInputSchema).min(1).max(TRIGGER_CONDITIONS_MAX),\n});\n\nconst combinedInputSchema = z\n .strictObject({\n /** How the rows combine: `And` (every one) or `Or` (any one) — a Form's filter's \"Match AND / OR\". */\n logic: conditionLogicSchema.default(\"And\"),\n /** Conditions, and groups of conditions with their own logic, one level deep. */\n conditions: z\n .array(z.union([hubspotConditionInputSchema, conditionGroupInputSchema]))\n .min(1)\n .max(TRIGGER_CONDITIONS_MAX),\n })\n .superRefine((trigger, context) => {\n const problem = triggerProblem(trigger);\n if (problem !== null) context.addIssue({ code: \"custom\", message: problem });\n });\n\n/**\n * What a HubSpot source watches: one condition, or several combined — the\n * way a Form's filter combines them. A single condition is the short\n * spelling, and is read as a trigger of that one condition.\n */\nexport const hubspotTriggerInputSchema = z\n .union([combinedInputSchema, hubspotConditionInputSchema])\n .transform((input): HubspotTriggerInput => (\"conditions\" in input ? input : onlyCondition(input)));\n\nconst hubspotConditionSchema = hubspotConditionInputSchema.extend({\n propertyLabel: z.string(),\n kind: z.enum(HUBSPOT_PROPERTY_KINDS),\n /** A select that holds several values at once (`a;b`); decides what HubSpot may filter on. */\n multiple: z.boolean().optional(),\n valueLabels: z.array(z.string()),\n});\n\nconst hubspotTriggerFields = {\n logic: conditionLogicSchema,\n conditions: z.array(\n z.union([\n hubspotConditionSchema,\n z.strictObject({ logic: conditionLogicSchema, conditions: z.array(hubspotConditionSchema) }),\n ]),\n ),\n};\n\n/** The trigger as stored on a source: every condition resolved, and on its object. */\nexport const hubspotWatchSchema = z.strictObject({\n ...hubspotTriggerFields,\n object: hubspotObjectSchema,\n contacts: hubspotDealContactsSchema.optional(),\n});\nexport type HubspotWatchView = z.infer<typeof hubspotWatchSchema>;\n\n/** A sample record as the preview shows it: its id and the properties it holds, empty ones dropped. */\nconst sampleRecordSchema = z.strictObject({ id: z.string(), properties: z.record(z.string(), z.string()) });\n\n/** What a HubSpot event would count today, asked before it is made: the trigger and the properties to read off the sample. */\nexport const hubspotPreviewRequestSchema = z.strictObject({\n object: hubspotObjectSchema.default(\"contact\"),\n trigger: hubspotTriggerInputSchema,\n /** Property names to read off the sample; `id` is always there. On a deal or a lead, `contact.<name>` reads its first contact. */\n properties: z.array(z.string().trim().min(1)).max(60).optional(),\n /** The record to draw the preview from — an id, or text to search (an email or a name for a contact, a deal's or a lead's name). The one most recently at the trigger when unsaid. */\n contact: z.string().trim().min(1).max(200).optional(),\n});\nexport type HubspotPreviewRequest = z.infer<typeof hubspotPreviewRequestSchema>;\n\nexport const hubspotPreviewSchema = z.strictObject({\n /** Records satisfying the trigger today — the ones that will NOT be counted. */\n total: z.number(),\n /** False when the trigger has more combinations than HubSpot's search takes, so `total` is only near. */\n exact: z.boolean().optional(),\n /**\n * The sample record the trigger is on, with the properties asked for and\n * the contacts behind it, first first; none when nothing fits.\n *\n * One field rather than one per object: a contact source's record *is* the\n * person and its `contacts` is empty, while a deal's and a lead's carry the\n * people the event is about. Three parallel nullable fields, exactly one of\n * them ever set, would say the same thing and let a caller read the wrong one.\n */\n record: sampleRecordSchema.extend({ contacts: z.array(sampleRecordSchema) }).nullable(),\n});\nexport type HubspotPreview = z.infer<typeof hubspotPreviewSchema>;\n\nexport const sourcesRequestSchema = z.strictObject({\n /** The company's own server door: made once, `counting` from the start, the same address for ever after. */\n server: z.strictObject({}).optional(),\n create: z.strictObject({ name: sourceNameSchema }).optional(),\n /** A HubSpot event: read every five minutes, counting from now. The labels are looked up server-side. */\n createHubspot: z\n .strictObject({\n name: sourceNameSchema.optional(),\n /** A contact, a deal or a lead. A deal's and a lead's event is about its contact, read through `contact.<property>` rows. */\n object: hubspotObjectSchema.default(\"contact\"),\n trigger: hubspotTriggerInputSchema,\n /** On a deal: the deal's first contact (the default), or every contact on it, each its own event. */\n contacts: hubspotDealContactsSchema.optional(),\n /** Rows to read off the record, over the defaults; the same table `map` writes. */\n mapping: sourceMappingSchema.optional(),\n /** A number property on the record to read as the amount; needs `currency` beside it. Sugar over the mapping's `value` and `currency` rows. */\n amountProperty: z.string().trim().min(1).optional(),\n currency: currencyCodeSchema.optional(),\n })\n .optional(),\n /**\n * An ActiveCampaign source: ActiveCampaign's own webhook, made on the\n * account when this is applied, sending the events picked here. Each raises\n * `activecampaign.<type>` and counts from then on.\n */\n createActiveCampaign: z\n .strictObject({\n name: sourceNameSchema.optional(),\n /** ActiveCampaign's event names (`subscribe`, `deal_update`, …); the lead and deal moments when unsaid. */\n events: activeCampaignEventsSchema.optional(),\n /** Which connection, when the company has more than one. */\n account: z.string().trim().min(1).optional(),\n })\n .optional(),\n /** Change what a HubSpot event watches. It counts from now on under the new trigger; the rows stay. The object cannot change: the rows read it. */\n setTrigger: z\n .strictObject({\n sourceId: sourceIdSchema,\n trigger: hubspotTriggerInputSchema,\n contacts: hubspotDealContactsSchema.optional(),\n })\n .optional(),\n /** Ask HubSpot what a trigger would count today, and read one real record, without making anything. */\n preview: hubspotPreviewRequestSchema.optional(),\n /** Change where a HubSpot-read source takes its amount from; no `amountProperty` clears it. Sugar over `map`. */\n setAmount: z\n .strictObject({\n sourceId: sourceIdSchema,\n amountProperty: z.string().trim().min(1).optional(),\n currency: currencyCodeSchema.optional(),\n })\n .optional(),\n /**\n * Count a HubSpot event's history: every moment its trigger came to hold\n * since `since`, read out of HubSpot's own property history.\n *\n * Not the thing a source deliberately refuses to do. A source never\n * backfills the **present state** — somebody who already satisfies a\n * condition is not an event today — and this reports only moments HubSpot\n * has a timestamp for, so nothing is invented. Dry unless `write`.\n */\n backfill: z\n .strictObject({\n sourceId: sourceIdSchema,\n /** ISO instant, or Unix milliseconds. Bounded by the 400 days the store keeps. */\n since: z.union([z.string().trim().min(1), z.number()]),\n /**\n * Where a capped run carries on from: only records last changed at or\n * before this instant are read.\n *\n * The **read** is what it bounds, never the history. Records are chosen\n * most-recently-changed first, so a run that reaches its cap has covered\n * the newest of them and the rest are the ones nearest `since` — which\n * no shorter window can reach, because shortening one only drops\n * candidates from the old end and hands back the same newest records\n * again. `reachedBack` is the value to pass here, and the moments each\n * record is then judged on are still the whole of `since` to now.\n */\n before: z.union([z.string().trim().min(1), z.number()]).optional(),\n /** Without it, nothing is counted and the answer says what would be. */\n write: z.boolean().optional(),\n })\n .optional(),\n map: z.strictObject({ sourceId: sourceIdSchema, mapping: sourceMappingSchema }).optional(),\n pause: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n resume: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n remove: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n});\nexport type SourcesRequest = z.infer<typeof sourcesRequestSchema>;\n/** The request as a caller writes it, before the schema fills its defaults — what the CLI builds. */\nexport type SourcesRequestInput = z.input<typeof sourcesRequestSchema>;\n\n/** A delivery that arrived and was refused — mirrors `sourceRefusalValidator` in the backend schema. */\nexport const sourceRefusalSchema = z.strictObject({\n at: z.number(),\n count: z.number(),\n code: z.string(),\n reason: z.string(),\n});\n\nexport const detectedFieldSchema = z.strictObject({\n path: z.string(),\n confidence: z.enum([\"key\", \"value\"]),\n});\n\n/** Whether HubSpot's journal is being told to keep the changes a source watches. */\nexport const HUBSPOT_LISTENING_STATES = [\"listening\", \"not_configured\", \"failed\"] as const;\nexport type HubspotListeningState = (typeof HUBSPOT_LISTENING_STATES)[number];\n\nexport const sourceViewSchema = z.strictObject({\n id: z.string(),\n kind: z.enum(SOURCE_KINDS),\n name: z.string(),\n status: z.enum(SOURCE_STATUSES),\n /** The address a tool posts to. A HubSpot source has none: Baker calls HubSpot. */\n url: z.string().optional(),\n /** What a HubSpot source watches, and on which object. */\n hubspot: hubspotWatchSchema.optional(),\n /**\n * What an ActiveCampaign source listens to, and whether ActiveCampaign has\n * the webhook that sends it: `listening` once it is made, `not_configured`\n * until then, `failed` when ActiveCampaign refused it — `detail` says why.\n */\n activecampaign: z\n .strictObject({\n events: z.array(z.string()),\n webhook: z.strictObject({ state: z.enum(ACTIVECAMPAIGN_WEBHOOK_STATES), detail: z.string().optional() }),\n })\n .optional(),\n /** A HubSpot source counts changes from here on; one HubSpot reports from before it is dropped. Moves when the trigger changes. */\n countingSince: z.number().optional(),\n /**\n * Whether HubSpot is keeping this source's changes for Baker, as last\n * checked: `listening` when the app's journal subscription on the account\n * names the property; `not_configured` when the app has not been told yet\n * (or cannot be, with no credentials); `failed` when HubSpot refused the\n * subscription. `detail` says what to do.\n */\n listening: z.strictObject({ state: z.enum(HUBSPOT_LISTENING_STATES), detail: z.string().optional() }).optional(),\n /** Why the last delivery could not be counted, in product words; absent when the last one was. */\n lastError: z.string().optional(),\n lastArrivalAt: z.number().optional(),\n /**\n * What its last delivery **refused, event by event** — which `lastError` is\n * not and `lastArrivalAt` cannot be. A source refusing everything it\n * receives has no arrival and no read failure, so without this it reads as\n * one nobody has sent anything to. `refusalWords` turns it into the\n * sentence a person is shown. Cleared by the next delivery that counts.\n */\n lastRefusal: sourceRefusalSchema.optional(),\n /** The first send, masked, while learning. Kept once confirmed. */\n sample: z.strictObject({ receivedAt: z.number(), body: z.string() }).optional(),\n /** Field → template; empty means the guess (an address) or the defaults (a HubSpot read). */\n mapping: z.record(z.string(), z.string()),\n /** The guess over the sample, for the sheet to prefill and the CLI to suggest. */\n detected: z.record(z.string(), detectedFieldSchema).optional(),\n /** Every path the sample's first item holds, with its masked value — what the picker offers. */\n paths: z.array(z.strictObject({ path: z.string(), value: z.string() })).optional(),\n /** `baker` when the sample already parses as the `POST /v1/events` contract and needs no mapping. */\n format: z.enum([\"baker\", \"foreign\"]).optional(),\n});\nexport type SourceView = z.infer<typeof sourceViewSchema>;\n\n/**\n * One change to the company's sources, staged inside a chat and applied when\n * it is published. `ref` is the source's id, or a `src_temp_*` for one the\n * chat makes.\n */\nexport const stagedSourceOpSchema = z.strictObject({\n kind: z.enum([\"create\", \"setTrigger\", \"map\", \"status\", \"remove\"]),\n ref: z.string(),\n name: z.string(),\n summary: z.string(),\n /** On a create: what the source will watch and read. */\n hubspot: hubspotWatchSchema.optional(),\n /** On an ActiveCampaign create: the events its webhook will send. */\n activecampaign: z.strictObject({ events: z.array(z.string()) }).optional(),\n mapping: z.record(z.string(), z.string()).optional(),\n status: z.enum([\"paused\", \"counting\"]).optional(),\n});\nexport type StagedSourceOp = z.infer<typeof stagedSourceOpSchema>;\n\n/** What a backfill found, and — on a `write` run — what became of it. */\nexport const backfillResultSchema = z.strictObject({\n sourceId: z.string(),\n name: z.string(),\n since: z.number(),\n /** Records whose history was read. */\n examined: z.number(),\n /** Moments the trigger came to hold, across them. */\n entries: z.number(),\n /** Of those, already counted — the journal got there first, or a previous run did. */\n alreadyCounted: z.number(),\n /** What a `write` run would hand over, or did. */\n pending: z.number(),\n /** Whether the read stopped at its cap; {@link BackfillResult.reachedBack} is where to carry on from. */\n capped: z.boolean(),\n /**\n * How far back the read got: the instant the oldest record it examined was\n * last changed. Only on a capped run, and it is the next run's `before`.\n */\n reachedBack: z.number().optional(),\n counted: z.number().optional(),\n refused: z.number().optional(),\n refusedReason: z.string().optional(),\n});\nexport type BackfillResult = z.infer<typeof backfillResultSchema>;\n\nexport const sourcesResponseSchema = z.strictObject({\n ok: z.literal(true),\n data: z.strictObject({\n sources: z.array(sourceViewSchema),\n /** Only when the request carried `preview`. */\n preview: hubspotPreviewSchema.optional(),\n /** Only when the request carried `backfill`. */\n backfill: backfillResultSchema.optional(),\n /** What this chat has staged, when one is attached: applied at Publish, dropped with a discard. */\n staged: z.array(stagedSourceOpSchema).optional(),\n }),\n hints: z.array(z.string()).optional(),\n});\nexport type SourcesResponse = z.infer<typeof sourcesResponseSchema>;\n","/**\n * What an ActiveCampaign source can listen to: ActiveCampaign's own webhook\n * events, and the event name each one raises in Baker.\n *\n * The list is ActiveCampaign's, read from `GET /api/3/webhook/events` — an\n * account answers with exactly these 27 — and the words are ours, for the\n * picker and the change list. Every event a source raises is called\n * `activecampaign.<type>`, whatever the source is called, so a scheduled agent\n * narrowed to `activecampaign.deal_update` runs for any connected account and\n * `properties.baker_source` says which source it came through.\n */\nimport { z } from \"zod\";\n\nexport const ACTIVECAMPAIGN_WEBHOOK_EVENTS = {\n subscribe: \"A contact subscribes to a list\",\n unsubscribe: \"A contact unsubscribes\",\n update: \"A contact's details change\",\n contact_tag_added: \"A tag is added to a contact\",\n contact_tag_removed: \"A tag is removed from a contact\",\n subscriber_note: \"A note is added to a contact\",\n contact_task_add: \"A task is added to a contact\",\n sent: \"A campaign starts sending\",\n open: \"A contact opens a campaign\",\n click: \"A contact clicks a link in a campaign\",\n reply: \"A contact replies to a campaign\",\n forward: \"A contact forwards a campaign\",\n share: \"A contact shares a campaign\",\n bounce: \"A campaign email bounces\",\n list_add: \"A list is created\",\n deal_add: \"A deal is created\",\n deal_update: \"A deal changes\",\n deal_note_add: \"A note is added to a deal\",\n deal_task_add: \"A task is added to a deal\",\n deal_task_complete: \"A deal task is completed\",\n deal_pipeline_add: \"A pipeline is created\",\n deal_stage_add: \"A deal stage is created\",\n deal_tasktype_add: \"A deal task type is created\",\n account_add: \"An account is created\",\n account_update: \"An account changes\",\n account_contact_add: \"A contact is added to an account\",\n account_contact_update: \"A contact on an account changes\",\n} as const;\n\nexport type ActiveCampaignWebhookEvent = keyof typeof ACTIVECAMPAIGN_WEBHOOK_EVENTS;\n\nexport const ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES = Object.keys(\n ACTIVECAMPAIGN_WEBHOOK_EVENTS,\n) as readonly ActiveCampaignWebhookEvent[];\n\n/** Who may have caused an event: a contact, a user, an automation, the API — all of them, so nothing is missed. */\nexport const ACTIVECAMPAIGN_WEBHOOK_SOURCES = [\"public\", \"admin\", \"api\", \"system\"] as const;\n\n/** What a new source listens to when nobody says: the lead and deal moments a marketer asks about first. */\nexport const ACTIVECAMPAIGN_DEFAULT_EVENTS: readonly ActiveCampaignWebhookEvent[] = [\n \"subscribe\",\n \"contact_tag_added\",\n \"deal_add\",\n \"deal_update\",\n];\n\n/** The source's name when nobody gives one. */\nexport const ACTIVECAMPAIGN_SOURCE_NAME = \"ActiveCampaign\";\n\nconst EVENT_PREFIX = \"activecampaign.\";\n\n/** The Baker event an ActiveCampaign webhook event raises: `subscribe` → `activecampaign.subscribe`. */\nexport function activeCampaignEventName(type: string): string {\n return `${EVENT_PREFIX}${type}`;\n}\n\n/** The ActiveCampaign event behind a Baker event name, or null when it is not one. */\nexport function activeCampaignEventOf(eventName: string): ActiveCampaignWebhookEvent | null {\n if (!eventName.startsWith(EVENT_PREFIX)) return null;\n const type = eventName.slice(EVENT_PREFIX.length);\n return type in ACTIVECAMPAIGN_WEBHOOK_EVENTS ? (type as ActiveCampaignWebhookEvent) : null;\n}\n\n/** The words for one event, falling back to ActiveCampaign's own name for one this list does not know. */\nexport function activeCampaignEventLabel(type: string): string {\n return type in ACTIVECAMPAIGN_WEBHOOK_EVENTS\n ? ACTIVECAMPAIGN_WEBHOOK_EVENTS[type as ActiveCampaignWebhookEvent]\n : type;\n}\n\n/**\n * The events a source listens to, as the CLI and the dashboard hand them in:\n * ActiveCampaign's names, or Baker's `activecampaign.<type>` spelling of them,\n * deduplicated, in the catalogue's order.\n */\nexport const activeCampaignEventsSchema = z\n .array(z.string().trim().min(1))\n .min(1, \"Pick at least one ActiveCampaign event to listen to.\")\n .max(ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.length)\n .transform((raw, ctx) => {\n const picked = new Set<ActiveCampaignWebhookEvent>();\n for (const item of raw) {\n const type = activeCampaignEventOf(item) ?? (item in ACTIVECAMPAIGN_WEBHOOK_EVENTS ? item : null);\n if (type === null) {\n ctx.addIssue({\n code: \"custom\",\n message: `\"${item}\" is not an ActiveCampaign event. Pick from: ${ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.join(\", \")}.`,\n });\n return z.NEVER;\n }\n picked.add(type as ActiveCampaignWebhookEvent);\n }\n return ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.filter((type) => picked.has(type));\n });\n\n/** Whether ActiveCampaign has the webhook that sends a source its events, as last checked. */\nexport const ACTIVECAMPAIGN_WEBHOOK_STATES = [\"listening\", \"not_configured\", \"failed\"] as const;\nexport type ActiveCampaignWebhookState = (typeof ACTIVECAMPAIGN_WEBHOOK_STATES)[number];\n"],"mappings":";;;;;;;;;;;;;;;;;AAkCO,IAAM,8BAA8B;AAGpC,IAAM,yBAAyB;AAG/B,SAAS,YAAY,UAA0B;AACpD,SAAO,GAAG,sBAAsB,GAAG,QAAQ;AAC7C;AAQO,IAAM,6BAA6E;AAAA,EACxF,OAAO;AAAA,EACP,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AACV;AAMA,IAAM,iBAAiE,OAAO;AAAA,EAC5E,OAAO,QAAQ,0BAA0B,EAAE,IAAI,CAAC,CAAC,OAAO,QAAQ,MAAM,CAAC,OAAO,YAAY,QAAQ,CAAC,CAAC;AACtG;AAQO,IAAM,kCAAkF;AAAA,EAC7F,GAAG;AAAA,EACH,OAAO;AAAA,EACP,UAAU;AACZ;AAQO,IAAM,kCAAkF;AAE/F,IAAM,WAA4F;AAAA,EAChG,SAAS;AAAA,EACT,MAAM;AAAA,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
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/analytics/sources.ts"],"sourcesContent":["import { REJECTION_MESSAGES, validateEventName } from \"@baker/api/event-ingest\";\nimport {\n HUBSPOT_DEAL_CONTACTS,\n HUBSPOT_OBJECTS,\n type HubspotDealContacts,\n type HubspotObject,\n hubspotDefaultMapping,\n hubspotTriggerInputSchema,\n mappingRowProblem,\n readsAssociatedContact,\n SOURCE_FIELD_NAMES,\n type SourcesRequestInput,\n type SourcesResponse,\n templateMentions,\n} from \"@baker/api/event-sources\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { hubspotRefusal } from \"../hubspot/refusal.ts\";\nimport { ConversionArgsError, onlyOnce } from \"./conversionArgs.ts\";\n\n/**\n * `baker analytics sources` — an address for each of the client's own tools to\n * send events to, and what each one's payloads are read as.\n *\n * ## Why a URL and not a key\n *\n * `POST /v1/events` needs the sender to write code to our contract. A CRM's\n * webhook, an automation platform, a billing system cannot be told what to\n * send — they post what they post, to a URL, and set nothing else. A source\n * is that URL: the token in it is the whole credential, the first send\n * teaches Baker the shape, and a person confirms once which path is the\n * email, which the amount. From then on every arrival is an ordinary event.\n *\n * ## `--field` and `--value` repeat, and citty keeps only the last\n *\n * citty hands the LAST value of a repeated flag over as a plain string, so\n * `--field email=a --field value=b` would map `value` and silently drop\n * `email`, and `--value lead --value customer` would watch `customer` alone.\n * Both are read off `process.argv` instead, the way `conversions` reads its\n * repeats.\n */\n\nconst args = {\n server: {\n type: \"boolean\",\n description:\n \"The client's own server door: one address for their developers, made once and the same for ever after, counting at once in Baker's own format (`baker analytics sending-events` has the contract). Prints it; nothing else to set\",\n required: false,\n },\n create: {\n type: \"boolean\",\n description:\n \"Make an address for a tool that cannot be told what to send (a CRM webhook, an automation step). Needs --name. Its first send is kept as a sample and counted as nothing until --map\",\n required: false,\n },\n \"create-hubspot\": {\n type: \"boolean\",\n description:\n \"Make a HubSpot event: HubSpot keeps each change to --property for Baker (Baker's app subscribes the account to that property with the condition as HubSpot's own filter, and nothing else), and every contact whose new value satisfies --operator --value is an event, counted within a minute. Needs --property (names, kinds and operators from `baker hubspot contacts properties`); --operator defaults to `is`; --value repeats for a list (`is` on a dropdown) or a between; --name is optional and defaults to the trigger's words; --field rows (names from `baker hubspot contacts fields`) replace the default rows they name. Counts from now on, never earlier contacts\",\n required: false,\n },\n \"create-activecampaign\": {\n type: \"boolean\",\n description:\n \"Make an ActiveCampaign event source: when this chat is published, ActiveCampaign's own webhook is set up on the account to send --events here, and each one counts as `activecampaign.<event>` (a contact subscribing is `activecampaign.subscribe`) from then on — a scheduled agent can run on any of them (`baker scheduled-agents create --trigger event.received --event activecampaign.deal_update`). --events defaults to subscribe,contact_tag_added,deal_add,deal_update; --name to ActiveCampaign; --account picks the connection when there are several. Removing the source takes the webhook off the account\",\n required: false,\n },\n events: {\n type: \"string\",\n description:\n \"With --create-activecampaign: ActiveCampaign's events, comma-separated — subscribe, unsubscribe, update, contact_tag_added, contact_tag_removed, subscriber_note, contact_task_add, sent, open, click, reply, forward, share, bounce, list_add, deal_add, deal_update, deal_note_add, deal_task_add, deal_task_complete, deal_pipeline_add, deal_stage_add, deal_tasktype_add, account_add, account_update, account_contact_add, account_contact_update\",\n required: false,\n },\n account: {\n type: \"string\",\n description:\n \"With --create-activecampaign: which ActiveCampaign connection, by id, when the company has more than one (the refusal lists them)\",\n required: false,\n },\n \"set-trigger\": {\n type: \"boolean\",\n description:\n \"Change what a HubSpot event watches. Needs --source and the same --property --operator --value as --create-hubspot. The rows stay; it counts from now on under the new trigger\",\n required: false,\n },\n preview: {\n type: \"boolean\",\n description:\n \"Ask HubSpot what --property --operator --value would count today, and read one real contact — the one most recently there, or --contact — with the properties the --field rows mention (the defaults when none), to check every row against real data BEFORE --create-hubspot. Makes nothing\",\n required: false,\n },\n object: {\n type: \"string\",\n description:\n \"With --create-hubspot or --preview: what the trigger is on — `contact` (the default), `deal` or `lead`. A deal's and a lead's event is about the contact the record is associated with: its rows read the record's own properties bare ({{amount}}, {{dealstage}}, {{hs_pipeline_stage}}) and the contact's as {{contact.<name>}} (`baker hubspot deals fields` / `baker hubspot leads fields`). A deal's amount defaults to its own amount in its currency; a lead has none, so it counts the step rather than money. Use `lead` for qualification and disqualification — HubSpot records both as a lead stage, and nothing on the contact or the deal says a lead was disqualified\",\n required: false,\n },\n contacts: {\n type: \"string\",\n description:\n \"With --object deal or --object lead (on --create-hubspot or --set-trigger): whose event it is — `every` (the default: every contact on the record, each its own event; on a deal each worth the deal's amount) or `first` (the record's first contact only)\",\n required: false,\n },\n property: {\n type: \"string\",\n description:\n \"With --create-hubspot, --set-trigger or --preview: the property to watch, by HubSpot's internal name (lifecyclestage, hs_lead_status, a custom one on a contact; dealstage, amount, closedate on a deal; hs_pipeline_stage, hs_lead_label on a lead) — any property, whatever its kind\",\n required: false,\n },\n operator: {\n type: \"string\",\n description:\n \"With --property: how the property has to read. By the property's kind — select: is, isNot, isEmpty, isNotEmpty · text: is, isNot, contains, doesNotContain, startsWith, endsWith, isEmpty, isNotEmpty · number: equal, notEqual, lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual, isEmpty, isNotEmpty · date: is, isBefore, isAfter, isOnOrBefore, isOnOrAfter, isBetween, isEmpty, isNotEmpty · yes/no: is, isNot. `is` when unsaid\",\n required: false,\n },\n value: {\n type: \"string\",\n description:\n \"With --property: the value, as HubSpot spells it — a dropdown's internal value (customer, QUALIFIED…), a number, a YYYY-MM-DD, true/false. Repeat it for a list (--value lead --value customer) or the two ends of isBetween; none for isEmpty / isNotEmpty\",\n required: false,\n },\n conditions: {\n type: \"string\",\n description:\n 'With --create-hubspot, --set-trigger or --preview, instead of --property/--operator/--value: several conditions combined the way a Form\\'s filter combines them, as JSON — `{\"logic\":\"And\",\"conditions\":[{\"property\":\"lifecyclestage\",\"values\":[\"customer\"]},{\"logic\":\"Or\",\"conditions\":[{\"property\":\"country\",\"values\":[\"Spain\"]},{\"property\":\"amount\",\"operator\":\"greaterThan\",\"values\":[\"1000\"]}]}]}`. `logic` is And (every row) or Or (any row); a row is a condition or a group with its own logic, one level deep; at most 10 conditions. The event fires when a change to any named property makes the whole combination hold',\n required: false,\n },\n contact: {\n type: \"string\",\n description:\n \"With --preview: the record to draw the sample from — a HubSpot id, or text to search (an email or a name for a contact, a deal's or a lead's name). The one most recently satisfying the trigger when unsaid\",\n required: false,\n },\n \"amount-property\": {\n type: \"string\",\n description:\n \"With --create-hubspot or --set-amount: a NUMBER property of the watched object to read as the event's amount (a deal value synced onto the contact; a deal's own `amount` is read by default on a deal). Needs --currency beside it\",\n required: false,\n },\n currency: {\n type: \"string\",\n description: \"With --amount-property: the three-letter currency the property is in, like EUR or USD\",\n required: false,\n },\n \"set-amount\": {\n type: \"boolean\",\n description:\n \"Change where a HubSpot-read source takes its amount from. Needs --source; with --amount-property and --currency it reads them, with neither it stops reading an amount\",\n required: false,\n },\n backfill: {\n type: \"boolean\",\n description:\n \"Count a HubSpot event's history: every moment its trigger came to hold since --since, at the instant HubSpot says it did. Needs --source and --since. Nothing is invented — a record that merely satisfies the trigger today is not an event today, and only moments HubSpot has a timestamp for are counted. Dry without --write. Reach for it when an event was made after the deals it should have counted, or after fixing one that was refusing everything it received\",\n required: false,\n },\n since: {\n type: \"string\",\n description:\n \"With --backfill: the date to count this event's history from, `2026-09-19` or an ISO instant. At most 400 days back — the store keeps no more\",\n required: false,\n },\n before: {\n type: \"string\",\n description:\n \"With --backfill: carry on from where a capped run stopped, by passing back the `reachedBack` it returned. One run reads at most 500 records, most recently changed first, so a capped run has covered the newest and the rest are the ones nearest --since — narrowing --since cannot reach them, this can. Repeat until `capped` is false; nothing is counted twice. It bounds which records are read, never which of their moments count: those are still the whole of --since to now\",\n required: false,\n },\n write: {\n type: \"boolean\",\n description:\n \"With --backfill: actually count what it found. Without it nothing is counted and the answer says what would be. Events inside the last 72 hours are uploaded to this event's ad platforms within minutes of counting, which spends real budget\",\n required: false,\n },\n name: {\n type: \"string\",\n description:\n \"The tool the source is for — HubSpot, Zapier, Stripe. It is the event's name when the payload does not say one, and every event it sends carries it as `baker_source`\",\n required: false,\n },\n map: {\n type: \"boolean\",\n description:\n \"Set what each field is read from. For an address this starts counting; needs --source, and one --field per row. With no --field the guess is used, which is right for a tool already sending Baker's own format. For a HubSpot-read source it replaces the whole mapping (the row list is on the source as `mapping`; empty means HubSpot's standard properties), so repeat every row you want kept\",\n required: false,\n },\n source: { type: \"string\", description: \"The source id, from the list\", required: false },\n field: {\n type: \"string\",\n description: `<field>=<template>, repeatable. A template is text with {{path}} mentions, one thing per mention: --field email={{contact.email}} --field currency=EUR --field first_name=\"{{who.first}} {{who.last}}\". A bare path (--field email=contact.email) is read as its mention when the sample has that path, so the short spelling still works. Fields: ${SOURCE_FIELD_NAMES.join(\", \")}. An EXTRA PROPERTY of the event — a plan, a stage, anything Measure → Events should break it down by and a send may pass on to a platform — is --field properties.<name>=<template>, e.g. --field properties.plan={{plan_tier}}. Paths come from \\`paths\\` on the source's sample; for a HubSpot event they are contact property names (\\`baker hubspot contacts fields\\`) plus \\`id\\` for the contact id`,\n required: false,\n },\n pause: {\n type: \"boolean\",\n description: \"Stop counting a source's arrivals; they are answered and dropped. Needs --source\",\n required: false,\n },\n resume: { type: \"boolean\", description: \"Count a paused source's arrivals again. Needs --source\", required: false },\n remove: {\n type: \"boolean\",\n description: \"Delete a source; its address stops working at once. Needs --source\",\n required: false,\n },\n full: {\n type: \"boolean\",\n description:\n \"Also return each source's masked sample body. The paths and the guess are always returned; the body is only for reading what a path held\",\n required: false,\n },\n} as const;\n\nregisterSchema({\n command: \"analytics.sources\",\n routes: [\"POST /api/analytics/sources\"],\n effect: \"write\",\n description:\n \"Where events reach Baker from a server: the client's own server door, HubSpot events Baker reads, and ActiveCampaign events its webhook sends — what each one watches and reads, and how it is doing\",\n args,\n});\n\n/** The value a repeated flag carries at this position, in either spelling, or nothing. */\nfunction flagValueAt(argv: readonly string[], flag: string, index: number): string | undefined {\n const arg = argv[index] ?? \"\";\n if (arg === flag) return argv[index + 1];\n return arg.startsWith(`${flag}=`) ? arg.slice(flag.length + 1) : undefined;\n}\n\n/** Every value of a repeated flag on the command line, in order. */\nexport function parseRepeated(argv: readonly string[], flag: string): string[] {\n const values: string[] = [];\n for (let index = 0; index < argv.length; index += 1) {\n const value = flagValueAt(argv, flag, index);\n if (value !== undefined) values.push(value);\n }\n return values;\n}\n\n/** Every `--field k=v` on the command line, in order, refusing a malformed one. */\nexport function parseFieldArgs(argv: readonly string[]): Record<string, string> {\n const mapping: Record<string, string> = {};\n for (const pair of parseRepeated(argv, \"--field\")) {\n const eq = pair.indexOf(\"=\");\n const field = eq === -1 ? pair : pair.slice(0, eq);\n const path = eq === -1 ? \"\" : pair.slice(eq + 1).trim();\n const problem = mappingRowProblem(field);\n if (problem !== null) throw new ConversionArgsError(problem);\n if (path === \"\") throw new ConversionArgsError(`--field ${field} needs a path: --field ${field}=<dotted.path>.`);\n mapping[field] = path;\n }\n return mapping;\n}\n\n/** The amount pair, which travels together or not at all. */\nfunction amountArgs(raw: Record<string, unknown>, argv: readonly string[]) {\n const amountProperty = onlyOnce(raw[\"amount-property\"], \"--amount-property\", argv);\n const currency = onlyOnce(raw.currency, \"--currency\", argv);\n if ((amountProperty === undefined) !== (currency === undefined)) {\n throw new ConversionArgsError(\"--amount-property and --currency go together: name both or neither.\");\n }\n return {\n ...(amountProperty === undefined ? {} : { amountProperty }),\n ...(currency === undefined ? {} : { currency }),\n };\n}\n\nconst NO_VALUE_OPERATORS = new Set([\"isEmpty\", \"isNotEmpty\"]);\n\n/**\n * The trigger every HubSpot verb needs: the property, how it has to read,\n * and the values — repeated on the command line, read off argv. Refused with\n * where the names come from; what the property's kind allows is checked\n * against the account by the backend.\n */\nfunction triggerArgs(raw: Record<string, unknown>, argv: readonly string[], verb: string): TriggerInput {\n const conditions = onlyOnce(raw.conditions, \"--conditions\", argv);\n if (conditions !== undefined) return conditionsArg(conditions, raw, verb);\n const property = onlyOnce(raw.property, \"--property\", argv);\n const operator = onlyOnce(raw.operator, \"--operator\", argv) ?? \"is\";\n // The last --value is what citty kept; every one is what was typed.\n const values = argv.length === 0 && typeof raw.value === \"string\" ? [raw.value] : parseRepeated(argv, \"--value\");\n if (property === undefined) {\n throw new ConversionArgsError(\n `--${verb} needs --property <name> [--operator <op>] --value <value>…, from \\`baker hubspot contacts properties\\`.`,\n );\n }\n if (values.length === 0 && !NO_VALUE_OPERATORS.has(operator)) {\n throw new ConversionArgsError(\n `--${verb} needs --value <value> (repeat it for a list); only --operator isEmpty / isNotEmpty take none.`,\n );\n }\n return { property, operator, values };\n}\n\ntype TriggerInput = NonNullable<SourcesRequestInput[\"createHubspot\"]>[\"trigger\"];\n\n/** `--conditions <json>`: a combination, checked for shape here so a typo is refused before the call. */\nfunction conditionsArg(text: string, raw: Record<string, unknown>, verb: string): TriggerInput {\n if (raw.property !== undefined || raw.value !== undefined || raw.operator !== undefined) {\n throw new ConversionArgsError(`--${verb} takes --conditions or --property/--operator/--value, not both.`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new ConversionArgsError(\n '--conditions is JSON: {\"logic\":\"And\",\"conditions\":[{\"property\":\"lifecyclestage\",\"values\":[\"customer\"]}]}.',\n );\n }\n const checked = hubspotTriggerInputSchema.safeParse(parsed);\n if (!checked.success) {\n throw new ConversionArgsError(`--conditions: ${checked.error.issues.map((issue) => issue.message).join(\"; \")}`);\n }\n return parsed as TriggerInput;\n}\n\n/** `--object contact|deal`, spelled the two ways the wire takes and nothing else. */\nfunction objectArg(raw: Record<string, unknown>, argv: readonly string[]): HubspotObject {\n const object = onlyOnce(raw.object, \"--object\", argv) ?? \"contact\";\n if (!(HUBSPOT_OBJECTS as readonly string[]).includes(object)) {\n throw new ConversionArgsError(`--object is one of ${HUBSPOT_OBJECTS.join(\", \")}, not \"${object}\".`);\n }\n return object as HubspotObject;\n}\n\n/** `--contacts first|every`, which only means something on a deal or a lead. */\nfunction contactsArg(raw: Record<string, unknown>, argv: readonly string[]): HubspotDealContacts | undefined {\n const contacts = onlyOnce(raw.contacts, \"--contacts\", argv);\n if (contacts === undefined) return undefined;\n if (!(HUBSPOT_DEAL_CONTACTS as readonly string[]).includes(contacts)) {\n throw new ConversionArgsError(`--contacts is one of ${HUBSPOT_DEAL_CONTACTS.join(\", \")}, not \"${contacts}\".`);\n }\n return contacts as HubspotDealContacts;\n}\n\nfunction createHubspotArgs(\n raw: Record<string, unknown>,\n argv: readonly string[],\n name: string | undefined,\n): NonNullable<SourcesRequestInput[\"createHubspot\"]> {\n const mapping = parseFieldArgs(argv);\n const object = objectArg(raw, argv);\n const contacts = contactsArg(raw, argv);\n if (contacts !== undefined && !readsAssociatedContact(object)) {\n throw new ConversionArgsError(\n \"--contacts says whose event a deal's or a lead's is; it needs --object deal or --object lead.\",\n );\n }\n return {\n // A contact is the wire's default, so it is left unsaid — the way the schema reads it back.\n ...(object === \"contact\" ? {} : { object }),\n trigger: triggerArgs(raw, argv, \"create-hubspot\"),\n ...(contacts === undefined ? {} : { contacts }),\n ...(name === undefined ? {} : { name }),\n ...(Object.keys(mapping).length === 0 ? {} : { mapping }),\n ...amountArgs(raw, argv),\n };\n}\n\n/** What to read off the sample contact: whatever the rows mention, or the default rows' properties. */\nfunction previewArgs(\n raw: Record<string, unknown>,\n argv: readonly string[],\n): NonNullable<SourcesRequestInput[\"preview\"]> {\n const rows = parseFieldArgs(argv);\n const object = objectArg(raw, argv);\n const templates = Object.values(Object.keys(rows).length === 0 ? hubspotDefaultMapping(\"\", object) : rows);\n const properties = [...new Set(templates.flatMap((template) => templateMentions(template ?? \"\")))];\n const contact = onlyOnce(raw.contact, \"--contact\", argv);\n return {\n ...(object === \"contact\" ? {} : { object }),\n trigger: triggerArgs(raw, argv, \"preview\"),\n properties,\n ...(contact === undefined ? {} : { contact }),\n };\n}\n\nconst VERBS = [\n \"server\",\n \"create\",\n \"create-hubspot\",\n \"create-activecampaign\",\n \"set-trigger\",\n \"preview\",\n \"backfill\",\n \"set-amount\",\n \"map\",\n \"pause\",\n \"resume\",\n \"remove\",\n] as const;\n\n/**\n * The name, refused here when the ingest door could never accept it.\n *\n * A source's name is the `event_name` of every event it raises, so this is\n * not a label being tidied: a name outside the rule makes a source that\n * counts **nothing**, for ever, while `baker analytics sources` goes on\n * listing it as counting and the only trace is one red line per event on the\n * feed. The contract refuses it too (`sourceNameSchema`), but that comes back\n * as a wire-validation error; the agent is better served by the sentence.\n */\nfunction checkedName(raw: Record<string, unknown>, argv: readonly string[]): string | undefined {\n const name = onlyOnce(raw.name, \"--name\", argv);\n if (name === undefined || validateEventName(name) === null) return name;\n throw new ConversionArgsError(\n `\"${name}\" cannot be an event name, and the name is what every event this source raises will carry. ${REJECTION_MESSAGES.invalid_name}`,\n );\n}\n\n/** What a backfill reads back to, and whether it counts what it finds. */\nfunction backfillArgs(\n raw: Record<string, unknown>,\n argv: readonly string[],\n sourceId: string,\n): NonNullable<SourcesRequestInput[\"backfill\"]> {\n const since = onlyOnce(raw.since, \"--since\", argv);\n if (since === undefined) {\n throw new ConversionArgsError(\n \"--backfill needs --since <date>, e.g. --since 2026-09-19. Nothing before it is read.\",\n );\n }\n const before = onlyOnce(raw.before, \"--before\", argv);\n return {\n sourceId,\n since,\n ...(before === undefined ? {} : { before }),\n ...(raw.write === true ? { write: true } : {}),\n };\n}\n\nfunction createActiveCampaignArgs(\n raw: Record<string, unknown>,\n argv: readonly string[],\n name: string | undefined,\n): NonNullable<SourcesRequestInput[\"createActiveCampaign\"]> {\n const events = onlyOnce(raw.events, \"--events\", argv);\n const account = onlyOnce(raw.account, \"--account\", argv);\n return {\n ...(name === undefined ? {} : { name }),\n ...(events === undefined\n ? {}\n : {\n events: events\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item !== \"\"),\n }),\n ...(account === undefined ? {} : { account }),\n };\n}\n\n/** The three ways to make a source: an address for a tool, a HubSpot event, ActiveCampaign events. */\nfunction createRequest(\n verb: (typeof VERBS)[number],\n raw: Record<string, unknown>,\n argv: readonly string[],\n name: string | undefined,\n): SourcesRequestInput | null {\n if (verb === \"create\") {\n if (name === undefined) throw new ConversionArgsError(\"--create needs --name <tool>.\");\n return { create: { name } };\n }\n if (verb === \"create-hubspot\") return { createHubspot: createHubspotArgs(raw, argv, name) };\n if (verb === \"create-activecampaign\") return { createActiveCampaign: createActiveCampaignArgs(raw, argv, name) };\n return null;\n}\n\nexport function sourcesRequest(raw: Record<string, unknown>, argv: readonly string[]): SourcesRequestInput {\n const name = checkedName(raw, argv);\n const source = onlyOnce(raw.source, \"--source\", argv);\n const verbs = VERBS.filter((verb) => raw[verb] === true);\n if (verbs.length > 1) throw new ConversionArgsError(`One of --${verbs.join(\", --\")} per call.`);\n const verb = verbs[0];\n if (verb === undefined) return {};\n if (verb === \"server\") return { server: {} };\n const made = createRequest(verb, raw, argv, name);\n if (made !== null) return made;\n if (verb === \"preview\") return { preview: previewArgs(raw, argv) };\n if (source === undefined) throw new ConversionArgsError(`--${verb} needs --source <id>, from the list.`);\n if (verb === \"backfill\") return { backfill: backfillArgs(raw, argv, source) };\n if (verb === \"set-trigger\") {\n const contacts = contactsArg(raw, argv);\n return {\n setTrigger: {\n sourceId: source,\n trigger: triggerArgs(raw, argv, verb),\n ...(contacts === undefined ? {} : { contacts }),\n },\n };\n }\n if (verb === \"set-amount\") return { setAmount: { sourceId: source, ...amountArgs(raw, argv) } };\n if (verb === \"map\") return { map: { sourceId: source, mapping: parseFieldArgs(argv) } };\n return { [verb]: { sourceId: source } };\n}\n\nfunction handleError(err: unknown): never {\n if (err instanceof ApiError) {\n // A HubSpot event needs HubSpot connected, and allowed to read what it watches.\n const refusal = hubspotRefusal(err.code, err.message);\n writeJsonEnvelope({\n ok: false,\n error:\n refusal === null\n ? { code: err.code, message: err.message }\n : { code: refusal.code, message: err.message, fix: refusal.fix },\n });\n process.exit(1);\n }\n writeJsonEnvelope({\n ok: false,\n error: { code: \"NETWORK_ERROR\", message: err instanceof Error ? err.message : \"Unexpected error\" },\n });\n process.exit(1);\n}\n\nexport const sourcesCommand = defineCommand({\n meta: {\n name: \"sources\",\n description:\n 'Where events reach Baker from a server, and what each one reads. Two doors. **The client\\'s own server**: `--server` prints one address for their developers — made once, the same for ever, counting at once, Baker\\'s own `POST /v1/events` format (`baker analytics sending-events` has the contract, `X-Baker-Mode: test` rehearses). **HubSpot events**: HubSpot keeps each change to a watched property in a journal Baker reads every half minute — Baker\\'s app subscribes the account to that one property with the condition as HubSpot\\'s own filter, so an account with a million contacts costs nothing to watch — on every plan, nothing to set up in HubSpot. The trigger is *when a contact\\'s* property satisfies a condition — the same conditions a Form\\'s filters take: `--property lifecyclestage --value customer` (a dropdown; `--value lead --value customer` for either), `--property deal_value --operator greaterThan --value 1000`, `--property email --operator endsWith --value @acme.com`, `--property closed_at --operator isAfter --value 2026-01-01`, `--property phone --operator isEmpty`. Several conditions combine the way a Form\\'s filter does — `--conditions \\'{\"logic\":\"And\",\"conditions\":[{\"property\":\"lifecyclestage\",\"values\":[\"customer\"]},{\"property\":\"country\",\"values\":[\"Spain\"]}]}\\'` (AND / OR, groups one level deep, 10 conditions at most) in place of --property/--operator/--value, on --create-hubspot, --set-trigger and --preview; the event fires when a change to any named property makes the whole combination hold. `baker hubspot contacts properties` lists every property with its kind, the operators that kind takes and a dropdown\\'s values; `baker hubspot contacts fields` every property a row can read. `--preview --property … [--operator …] --value … [--field …] [--contact <id or email>]` says how many contacts satisfy it today (NOT counted — only contacts that come to satisfy it from now on are) and reads one real contact so every row can be checked against real data; then `--create-hubspot --property … --value … --name \"Deal won\" --field email={{work_email}} --field value={{deal_value}} --field currency=EUR` makes the event, rows over the defaults (email, phone, the contact id, name, address, hs_google_click_id, hs_facebook_click_id). `--set-trigger --source <id> --property … --operator … --value …` changes what an event watches later (rows kept, counting from now on). Every row is a template — text with {{property}} mentions, one thing per mention; `--map --source <id> --field …` replaces the whole row set later, `--amount-property <number property> --currency EUR` is the short spelling for the amount rows. Each event is an ordinary event named after the source, carrying `baker_source`, listed by `feed --source <name>`, counted with `conversions` under `page:<name>`, and sent to the ad platforms with `sends`. **ActiveCampaign events**: `--create-activecampaign [--events subscribe,deal_update] [--name …] [--account <id>]` stages a source that the ActiveCampaign webhook sends to once the chat is published; each arrival is an event called `activecampaign.<event>` — whatever the source is called — carrying the contact and the rest of the ActiveCampaign payload as `properties.*` (the stage of a deal, the tag, the campaign), which is what a scheduled agent on `event.received --event activecampaign.<event>` runs on. `--pause`, `--resume`, `--remove` by --source; removing an ActiveCampaign source deletes its webhook. `--create --name <tool>` still makes an address for a tool that cannot be told what to send; its first send is a masked sample counted as nothing until `--map` confirms the rows.',\n },\n args,\n run: async ({ args: raw }) => {\n try {\n const request = sourcesRequest(raw as Record<string, unknown>, process.argv);\n const response = await apiPost<SourcesResponse>(\"/api/analytics/sources\", request);\n const full = raw.full === true;\n const sources = response.data.sources.map((source) => {\n const { sample, ...rest } = source;\n return full || sample === undefined ? source : { ...rest, sample: { receivedAt: sample.receivedAt } };\n });\n writeJsonEnvelope({\n ok: true,\n data: {\n sources,\n ...(response.data.preview === undefined ? {} : { preview: response.data.preview }),\n ...(response.data.staged === undefined ? {} : { staged: response.data.staged }),\n },\n ...(response.hints && response.hints.length > 0 ? { hints: response.hints } : {}),\n });\n } catch (err) {\n if (err instanceof ConversionArgsError) {\n handleError(new ApiError(\"VALIDATION_ERROR\", err.message));\n }\n handleError(err);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,qBAAqB;AA6B9B,IAAM,OAAO;AAAA,EACX,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,kBAAkB;AAAA,IA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