@koda-sl/baker-cli 0.852.0-dev.0fbe16456 → 0.852.0-dev.65f932cdf
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 +1 -4
- package/dist/{activities-SUUW5KH7.js → activities-NWXWO7T2.js} +3 -3
- package/dist/{ads-DJHUXK2O.js → ads-BYETTX2Y.js} +2 -2
- package/dist/{ads-2O3DC7ZM.js → ads-EUQYHCBO.js} +5 -12
- package/dist/ads-EUQYHCBO.js.map +1 -0
- package/dist/{adsets-PMEPGGAI.js → adsets-CZFTSQQC.js} +3 -3
- package/dist/{analytics-SVV7JZ2J.js → analytics-KA3THH3F.js} +2 -2
- package/dist/{audiences-Y6UFKHZ5.js → audiences-SDFCRXHD.js} +3 -3
- package/dist/{campaigns-RNPLAVXM.js → campaigns-4JY3JKPY.js} +3 -3
- package/dist/{chunk-PRPSV4VB.js → chunk-DKRPMGEN.js} +1 -17
- package/dist/chunk-DKRPMGEN.js.map +1 -0
- package/dist/{chunk-TWSIY2FS.js → chunk-H3CYVM4E.js} +7 -3
- package/dist/chunk-H3CYVM4E.js.map +1 -0
- package/dist/{chunk-GN6X5C57.js → chunk-S2WUFUSW.js} +3 -4
- package/dist/chunk-S2WUFUSW.js.map +1 -0
- package/dist/cli.js +3 -3
- package/dist/{creatives-OTKJRMBJ.js → creatives-Q3DWV55N.js} +3 -3
- package/dist/{hubspot-W5LYFWTH.js → hubspot-NG2KTQDY.js} +2 -2
- package/dist/{leads-DAXPX7V5.js → leads-UTBT62TH.js} +2 -3
- package/dist/leads-UTBT62TH.js.map +1 -0
- package/dist/{meta-GSTM6EBD.js → meta-2ZQ3CWLF.js} +10 -10
- package/dist/{sources-G7QWYL2J.js → sources-DVNWHBF5.js} +10 -4
- package/dist/sources-DVNWHBF5.js.map +1 -0
- package/dist/{targeting-HIXQGQ7A.js → targeting-T2HTV2OD.js} +2 -2
- package/package.json +1 -1
- package/dist/ads-2O3DC7ZM.js.map +0 -1
- package/dist/chunk-GN6X5C57.js.map +0 -1
- package/dist/chunk-PRPSV4VB.js.map +0 -1
- package/dist/chunk-TWSIY2FS.js.map +0 -1
- package/dist/leads-DAXPX7V5.js.map +0 -1
- package/dist/sources-G7QWYL2J.js.map +0 -1
- /package/dist/{activities-SUUW5KH7.js.map → activities-NWXWO7T2.js.map} +0 -0
- /package/dist/{ads-DJHUXK2O.js.map → ads-BYETTX2Y.js.map} +0 -0
- /package/dist/{adsets-PMEPGGAI.js.map → adsets-CZFTSQQC.js.map} +0 -0
- /package/dist/{analytics-SVV7JZ2J.js.map → analytics-KA3THH3F.js.map} +0 -0
- /package/dist/{audiences-Y6UFKHZ5.js.map → audiences-SDFCRXHD.js.map} +0 -0
- /package/dist/{campaigns-RNPLAVXM.js.map → campaigns-4JY3JKPY.js.map} +0 -0
- /package/dist/{creatives-OTKJRMBJ.js.map → creatives-Q3DWV55N.js.map} +0 -0
- /package/dist/{hubspot-W5LYFWTH.js.map → hubspot-NG2KTQDY.js.map} +0 -0
- /package/dist/{meta-GSTM6EBD.js.map → meta-2ZQ3CWLF.js.map} +0 -0
- /package/dist/{targeting-HIXQGQ7A.js.map → targeting-T2HTV2OD.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/ads/meta/leads.ts","../src/commands/ads/meta/lead-form-writes.ts"],"sourcesContent":["import { isMetaLeadAdsRefusal } from \"@baker/api/ads-meta\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiGet } from \"../../../client.ts\";\nimport { withWindowSpellings } from \"../../../date-window.ts\";\nimport { registerSchema } from \"../../../schemas.ts\";\nimport { writeAdsJson, writeAdsOutput, writeJsonEnvelope } from \"../output.ts\";\nimport {\n leadFormsArchiveCommand,\n leadFormsCreateCommand,\n leadFormsDuplicateCommand,\n leadFormsSpecCommand,\n leadFormsUnarchiveCommand,\n} from \"./lead-form-writes.ts\";\nimport { csvOrJson, handleMetaError } from \"./shared.ts\";\n\n/** An instant form attached to a Facebook Page. */\nexport interface MetaLeadForm {\n id: string;\n name?: string;\n status?: string;\n locale?: string;\n leads_count?: number;\n created_time?: string;\n}\n\n/** One page of leads plus the cursor that continues it. */\nexport interface MetaLeadPage {\n leads: MetaLead[];\n /** Present only while Meta says another page exists. */\n nextCursor?: string;\n /** What the backend says about this page (every answer masked when it could not tell contact questions apart). */\n hints?: string[];\n}\n\n/** One lead, already shaped by the backend (contact values masked unless --full). */\nexport interface MetaLead {\n id: string;\n created_time?: string;\n ad_id?: string;\n ad_name?: string;\n adset_id?: string;\n adset_name?: string;\n campaign_id?: string;\n campaign_name?: string;\n form_id?: string;\n is_organic?: boolean;\n platform?: string;\n answers: Record<string, string>;\n /** Each disclaimer checkbox by its key: ticked or not. */\n consents?: Record<string, boolean>;\n partner_name?: string;\n}\n\nregisterSchema({\n command: \"ads.meta.lead-forms\",\n description:\n \"List the instant (lead) forms on a Facebook Page, with how many leads each has collected. Start here: a lead is fetched by form id. Use a Page from `baker ads meta pages` with hasPageAccessToken: true.\",\n args: {\n \"page-id\": {\n type: \"string\",\n description: \"Facebook Page ID — from `baker ads meta pages` with hasPageAccessToken: true\",\n required: true,\n },\n full: { type: \"boolean\", description: \"Include each form's questions\", required: false },\n output: { type: \"string\", description: \"json|csv\", required: false, default: \"json\" },\n },\n});\n\nregisterSchema({\n command: \"ads.meta.leads\",\n description:\n \"Read the leads an instant form collected. Contact details (email, phone) come back masked; pass --full only when the raw values are genuinely needed, e.g. handing them to a CRM.\",\n args: withWindowSpellings({\n \"form-id\": { type: \"string\", description: \"Instant form ID — from `baker ads meta lead-forms`\", required: false },\n \"ad-id\": { type: \"string\", description: \"Read the leads of one ad instead of a whole form\", required: false },\n \"adset-id\": { type: \"string\", description: \"Read the leads of every ad in an ad set\", required: false },\n \"campaign-id\": { type: \"string\", description: \"Read the leads of every ad in a campaign\", required: false },\n since: { type: \"string\", description: \"Earliest submission date, YYYY-MM-DD\", required: false },\n until: { type: \"string\", description: \"Latest submission date, YYYY-MM-DD (inclusive)\", required: false },\n limit: { type: \"string\", description: \"Leads per page (default 100, max 500)\", required: false },\n after: {\n type: \"string\",\n description: \"Cursor from a previous call's nextCursor — fetches the following page\",\n required: false,\n },\n full: { type: \"boolean\", description: \"Return raw contact details instead of masked ones\", required: false },\n output: { type: \"string\", description: \"json|csv\", required: false, default: \"json\" },\n }),\n});\n\n/**\n * A form that exists but has never collected anything is the single most common\n * thing to misread here — it looks identical to a permissions problem in the\n * output, and the remedies are opposite. Say which it is.\n */\n/** The backend drains instant forms up to this many; see `META_LEAD_FORMS_MAX`. */\nconst LEAD_FORMS_CAP = 500;\n\nexport function leadFormHints(forms: MetaLeadForm[]): string[] {\n if (forms.length === 0) {\n return [\"This Page has NO instant forms. Nothing to read leads from — the form has to be created first.\"];\n }\n if (forms.length >= LEAD_FORMS_CAP) {\n return [\n `PARTIAL LIST — this Page has at least ${LEAD_FORMS_CAP} instant forms and only the first ${LEAD_FORMS_CAP} came back. Do not describe this as every form on the Page.`,\n ];\n }\n const empty = forms.filter((form) => (form.leads_count ?? 0) === 0);\n if (empty.length === forms.length) {\n return [\n \"Every form on this Page has collected 0 leads. That is a real, readable answer — the connection works. Do not retry and do not report it as a permissions problem.\",\n ];\n }\n return [];\n}\n\n/**\n * A `FORBIDDEN` that Baker itself produced is already conclusive, so it must not\n * collect the generic ambiguous-403 remedy.\n *\n * `metaForbiddenFix` exists for Meta's own 403, which covers two causes with\n * opposite fixes and can only be told apart by testing the blast radius. Pasting\n * that after *\"this needs switching on by the Baker team\"* would hand the agent\n * a paragraph suggesting a reconnect right underneath a sentence saying a\n * reconnect cannot help — and the agent would pass it on, costing the client a\n * pointless round trip through their Meta login. Everything that is genuinely\n * Meta's still goes through the normal handler.\n */\nfunction handleLeadsError(err: unknown): never {\n if (err instanceof ApiError && err.code === \"FORBIDDEN\" && isMetaLeadAdsRefusal(err.message)) {\n writeAdsJson({\n ok: false,\n error: {\n code: err.code,\n message: err.message,\n fix: { action: \"reject\", explanation: err.message },\n retryable: false,\n },\n });\n process.exit(1);\n }\n handleMetaError(err);\n}\n\n/**\n * What the agent has to know before it reports a number.\n *\n * Counting is what this command is mostly used for, so a page that is full is\n * the dangerous case: without a word, 100 rows read as \"100 leads\" and the\n * client is told something false. The cursor is the remedy, and it has to be\n * named in the same breath as the warning.\n */\nexport function leadPageHints(page: MetaLeadPage, full: boolean): string[] {\n const hints: string[] = [];\n if (page.nextCursor) {\n hints.push(\n `PARTIAL PAGE — more leads exist. This is ${page.leads.length} of an unknown larger number; do NOT report it as a total. Fetch the next page with \\`--after ${page.nextCursor}\\` (repeat until no nextCursor), or narrow the window with --since/--until.`,\n );\n }\n if (!full) {\n hints.push(\n \"Answers that give contact details (email, phone, any question asking for one) are masked. Report on them as they are; pass --full only when the raw values have to leave Baker (a CRM hand-off), and never paste them into the chat otherwise.\",\n );\n }\n hints.push(...(page.hints ?? []));\n return hints;\n}\n\nconst LEAD_SOURCE_NOUNS = {\n \"form-id\": \"form\",\n \"ad-id\": \"ad\",\n \"adset-id\": \"ad set\",\n \"campaign-id\": \"campaign\",\n} as const;\n\n/**\n * An empty page is only an answer for the scope it searched. Name the form, ad,\n * ad set or campaign and the window, so \"no leads\" is never mistaken for a wrong scope.\n * A page reached by `--after` follows pages that may have held leads: it ends the read, nothing more.\n */\nfunction emptyLeadsHints(page: MetaLeadPage, params: Record<string, string>): string[] {\n if (page.leads.length > 0 || page.nextCursor) return [];\n const source = Object.entries(LEAD_SOURCE_NOUNS)\n .filter(([flag]) => params[flag])\n .map(([flag, noun]) => `${noun} ${params[flag]}`)\n .join(\", \");\n const window =\n [params.since ? `since ${params.since}` : \"\", params.until ? `through ${params.until}` : \"\"]\n .filter(Boolean)\n .join(\" \") || \"at any date\";\n if (params.after) {\n return [`No more leads on ${source} ${window}: this page ends the read, so add it to the earlier pages' leads.`];\n }\n return [\n `No leads on ${source} ${window}. That is the answer for this scope; widen the window or read another form only if the question was wider.`,\n ];\n}\n\nconst leadFormsListArgs = {\n \"page-id\": { type: \"string\", description: \"Facebook Page ID\" },\n full: { type: \"boolean\", description: \"Include each form's questions\" },\n output: { type: \"string\", description: \"Output format: json|csv|jsonl|md\", default: \"json\" },\n} as const;\n\nconst leadFormsListCommand = defineCommand({\n meta: {\n name: \"list\",\n description:\n \"List the Instant Forms on a Facebook Page, with lead counts. Choose a Page with hasPageAccessToken: true from `baker ads meta pages`. Pass --full to include questions.\",\n },\n args: leadFormsListArgs,\n run: async ({ args }) => {\n try {\n const pageId = args[\"page-id\"] as string | undefined;\n if (!pageId) {\n handleLeadsError(\n new Error(\n \"--page-id is required. Run `baker ads meta pages` and choose a Page with hasPageAccessToken: true.\",\n ),\n );\n }\n const params: Record<string, string> = { \"page-id\": pageId };\n if (args.full) params.full = \"true\";\n const data = await apiGet<MetaLeadForm[]>(\"/api/ads/meta/lead-forms\", params);\n const fmt = csvOrJson(args);\n if (fmt !== \"json\") {\n writeAdsOutput(data as unknown as Array<Record<string, unknown>>, fmt);\n return;\n }\n const hints = leadFormHints(data);\n writeJsonEnvelope(hints.length > 0 ? { ok: true, data, hints } : { ok: true, data });\n } catch (err) {\n handleLeadsError(err);\n }\n },\n});\n\nexport const leadFormsCommand = defineCommand({\n meta: {\n name: \"lead-forms\",\n description: `List Instant Forms on a Facebook Page, or stage a new one, a changed copy, an archive.\nA form is permanent on Meta and nothing on it changes once made: to change one, duplicate it with changes and archive the old one.\nExamples:\n baker ads meta lead-forms --page-id 100635183117758\n baker ads meta lead-forms --page-id 100635183117758 --full\n baker ads meta lead-forms create --account-id act_123 --page-id 555 --file form.json\n baker ads meta lead-forms spec 987654321 — a live form as a create --file payload\n baker ads meta lead-forms duplicate 987654321 --account-id act_123 --name \"Free audit (ES)\" --locale ES_LA\n baker ads meta lead-forms archive 987654321 --account-id act_123`,\n },\n args: leadFormsListArgs,\n subCommands: {\n list: leadFormsListCommand,\n create: leadFormsCreateCommand,\n spec: leadFormsSpecCommand,\n duplicate: leadFormsDuplicateCommand,\n archive: leadFormsArchiveCommand,\n unarchive: leadFormsUnarchiveCommand,\n },\n default: \"list\",\n});\n\nexport const leadsCommand = defineCommand({\n meta: {\n name: \"leads\",\n description: `Read the leads an instant form collected. Every question comes back; email and phone answers are MASKED unless you pass --full, so you can report on what a form is collecting without moving contact details around.\n\nExamples:\n baker ads meta leads --form-id 987654321\n baker ads meta leads --form-id 987654321 --since 2026-08-01 --until 2026-08-31\n baker ads meta leads --ad-id 6123456789 --limit 50\n baker ads meta leads --adset-id 6123456780 --since 2026-08-01 # every ad in the ad set (Meta has no ad set edge)\n baker ads meta leads --form-id 987654321 --after <nextCursor> # the next page\n baker ads meta leads --form-id 987654321 --full # raw contact details — only when handing leads over\n\nResults are PAGED. A response carrying \\`nextCursor\\` is not the whole set — follow it before reporting any total.`,\n },\n args: withWindowSpellings({\n \"form-id\": { type: \"string\", description: \"Instant form ID (from `baker ads meta lead-forms`)\" },\n \"ad-id\": { type: \"string\", description: \"Read one ad's leads instead of a whole form\" },\n \"adset-id\": { type: \"string\", description: \"Read the leads of every ad in an ad set\" },\n \"campaign-id\": { type: \"string\", description: \"Read the leads of every ad in a campaign\" },\n since: { type: \"string\", description: \"Earliest submission date, YYYY-MM-DD\" },\n until: { type: \"string\", description: \"Latest submission date, YYYY-MM-DD (inclusive)\" },\n limit: { type: \"string\", description: \"Leads per page (default 100, max 500)\" },\n after: { type: \"string\", description: \"Cursor from a previous call's nextCursor\" },\n full: { type: \"boolean\", description: \"Return raw contact details instead of masked ones\" },\n output: { type: \"string\", description: \"Output format: json|csv|jsonl|md\", default: \"json\" },\n }),\n run: async ({ args }) => {\n try {\n const params: Record<string, string> = {};\n for (const flag of [\"form-id\", \"ad-id\", \"adset-id\", \"campaign-id\"] as const) {\n const value = args[flag];\n if (typeof value === \"string\" && value.length > 0) params[flag] = value;\n }\n if (Object.keys(params).length !== 1) {\n handleLeadsError(\n new Error(\"Pass one of --form-id (from `baker ads meta lead-forms`), --ad-id, --adset-id or --campaign-id.\"),\n );\n }\n if (args.since) params.since = args.since as string;\n if (args.until) params.until = args.until as string;\n if (args.limit) params.limit = String(args.limit);\n if (args.after) params.after = String(args.after);\n if (args.full) params.full = \"true\";\n const page = await apiGet<MetaLeadPage>(\"/api/ads/meta/leads\", params);\n const emptyHints = emptyLeadsHints(page, params);\n const fmt = csvOrJson(args);\n if (fmt !== \"json\") {\n writeAdsOutput(page.leads as unknown as Array<Record<string, unknown>>, fmt, undefined, emptyHints);\n return;\n }\n writeJsonEnvelope({\n ok: true,\n data: page.leads,\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n hints: [...emptyHints, ...leadPageHints(page, args.full === true)],\n });\n } catch (err) {\n handleLeadsError(err);\n }\n },\n});\n","import { defineCommand } from \"citty\";\nimport { apiGet } from \"../../../client.ts\";\nimport { repeatedValues } from \"../../../lib/repeatedFlags.ts\";\nimport { registerSchema, withEffect } from \"../../../schemas.ts\";\nimport { writeJsonEnvelope } from \"../output.ts\";\nimport { handleMetaError } from \"./shared.ts\";\nimport {\n bareAccountId,\n failWriteValidation,\n fileArg,\n loadJsonFileArg,\n mergePayload,\n metaStages,\n requireTarget,\n stageOp,\n upper,\n} from \"./write-shared.ts\";\n\n/**\n * Staging Instant Forms. A form is permanent on Meta — it is never deleted,\n * only archived — and nothing on it changes once it exists, so every write\n * here is a new form (create, duplicate) or an archive / unarchive, all staged\n * on this chat's draft and applied at publish.\n */\n\ntype Args = Record<string, unknown>;\n\nconst STAGED_NOTE = \"Staged until publish — review with `baker ads meta draft`.\";\n\nconst str = (value: unknown): string | undefined => (typeof value === \"string\" && value.length > 0 ? value : undefined);\n\n/** `\"Question? => answer | answer\"` → a CUSTOM question, multiple choice when it lists answers. */\nfunction customQuestion(value: string): Record<string, unknown> {\n const [label = \"\", answers] = value.split(\"=>\").map((part) => part.trim());\n const options = answers\n ?.split(\"|\")\n .map((answer) => answer.trim())\n .filter(Boolean)\n .map((answer) => ({ value: answer }));\n return { type: \"CUSTOM\", label, ...(options && options.length > 0 ? { options } : {}) };\n}\n\nfunction questionsFromFlags(args: Args, rawArgs: readonly string[] | undefined): unknown[] | undefined {\n const predefined = (str(args.questions) ?? \"\")\n .split(\",\")\n .map((type) => type.trim().toUpperCase())\n .filter(Boolean)\n .map((type) => ({ type }));\n const custom = repeatedValues(rawArgs, \"question\", args.question).map(customQuestion);\n const all = [...predefined, ...custom];\n return all.length > 0 ? all : undefined;\n}\n\n/**\n * The intro fields the flags name, and only those: a duplicate keeps every\n * other intro field of the live form (`mergeDuplicateSpec`), so `--intro-title`\n * alone does not wipe the text and `--intro-button` alone is not dropped.\n */\nfunction introFromFlags(args: Args, rawArgs: readonly string[] | undefined): Record<string, unknown> | undefined {\n const content = repeatedValues(rawArgs, \"intro-text\", args[\"intro-text\"]);\n const set = {\n ...(str(args[\"intro-title\"]) ? { title: str(args[\"intro-title\"]) } : {}),\n ...(content.length > 0 ? { style: content.length > 1 ? \"LIST_STYLE\" : \"PARAGRAPH_STYLE\", content } : {}),\n ...(str(args[\"intro-button\"]) ? { buttonText: str(args[\"intro-button\"]) } : {}),\n };\n return Object.keys(set).length > 0 ? set : undefined;\n}\n\nfunction thankYouFromFlags(args: Args): Record<string, unknown> | undefined {\n const fields = {\n title: str(args[\"thank-you-title\"]),\n body: str(args[\"thank-you-body\"]),\n buttonType: upper(args[\"thank-you-button\"]),\n buttonText: str(args[\"thank-you-button-text\"]),\n websiteUrl: str(args[\"thank-you-url\"]),\n businessPhoneNumber: str(args[\"thank-you-phone\"]),\n countryCode: upper(args[\"thank-you-country\"]),\n };\n const set = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));\n return Object.keys(set).length > 0 ? set : undefined;\n}\n\nfunction trackingFromFlags(args: Args, rawArgs: readonly string[] | undefined): Record<string, string> | undefined {\n const pairs = repeatedValues(rawArgs, \"tracking\", args.tracking).map((pair) => {\n const at = pair.indexOf(\"=\");\n if (at <= 0) failWriteValidation(`--tracking takes name=value, got \"${pair}\"`);\n return [pair.slice(0, at).trim(), pair.slice(at + 1).trim()] as const;\n });\n return pairs.length > 0 ? Object.fromEntries(pairs) : undefined;\n}\n\n/** The `leadForm.create` fields the flags name; anything a flag leaves out comes from `--file`. */\nexport function leadFormPayloadFromFlags(args: Args, rawArgs?: readonly string[]): Record<string, unknown> {\n const quality = args[\"higher-intent\"] ?? args[\"optimized-for-quality\"];\n return {\n page_id: str(args[\"page-id\"]),\n name: str(args.name),\n locale: upper(args.locale),\n questionPageHeadline: str(args.headline),\n questions: questionsFromFlags(args, rawArgs),\n privacyPolicyUrl: str(args[\"privacy-policy-url\"]),\n privacyPolicyLinkText: str(args[\"privacy-link-text\"]),\n followUpActionUrl: str(args[\"follow-up-url\"]),\n optimizedForQuality: typeof quality === \"boolean\" ? quality : undefined,\n intro: introFromFlags(args, rawArgs),\n thankYou: thankYouFromFlags(args),\n sharing: str(args.sharing)?.toLowerCase(),\n smsVerification: args[\"sms-verification\"] === true ? true : undefined,\n trackingParameters: trackingFromFlags(args, rawArgs),\n };\n}\n\n/**\n * A `--file` form as staged. `lead-forms spec > form.json` writes the CLI's\n * `{ok, data, hints}` envelope, so the form is its `data`; a hand-written file\n * is the form itself.\n */\nexport function formFileForStaging(raw: Record<string, unknown>): Record<string, unknown> {\n const data = raw.ok === true && \"data\" in raw ? raw.data : raw;\n return data && typeof data === \"object\" && !Array.isArray(data) ? (data as Record<string, unknown>) : raw;\n}\n\n/** The screens a duplicate changes field by field, so a flag naming one field keeps the others. */\nconst SCREENS = [\"intro\", \"thankYou\"] as const;\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\n/** `over` on `base`, the intro and thank-you screens merged a field at a time. */\nfunction mergeOver(base: Record<string, unknown>, over: Record<string, unknown>): Record<string, unknown> {\n const merged = mergePayload(base, over);\n for (const screen of SCREENS) {\n const from = record(base[screen]);\n const to = record(over[screen]);\n if (from && to) merged[screen] = mergePayload(from, to);\n }\n return merged;\n}\n\n/**\n * A duplicate: the live form, then the `--file` changes over it, then the\n * flags over both. Forms are permanent, so the intro and thank-you screens\n * change only in the fields named — never wholesale.\n */\nexport function mergeDuplicateSpec(\n live: Record<string, unknown>,\n changes: Record<string, unknown>,\n flags: Record<string, unknown>,\n): Record<string, unknown> {\n return mergeOver(mergeOver(live, changes), flags);\n}\n\nconst FORM_FLAG_ARGS = {\n name: { type: \"string\", description: \"Form name — unique among the Page's forms (archived ones count)\" },\n locale: {\n type: \"string\",\n description:\n \"Form language, e.g. EN_US, ES_LA, PT_BR, FR_FR, DE_DE (Meta's 32) — Meta words its own questions in it\",\n },\n headline: { type: \"string\", description: \"Headline above the questions\" },\n questions: {\n type: \"string\",\n description:\n \"Questions Meta words itself, comma-separated: FULL_NAME,EMAIL,PHONE,WORK_EMAIL,COMPANY_NAME,JOB_TITLE,CITY,ZIP,DOB…\",\n },\n question: {\n type: \"string\",\n description: 'A custom question, repeatable: \"Question?\" or multiple choice \"Question? => Answer | Answer\"',\n },\n \"privacy-policy-url\": { type: \"string\", description: \"Public https privacy policy (required)\" },\n \"privacy-link-text\": { type: \"string\", description: \"Words of the privacy link (≤70, default Privacy Policy)\" },\n \"follow-up-url\": { type: \"string\", description: \"https link of the default View website button\" },\n \"higher-intent\": {\n type: \"boolean\",\n description: \"Higher intent: people review their answers before submitting (default: more volume)\",\n },\n \"optimized-for-quality\": { type: \"boolean\", description: \"Same as --higher-intent\" },\n \"intro-title\": { type: \"string\", description: \"Intro screen title\" },\n \"intro-text\": { type: \"string\", description: \"Intro paragraph; repeat for bullet points\" },\n \"intro-button\": { type: \"string\", description: \"Intro screen button text\" },\n \"thank-you-title\": { type: \"string\", description: \"Thank-you screen title\" },\n \"thank-you-body\": { type: \"string\", description: \"Thank-you screen text\" },\n \"thank-you-button\": {\n type: \"string\",\n description: \"VIEW_WEBSITE|DOWNLOAD|BOOK_ON_WEBSITE|CALL_BUSINESS|WHATSAPP|P2B_MESSENGER|PROMO_CODE|NONE\",\n },\n \"thank-you-button-text\": { type: \"string\", description: \"Thank-you button text\" },\n \"thank-you-url\": { type: \"string\", description: \"Website the thank-you button opens\" },\n \"thank-you-phone\": { type: \"string\", description: \"CALL_BUSINESS: phone number, e.g. +14155550100\" },\n \"thank-you-country\": { type: \"string\", description: \"CALL_BUSINESS: the number's country, e.g. US\" },\n sharing: { type: \"string\", description: \"restricted (only people shown the ad, Meta's default) | open\" },\n \"sms-verification\": { type: \"boolean\", description: \"Confirm the PHONE answer with a text-message code\" },\n tracking: { type: \"string\", description: \"name=value Meta adds to every lead, repeatable\" },\n} as const;\n\nconst SCHEMA_FORM_ARGS = Object.fromEntries(\n Object.entries(FORM_FLAG_ARGS).map(([key, arg]) => [key, { ...arg, required: false }]),\n);\n\n// --- Create ---\n\nregisterSchema({\n command: \"ads.meta.lead-forms.create\",\n description:\n \"Start here to stage a Page-owned Meta Instant Form. The form is created only when this Session publishes, and it is permanent (Meta archives, never deletes). Use the returned meta_temp_* ref as --lead-form on a creative in the same Session. --file takes the whole spec (questions with keys, options, inlineContext; intro; disclaimer with checkboxes; thankYou; sharing; trackingParameters). Before staging: lead ads switched on for the company (`baker ads meta account` → bakerPermissions.leadAds) and the Page's lead terms accepted (`baker ads terms --platform meta --account-id act_<id> --page-id <id>`). The whole lead campaign (ad set ON_AD, creative --lead-form): the ads-meta tool doc § Lead ads.\",\n args: {\n \"account-id\": { type: \"string\", description: \"Selected Meta ad account, act_<id>\", required: true },\n \"page-id\": {\n type: \"string\",\n description:\n \"Facebook Page that owns the form — choose one with this account in promotingAccountIds and hasPageAccessToken: true from `baker ads meta pages`\",\n required: true,\n },\n ...SCHEMA_FORM_ARGS,\n file: {\n type: \"string\",\n description: \"JSON file with the full form payload; flags override its keys\",\n required: false,\n },\n },\n});\n\nexport const leadFormsCreateCommand = withEffect(\n metaStages(\"leadForm.create\"),\n defineCommand({\n meta: {\n name: \"create\",\n description: `Stage a Meta Instant Form on a Facebook Page. ${STAGED_NOTE} The form is permanent once published (archive it to retire it).\nChoose a Page with this account in promotingAccountIds and hasPageAccessToken: true from \\`baker ads meta pages\\`.\nExample: baker ads meta lead-forms create --account-id act_123 --page-id 456 --name \"Free audit\" --questions FULL_NAME,EMAIL,PHONE --question \"Budget? => Under 1k | 1k+\" --privacy-policy-url https://example.com/privacy --follow-up-url https://example.com\nFull spec: --file form.json (see \\`baker schema ads.meta.lead-forms.create\\`). The whole lead campaign, prerequisites first: the ads-meta tool doc § Lead ads.`,\n },\n args: {\n \"account-id\": { type: \"string\", description: \"Selected Meta ad account\" },\n \"page-id\": { type: \"string\", description: \"Facebook Page ID\" },\n ...FORM_FLAG_ARGS,\n ...fileArg(\"leadForm.create\", \"JSON form payload; flags override file keys\"),\n },\n run: async ({ args, rawArgs }) => {\n const accountId = await bareAccountId(args as Args);\n const payload = mergePayload(\n formFileForStaging(loadJsonFileArg(args.file)),\n leadFormPayloadFromFlags(args as Args, rawArgs),\n );\n await stageOp({ kind: \"leadForm.create\", accountId, payload }, [\n \"An ad opens it with `creatives create --cta SIGN_UP --lead-form <ref>` into an ad set with destination ON_AD.\",\n ]);\n },\n }),\n);\n\n// --- Spec + duplicate ---\n\ninterface FormSpec {\n spec: Record<string, unknown>;\n notCopied: string[];\n status?: string;\n}\n\nregisterSchema({\n command: \"ads.meta.lead-forms.spec\",\n description:\n \"Read a live Instant Form as the exact payload `lead-forms create --file` takes — the starting point for a changed copy. Lists what could not be carried over.\",\n args: { id: { type: \"positional\", description: \"Instant Form id\", required: true } },\n});\n\nexport const leadFormsSpecCommand = defineCommand({\n meta: {\n name: \"spec\",\n description: `A live form as the payload \\`lead-forms create --file\\` / \\`lead-forms duplicate --file\\` take.\nExample: baker ads meta lead-forms spec 1460955752594831 > form.json`,\n },\n args: { id: { type: \"positional\", description: \"Instant Form id\", required: true } },\n run: async ({ args }) => {\n try {\n const data = await apiGet<FormSpec>(\"/api/ads/meta/lead-forms/spec\", { \"form-id\": String(args.id) });\n writeJsonEnvelope({\n ok: true,\n data: data.spec,\n ...(data.notCopied.length > 0 ? { hints: [`Not carried over: ${data.notCopied.join(\"; \")}`] } : {}),\n });\n } catch (err) {\n handleMetaError(err);\n }\n },\n});\n\nregisterSchema({\n command: \"ads.meta.lead-forms.duplicate\",\n description:\n \"Stage a NEW Instant Form copied from a live one, with changes — the only way Meta lets a form change (it keeps a form's questions, texts and settings as made). --file holds the changed keys; flags override both. Point ads at the copy, then archive the original.\",\n args: {\n id: { type: \"positional\", description: \"Instant Form id to copy\", required: true },\n \"account-id\": { type: \"string\", description: \"Selected Meta ad account, act_<id>\", required: true },\n ...SCHEMA_FORM_ARGS,\n name: { type: \"string\", description: \"Name of the copy — unique on the Page\", required: true },\n file: { type: \"string\", description: \"JSON with the keys to change (same shape as create)\", required: false },\n },\n});\n\nexport const leadFormsDuplicateCommand = defineCommand({\n meta: {\n name: \"duplicate\",\n description: `Stage a changed copy of a live Instant Form (Meta changes nothing on an existing form). ${STAGED_NOTE}\nExample: baker ads meta lead-forms duplicate 1460955752594831 --account-id act_123 --name \"Free audit (ES)\" --locale ES_LA\nThen point the ads at the copy (\\`creatives create --lead-form <ref>\\`) and \\`lead-forms archive <old id>\\`.`,\n },\n args: {\n id: { type: \"positional\", description: \"Instant Form id to copy\", required: true },\n \"account-id\": { type: \"string\", description: \"Selected Meta ad account\" },\n ...FORM_FLAG_ARGS,\n file: { type: \"string\", description: \"JSON with the keys to change\" },\n },\n run: async ({ args, rawArgs }) => {\n const accountId = await bareAccountId(args as Args);\n if (!str(args.name)) failWriteValidation(\"--name is required: Meta refuses a second form with the same name\");\n let source: FormSpec;\n try {\n source = await apiGet<FormSpec>(\"/api/ads/meta/lead-forms/spec\", { \"form-id\": String(args.id) });\n } catch (err) {\n handleMetaError(err);\n }\n const flags = leadFormPayloadFromFlags(args as Args, rawArgs);\n const payload = mergeDuplicateSpec(source.spec, formFileForStaging(loadJsonFileArg(args.file)), flags);\n const notCopied = source.notCopied.length > 0 ? [`Not carried over: ${source.notCopied.join(\"; \")}`] : [];\n await stageOp({ kind: \"leadForm.create\", accountId, payload }, [\n ...notCopied,\n `Point the ads at the copy, then \\`baker ads meta lead-forms archive ${String(args.id)}\\` to retire the original.`,\n ]);\n },\n});\n\n// --- Archive / unarchive ---\n\nfunction statusCommand(name: \"archive\" | \"unarchive\", status: \"ARCHIVED\" | \"ACTIVE\", description: string) {\n registerSchema({\n command: `ads.meta.lead-forms.${name}`,\n description,\n args: {\n id: { type: \"positional\", description: \"Instant Form id\", required: true },\n \"account-id\": { type: \"string\", description: \"Ad account the change is staged under\", required: true },\n },\n });\n return withEffect(\n metaStages(\"leadForm.update\"),\n defineCommand({\n meta: {\n name,\n description: `${description} ${STAGED_NOTE}\nExample: baker ads meta lead-forms ${name} 1460955752594831 --account-id act_123`,\n },\n args: {\n id: { type: \"positional\", description: \"Instant Form id\", required: true },\n \"account-id\": { type: \"string\", description: \"Numeric account ID or act_N\" },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: \"leadForm.update\",\n accountId: await bareAccountId(args as Args),\n target: requireTarget(args as Args, \"Instant Form\"),\n payload: { status },\n });\n },\n }),\n );\n}\n\nexport const leadFormsArchiveCommand = statusCommand(\n \"archive\",\n \"ARCHIVED\",\n \"Archive an Instant Form: it leaves the Page's form library and no ad can use it. Meta never deletes a form; this is how one is retired.\",\n);\n\nexport const leadFormsUnarchiveCommand = statusCommand(\n \"unarchive\",\n \"ACTIVE\",\n \"Bring an archived Instant Form back so ads can use it again.\",\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,iBAAAA,sBAAqB;;;ACD9B,SAAS,qBAAqB;AA2B9B,IAAM,cAAc;AAEpB,IAAM,MAAM,CAAC,UAAwC,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AAG7G,SAAS,eAAe,OAAwC;AAC9D,QAAM,CAAC,QAAQ,IAAI,OAAO,IAAI,MAAM,MAAM,IAAI,EAAE,IA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docs/tools/baker/ads-meta.md`
|
|
|
110
110
|
account: () => import("./account-B57D3OSA.js").then((m) => m.accountCommand),
|
|
111
111
|
businesses: () => import("./businesses-Y555ZAIW.js").then((m) => m.businessesCommand),
|
|
112
112
|
pages: () => import("./pages-G5DNWE2G.js").then((m) => m.pagesCommand),
|
|
113
|
-
"lead-forms": () => import("./leads-
|
|
113
|
+
"lead-forms": () => import("./leads-UTBT62TH.js").then((m) => m.leadFormsCommand),
|
|
114
114
|
"instant-experiences": () => import("./instant-experiences-IRBTOXAW.js").then((m) => m.instantExperiencesCommand),
|
|
115
|
-
leads: () => import("./leads-
|
|
116
|
-
campaigns: () => import("./campaigns-
|
|
117
|
-
adsets: () => import("./adsets-
|
|
118
|
-
ads: () => import("./ads-
|
|
119
|
-
creatives: () => import("./creatives-
|
|
120
|
-
audiences: () => import("./audiences-
|
|
115
|
+
leads: () => import("./leads-UTBT62TH.js").then((m) => m.leadsCommand),
|
|
116
|
+
campaigns: () => import("./campaigns-4JY3JKPY.js").then((m) => m.campaignsCommand),
|
|
117
|
+
adsets: () => import("./adsets-CZFTSQQC.js").then((m) => m.adsetsCommand),
|
|
118
|
+
ads: () => import("./ads-EUQYHCBO.js").then((m) => m.adsListCommand),
|
|
119
|
+
creatives: () => import("./creatives-Q3DWV55N.js").then((m) => m.creativesCommand),
|
|
120
|
+
audiences: () => import("./audiences-SDFCRXHD.js").then((m) => m.audiencesCommand),
|
|
121
121
|
"custom-conversions": () => import("./custom-conversions-RFFTAVXT.js").then((m) => m.customConversionsCommand),
|
|
122
122
|
pixels: () => import("./pixels-IEIARQNK.js").then((m) => m.pixelsCommand),
|
|
123
|
-
activities: () => import("./activities-
|
|
123
|
+
activities: () => import("./activities-NWXWO7T2.js").then((m) => m.activitiesCommand),
|
|
124
124
|
insights: () => import("./insights-HCLFFFFV.js").then((m) => m.insightsCommand),
|
|
125
125
|
preview: () => import("./preview-S5QKIKNG.js").then((m) => m.previewCommand),
|
|
126
126
|
videos: () => import("./videos-KN2TUWQ6.js").then((m) => m.videosCommand),
|
|
127
|
-
targeting: () => import("./targeting-
|
|
127
|
+
targeting: () => import("./targeting-T2HTV2OD.js").then((m) => m.targetingCommand),
|
|
128
128
|
"instagram-accounts": () => import("./account-assets-MQK5BDAJ.js").then((m) => m.instagramAccountsCommand),
|
|
129
129
|
apps: () => import("./account-assets-MQK5BDAJ.js").then((m) => m.appsCommand),
|
|
130
130
|
"dsa-recommendations": () => import("./account-assets-MQK5BDAJ.js").then((m) => m.dsaRecommendationsCommand),
|
|
@@ -149,4 +149,4 @@ Full guide: __tooling__/docs/tools/baker/ads-meta.md`
|
|
|
149
149
|
export {
|
|
150
150
|
metaCommand
|
|
151
151
|
};
|
|
152
|
-
//# sourceMappingURL=meta-
|
|
152
|
+
//# sourceMappingURL=meta-2ZQ3CWLF.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
hubspotDefaultMapping,
|
|
3
3
|
hubspotTriggerInputSchema
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-H3CYVM4E.js";
|
|
5
5
|
import {
|
|
6
6
|
hubspotRefusal
|
|
7
7
|
} from "./chunk-YBSRIW5S.js";
|
|
@@ -93,6 +93,11 @@ var args = {
|
|
|
93
93
|
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",
|
|
94
94
|
required: false
|
|
95
95
|
},
|
|
96
|
+
breakdown: {
|
|
97
|
+
type: "boolean",
|
|
98
|
+
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",
|
|
99
|
+
required: false
|
|
100
|
+
},
|
|
96
101
|
object: {
|
|
97
102
|
type: "string",
|
|
98
103
|
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",
|
|
@@ -321,7 +326,8 @@ function previewArgs(raw, argv) {
|
|
|
321
326
|
...object === "contact" ? {} : { object },
|
|
322
327
|
trigger: triggerArgs(raw, argv, "preview"),
|
|
323
328
|
properties,
|
|
324
|
-
...contact === void 0 ? {} : { contact }
|
|
329
|
+
...contact === void 0 ? {} : { contact },
|
|
330
|
+
...raw.breakdown === true ? { breakdown: true } : {}
|
|
325
331
|
};
|
|
326
332
|
}
|
|
327
333
|
var VERBS = [
|
|
@@ -425,7 +431,7 @@ function handleError(err) {
|
|
|
425
431
|
var sourcesCommand = defineCommand({
|
|
426
432
|
meta: {
|
|
427
433
|
name: "sources",
|
|
428
|
-
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.'
|
|
434
|
+
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.'
|
|
429
435
|
},
|
|
430
436
|
args,
|
|
431
437
|
run: async ({ args: raw }) => {
|
|
@@ -460,4 +466,4 @@ export {
|
|
|
460
466
|
sourcesCommand,
|
|
461
467
|
sourcesRequest
|
|
462
468
|
};
|
|
463
|
-
//# sourceMappingURL=sources-
|
|
469
|
+
//# sourceMappingURL=sources-DVNWHBF5.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,UAA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C,IAAI,EAAE,SAAS,SAAS,KAAK,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"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AUDIENCE_SIZE_NOT_REPORTED,
|
|
3
3
|
metaSizeWithheld
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-DKRPMGEN.js";
|
|
5
5
|
import {
|
|
6
6
|
loadJsonFileArg
|
|
7
7
|
} from "./chunk-7M2EY3CA.js";
|
|
@@ -774,4 +774,4 @@ Start here before writing interests, behaviors, places or languages into an ad s
|
|
|
774
774
|
export {
|
|
775
775
|
targetingCommand
|
|
776
776
|
};
|
|
777
|
-
//# sourceMappingURL=targeting-
|
|
777
|
+
//# sourceMappingURL=targeting-T2HTV2OD.js.map
|
package/package.json
CHANGED
package/dist/ads-2O3DC7ZM.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/ads/meta/ads.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { NO_CACHE_ARG } from \"../../../cache-flag.ts\";\nimport { apiGet } from \"../../../client.ts\";\nimport {\n IDS_ARG,\n largeListingHints,\n META_LIST_SHAPE_ARGS,\n metaListFields,\n registerMetaListSchema,\n shapeMetaListRows,\n writeMetaListRows,\n} from \"./list-rows.ts\";\nimport {\n csvOrJson,\n handleMetaError,\n NAME_CONTAINS_ARG,\n resolveAccountIdArg,\n resolveEffectiveStatus,\n statusFilterHints,\n} from \"./shared.ts\";\n\nconst ACCOUNT_SELECTION =\n \"Account: --account-id, else BAKER_META_AD_ACCOUNT_ID, else the company's only connected Meta ad account. With several connected it refuses with MISSING_ACCOUNT_ID listing each — re-run naming one.\";\n\nconst listArgs = {\n \"account-id\": {\n type: \"string\",\n description:\n \"Meta ad account ID (act_123). Optional when the company connected only one account (or BAKER_META_AD_ACCOUNT_ID is set); required when several are connected.\",\n },\n \"adset-id\": { type: \"string\", alias: \"adset\", description: \"Filter to one adset\" },\n \"campaign-id\": { type: \"string\", alias: \"campaign\", description: \"Filter to one campaign\" },\n \"effective-status\": { type: \"string\", description: \"Comma-separated effective_status filter (overrides default)\" },\n \"all-statuses\": { type: \"boolean\", description: \"Drop the default ACTIVE filter\" },\n \"name-contains\": NAME_CONTAINS_ARG,\n ids: IDS_ARG,\n \"lead-form\": {\n type: \"string\",\n description:\n \"Only the ads whose button opens this instant form (a form id from `baker ads meta lead-forms`). Add --all-statuses to count paused ones too. Example: --lead-form 1290001 --all-statuses\",\n },\n limit: { type: \"string\", description: \"Max rows (default 1000)\" },\n \"no-cache\": NO_CACHE_ARG,\n ...META_LIST_SHAPE_ARGS,\n} as const;\n\nregisterMetaListSchema(\n \"ads\",\n `List ads in a Meta ad account, as a table by default: id, name, adset_id, campaign_id, effective_status, creative_id, issues (why an ad is WITH_ISSUES), created_time, plus each creative's link (destination), lead_form_id (the instant form its button opens) and url_tags — audit live ads' tracking in this one call, not a creatives call per ad. Which ads use a form: --lead-form <id> --all-statuses. Start here: baker ads meta ads --adset-id 6123. --fields takes dotted paths (e.g. id,tracking_specs); --full returns every field Meta sent; --output json returns the rows in the envelope. ${ACCOUNT_SELECTION}`,\n listArgs,\n);\n\nconst listCommand = defineCommand({\n meta: {\n name: \"list\",\n description: `List ads in a Meta ad account. Runs by default when no subcommand is given. ${ACCOUNT_SELECTION} Example: baker ads meta ads --account-id act_123`,\n },\n args: listArgs,\n run: async ({ args }) => {\n const accountId = await resolveAccountIdArg(args);\n const effectiveStatus = resolveEffectiveStatus(args);\n try {\n const params: Record<string, string> = { \"account-id\": accountId };\n if (args[\"adset-id\"]) params[\"adset-id\"] = args[\"adset-id\"] as string;\n if (args[\"campaign-id\"]) params[\"campaign-id\"] = args[\"campaign-id\"] as string;\n if (effectiveStatus) params[\"effective-status\"] = effectiveStatus;\n if (args[\"name-contains\"]) params[\"name-contains\"] = args[\"name-contains\"] as string;\n if (args.ids) params.ids = args.ids as string;\n if (args[\"lead-form\"]) params[\"lead-form\"] = args[\"lead-form\"] as string;\n const fields = metaListFields(\"ads\", args);\n if (fields) params.fields = fields;\n if (args.limit) params.limit = args.limit as string;\n if (args[\"no-cache\"]) params[\"skip-cache\"] = \"true\";\n const data = await apiGet<Array<Record<string, unknown>>>(\"/api/ads/meta/ads\", params);\n const shaped = shapeMetaListRows(\"ads\", data, args);\n writeMetaListRows(\"ads\", shaped, csvOrJson(args), [\n ...statusFilterHints(data, effectiveStatus, \"ads\"),\n ...largeListingHints(\"ads\", data.length),\n ]);\n } catch (err) {\n handleMetaError(err);\n }\n },\n});\n\nexport const adsListCommand = defineCommand({\n meta: {\n name: \"ads\",\n description: `List ads in a Meta ad account, or stage writes (create/update/pause/resume/archive/delete/duplicate/copy/retag).\nDefaults to ACTIVE only — pass --all-statuses to widen. Write subcommands stage ops on this chat's draft.\n${ACCOUNT_SELECTION}\n\nThe dashboard shows effective_status (e.g. WITH_ISSUES, PENDING_REVIEW, DISAPPROVED, ADSET_PAUSED), not status.\n\nListings print a table by default: id, name, adset_id, campaign_id, effective_status, creative_id, issues\n(why an ad is WITH_ISSUES), created_time, and the creative's link (destination), lead_form_id (the instant form it opens)\nand url_tags. --fields takes dotted paths (e.g. tracking_specs,\npreview_shareable_link); --full returns every field; --output json returns the rows as JSON.\n\nExamples:\n baker ads meta ads --account-id act_123\n baker ads meta ads --adset-id 6123\n baker ads meta ads --account-id act_123 --all-statuses --name-contains octubre --fields id,name,adset_id,creative_id — find one ad by name\n baker ads meta ads --adset-id 6123 --fields id,name,preview_shareable_link\n baker ads meta ads --ids 6123,6124 — the ads you have ids for, any status\n baker ads meta ads --account-id act_123 --lead-form 1290001 --all-statuses — the ads that open one instant form\n baker ads meta ads create --name \"Ad 1\" --adset meta_temp_as01 --creative meta_temp_cr01\n baker ads meta ads pause 6123 --account-id act_123\n baker ads meta ads retag 6123 --set \"utm_medium=paid-social\" — fix tracking on a LIVE ad, keeping everything else`,\n },\n subCommands: {\n list: listCommand,\n create: () => import(\"./write-commands.ts\").then((m) => m.adsCreateCommand),\n update: () => import(\"./write-commands.ts\").then((m) => m.adsUpdateCommand),\n pause: () => import(\"./write-commands.ts\").then((m) => m.adsPauseCommand),\n resume: () => import(\"./write-commands.ts\").then((m) => m.adsResumeCommand),\n archive: () => import(\"./write-commands.ts\").then((m) => m.adsArchiveCommand),\n delete: () => import(\"./write-commands.ts\").then((m) => m.adsDeleteCommand),\n duplicate: () => import(\"./write-commands.ts\").then((m) => m.adsDuplicateCommand),\n copy: () => import(\"./copy-writes.ts\").then((m) => m.adsCopyCommand),\n retag: () => import(\"./write-commands.ts\").then((m) => m.adsRetagCommand),\n },\n // `args` stays even though the parent has no `run`: citty scans rawArgs for the\n // subcommand name using THIS command's arg defs, so without them `--account-id act_1`\n // would read `act_1` as a subcommand. `default` (not `run`) dispatches the bare\n // invocation — citty falls through to `run` after a subcommand, double-executing it.\n args: listArgs,\n default: \"list\",\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAqB9B,IAAM,oBACJ;AAEF,IAAM,WAAW;AAAA,EACf,cAAc;AAAA,IACZ,MAAM;AAAA,IACN,aACE;AAAA,EACJ;AAAA,EACA,YAAY,EAAE,MAAM,UAAU,OAAO,SAAS,aAAa,sBAAsB;AAAA,EACjF,eAAe,EAAE,MAAM,UAAU,OAAO,YAAY,aAAa,yBAAyB;AAAA,EAC1F,oBAA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N,SAAS;AACX,CAAC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/ads/meta/list-rows.ts"],"sourcesContent":["import {\n AUDIENCE_SIZE_NOT_REPORTED,\n AUDIENCE_SIZE_NOTE,\n adCreativeColumns,\n adSetBudgetColumns,\n audienceColumns,\n creativeLink,\n oneOrMany,\n optimizesTo,\n texts,\n} from \"@baker/api/ads-meta/listColumns\";\nimport type { CommandRoute } from \"@baker/api/cli-catalog/entry\";\nimport { registerSchema } from \"../../../schemas.ts\";\nimport { asRecord, type CompactProjection, type ShapedRows, shapeListRows } from \"../list-rows.ts\";\nimport { writeAdsOutput } from \"../output.ts\";\n\n/**\n * The compact row of each Meta listing. The backend asks Graph for every field a\n * write or an audit might need (targeting, tracking specs, three status fields),\n * and 100 campaigns or two days of activity passed through whole ran to 55–78 KB.\n * A compact row carries what an agent decides with; `--fields` reaches any other\n * path and `--full` returns the record Graph sent.\n *\n * `effective_status` is the one status kept: it is what Ads Manager shows, and\n * `status`/`configured_status` only restate the toggle it already folds in.\n *\n * Listings print a table by default: keyed JSON repeats every column name on\n * every row, and 100 campaigns stayed near 30 KB even compact. `--output json`\n * returns the same rows in the envelope.\n */\n\ntype MetaRow = Record<string, unknown>;\n\nexport type MetaListKind = \"campaigns\" | \"adsets\" | \"ads\" | \"activities\" | \"audiences\" | \"creatives\";\n\nfunction pick(row: MetaRow, keys: readonly string[]): MetaRow {\n const picked: MetaRow = {};\n for (const key of keys) {\n if (row[key] !== undefined) picked[key] = row[key];\n }\n return picked;\n}\n\n/**\n * An account's campaign list is the widest listing an agent reads (100+ rows), so\n * its row is the narrowest: what a campaign is called, whether it runs and what\n * it spends. Objective, bid strategy and Special Ad Category are one `--fields`\n * away; the creation day is enough to order by, and `--fields created_time` has\n * the timestamp.\n */\nconst CAMPAIGN_COLUMNS = [\"id\", \"name\", \"effective_status\", \"daily_budget\", \"lifetime_budget\", \"created_date\"] as const;\n\n/** Why delivery stops and what Meta suggests: columns only when a row has one. */\nconst DIAGNOSTIC_COLUMNS = [\"issues\", \"suggestions\"] as const;\n\n/**\n * A campaign budgeted on its ad sets has no budget of its own, so its row marks\n * `budget_level: adset` and carries the sum of its active ad sets' budgets\n * (`adSetBudgetColumns`).\n */\nconst ADSET_BUDGET_COLUMNS = [\"budget_level\", \"adset_daily_budget\", \"adset_lifetime_budget\"] as const;\nconst CAMPAIGN_WHEN_PRESENT = [...ADSET_BUDGET_COLUMNS, ...DIAGNOSTIC_COLUMNS] as const;\n\nfunction compactCampaign(row: MetaRow): MetaRow {\n const created = row.created_time;\n return {\n ...pick(row, [\"id\", \"name\", \"effective_status\", \"daily_budget\", \"lifetime_budget\"]),\n ...(typeof created === \"string\" ? { created_date: created.slice(0, 10) } : {}),\n ...adSetBudgetColumns(row),\n ...diagnostics(row),\n };\n}\n\nconst ADSET_KEYS = [\n \"id\",\n \"name\",\n \"campaign_id\",\n \"effective_status\",\n \"optimization_goal\",\n \"billing_event\",\n \"bid_strategy\",\n \"daily_budget\",\n \"lifetime_budget\",\n \"destination_type\",\n // A Dynamic Creative ad set refuses every new ad, which changes the plan before anything is staged.\n \"is_dynamic_creative\",\n] as const;\n\nconst ADSET_COLUMNS = [...ADSET_KEYS, \"learning_stage\", \"end_time\", \"created_time\"] as const;\nconst ADSET_WHEN_PRESENT = [\"optimizes_to\", ...DIAGNOSTIC_COLUMNS] as const;\n\nfunction compactAdSet(row: MetaRow): MetaRow {\n const learning = asRecord(row.learning_stage_info)?.status;\n const optimizes = optimizesTo(row.promoted_object);\n return {\n ...pick(row, ADSET_KEYS),\n ...(typeof learning === \"string\" ? { learning_stage: learning } : {}),\n ...pick(row, [\"end_time\", \"created_time\"]),\n ...(optimizes !== undefined ? { optimizes_to: optimizes } : {}),\n ...diagnostics(row),\n };\n}\n\nconst AD_COLUMNS = [\n \"id\",\n \"name\",\n \"adset_id\",\n \"campaign_id\",\n \"effective_status\",\n \"creative_id\",\n \"issues\",\n \"created_time\",\n] as const;\n\n/** Why an ad is WITH_ISSUES — the one reason to open `issues_info`, in its own words. */\nfunction adIssues(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((entry) => {\n const issue = asRecord(entry);\n const text = issue?.error_summary ?? issue?.error_message;\n return typeof text === \"string\" && text ? [text] : [];\n });\n}\n\n/** Meta's suggestions for a campaign or ad set (`recommendations`), by their titles. */\nfunction suggestions(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((entry) => {\n const recommendation = asRecord(entry);\n const text = recommendation?.title ?? recommendation?.message;\n return typeof text === \"string\" && text ? [text] : [];\n });\n}\n\n/** Why a campaign or ad set cannot deliver, and what Meta suggests — only when Meta says something. */\nfunction diagnostics(row: MetaRow): MetaRow {\n const issues = adIssues(row.issues_info);\n const suggested = suggestions(row.recommendations);\n return {\n ...(issues.length > 0 ? { issues } : {}),\n ...(suggested.length > 0 ? { suggestions: suggested } : {}),\n };\n}\n\n/** Where an ad sends people, the URL parameters it adds and the instant form it opens — read off its creative, which the listing expands. */\nconst AD_WHEN_PRESENT = [\"link\", \"lead_form_id\", \"url_tags\"] as const;\n\nfunction compactAd(row: MetaRow): MetaRow {\n const creative = asRecord(row.creative);\n const issues = adIssues(row.issues_info);\n return {\n ...pick(row, [\"id\", \"name\", \"adset_id\", \"campaign_id\", \"effective_status\"]),\n ...(creative?.id !== undefined ? { creative_id: creative.id } : {}),\n ...(issues.length > 0 ? { issues } : {}),\n ...pick(row, [\"created_time\"]),\n ...adCreativeColumns(creative),\n };\n}\n\nconst ACTIVITY_COLUMNS = [\n \"event_time\",\n \"event_type\",\n \"actor_name\",\n \"object_type\",\n \"object_name\",\n \"object_id\",\n \"change\",\n] as const;\n\nfunction isScalar(value: unknown): value is string | number | null {\n return value === null || typeof value === \"string\" || typeof value === \"number\";\n}\n\n/**\n * `extra_data` is a JSON string whose shape varies by event type and carries most\n * of an activity's bytes (image URLs, whole targeting specs). A status, name,\n * budget or goal change stores its before and after as two plain values — those\n * read as one line; any richer change stays behind `--fields extra_data`.\n */\nexport function activityChange(extraData: unknown): string | undefined {\n if (typeof extraData !== \"string\") return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(extraData);\n } catch {\n return undefined;\n }\n const data = asRecord(parsed);\n // An absent old_value is one this read did not observe, not an unset one — only `null` means \"none\".\n if (!data || !(\"new_value\" in data) || !(\"old_value\" in data)) return undefined;\n const { old_value: before, new_value: after } = data;\n if (!isScalar(before) || !isScalar(after)) return undefined;\n const show = (value: string | number | null) => (value === null ? \"(none)\" : String(value));\n return `${show(before)} → ${show(after)}`;\n}\n\nfunction compactActivity(row: MetaRow): MetaRow {\n const change = activityChange(row.extra_data);\n return {\n ...pick(row, [\"event_time\", \"event_type\", \"actor_name\", \"object_type\", \"object_name\", \"object_id\"]),\n ...(change !== undefined ? { change } : {}),\n };\n}\n\n/**\n * An account can hold hundreds of audiences (one held 414, ~424 KB printed), and a\n * lookup is usually for one of them and its lookalikes. The row says what the audience\n * is, how big (or that Meta did not say), and — only when it is so — that it is still\n * processing, why it cannot be used and which audience a lookalike was built from. Its\n * rule and data source are one `--fields` away.\n */\nconst AUDIENCE_COLUMNS = [\"id\", \"name\", \"subtype\", \"size_min\", \"size_max\", \"retention_days\", \"updated_date\"] as const;\nconst AUDIENCE_WHEN_PRESENT = [\"size\", \"status\", \"delivery\", \"seed_id\"] as const;\n\nfunction compactAudience(row: MetaRow): MetaRow {\n const updated = row.time_updated;\n const delivery = asRecord(row.delivery_status);\n const origin = asRecord(row.lookalike_spec)?.origin;\n const seed = Array.isArray(origin) ? asRecord(origin[0])?.id : undefined;\n return {\n ...pick(row, [\"id\", \"name\", \"subtype\"]),\n ...audienceColumns(row),\n ...pick(row, [\"retention_days\"]),\n ...(typeof updated === \"number\" ? { updated_date: new Date(updated * 1000).toISOString().slice(0, 10) } : {}),\n ...(delivery && delivery.code !== 200 && typeof delivery.description === \"string\"\n ? { delivery: delivery.description }\n : {}),\n ...(seed !== undefined ? { seed_id: seed } : {}),\n };\n}\n\n/**\n * A creative's copy, destination and assets live in one of three places — the\n * top-level fields Meta derives, `object_story_spec`, or a dynamic creative's\n * `asset_feed_spec`, a carousel's cards in `link_data.child_attachments` — next to specs that carry most of its bytes and none of its\n * meaning (`degrees_of_freedom_spec`, per-placement rules, signed image URLs). The\n * row reads each value from wherever the creative keeps it: one value as itself,\n * several (a dynamic creative's variants) as a list.\n */\nconst CREATIVE_COLUMNS = [\n \"id\",\n \"name\",\n \"status\",\n \"object_type\",\n \"dynamic\",\n \"body\",\n \"title\",\n \"description\",\n \"link\",\n \"cta\",\n \"url_tags\",\n \"image_hash\",\n \"video_id\",\n \"page_id\",\n \"instagram_user_id\",\n \"effective_object_story_id\",\n] as const;\n\nfunction compactCreative(row: MetaRow): MetaRow {\n const story = asRecord(row.object_story_spec);\n const link = asRecord(story?.link_data);\n const video = asRecord(story?.video_data);\n const feed = asRecord(row.asset_feed_spec);\n // A carousel's cards: each one's headline, description, destination and media.\n const cards = link?.child_attachments;\n const derived: MetaRow = {\n dynamic: feed ? (typeof feed.optimization_type === \"string\" ? feed.optimization_type : \"ASSET_FEED\") : undefined,\n body: oneOrMany(row.body, link?.message, video?.message, texts(feed?.bodies, \"text\")),\n title: oneOrMany(row.title, link?.name, video?.title, texts(feed?.titles, \"text\"), texts(cards, \"name\")),\n description: oneOrMany(\n link?.description,\n video?.link_description,\n texts(feed?.descriptions, \"text\"),\n texts(cards, \"description\"),\n ),\n link: creativeLink(row),\n cta: oneOrMany(row.call_to_action_type, feed?.call_to_action_types),\n url_tags: row.url_tags,\n image_hash: oneOrMany(\n row.image_hash,\n link?.image_hash,\n video?.image_hash,\n texts(feed?.images, \"hash\"),\n texts(cards, \"image_hash\"),\n ),\n video_id: oneOrMany(row.video_id, video?.video_id, texts(feed?.videos, \"video_id\"), texts(cards, \"video_id\")),\n page_id: story?.page_id,\n instagram_user_id: row.instagram_user_id ?? story?.instagram_user_id,\n effective_object_story_id: row.effective_object_story_id,\n };\n const compact: MetaRow = pick(row, [\"id\", \"name\", \"status\", \"object_type\"]);\n for (const [key, value] of Object.entries(derived)) if (value !== undefined) compact[key] = value;\n return compact;\n}\n\n/**\n * The unit a listing's budgets are in, said once rather than as a column (a\n * 100-campaign table stays small). Meta lists money in the account currency's\n * smallest unit and Baker passes it through unchanged (published reports read\n * it that way), while every money flag takes whole currency. An agent that once\n * took a listed \"8000\" for the flag's unit staged 10,000 EUR a day instead of 100.\n */\nexport function budgetUnitHints(rows: ReadonlyArray<Record<string, unknown>>): string[] {\n const listed = rows\n .flatMap((row) => [row.daily_budget, row.lifetime_budget, row.adset_daily_budget, row.adset_lifetime_budget])\n .map(Number)\n .find((amount) => Number.isFinite(amount) && amount > 0);\n if (listed === undefined) return [];\n const whole = listed / 100;\n return [\n `Budgets here are in the account currency's smallest unit, as Meta sends them: daily_budget ${listed} is ${whole} in EUR or USD (currencies without cents, such as JPY, are not divided). Money flags take whole currency: --daily-budget ${whole}, never ${listed}.`,\n ];\n}\n\n/** Past this many rows a listing is an account read whole, not an answer to a question. */\nconst LARGE_LISTING_ROWS = 100;\n\n/**\n * A large account lists ad sets and ads by the thousand — one listed 1,000 ad\n * sets, 1.4 MB as Meta sent them. Even compact, that table is more than an agent\n * reads to decide, so a long listing says how to ask for the part it needs.\n */\nexport function largeListingHints(kind: \"adsets\" | \"ads\", rowCount: number): string[] {\n if (rowCount < LARGE_LISTING_ROWS) return [];\n const parent = kind === \"ads\" ? \"--campaign-id <id> or --adset-id <id>\" : \"--campaign-id <id>\";\n return [\n `${rowCount} ${NOUNS[kind]} listed. On a large account, ask for the part you need: ${parent} (from baker ads meta campaigns), --effective-status ACTIVE or PAUSED, --name-contains <text>, or --ids <id>,<id>.`,\n ];\n}\n\nconst PROJECTIONS: Record<MetaListKind, CompactProjection<MetaRow>> = {\n campaigns: { row: compactCampaign, columns: CAMPAIGN_COLUMNS, whenPresent: CAMPAIGN_WHEN_PRESENT },\n adsets: { row: compactAdSet, columns: ADSET_COLUMNS, whenPresent: ADSET_WHEN_PRESENT },\n ads: { row: compactAd, columns: AD_COLUMNS, whenPresent: AD_WHEN_PRESENT },\n activities: { row: compactActivity, columns: ACTIVITY_COLUMNS },\n audiences: { row: compactAudience, columns: AUDIENCE_COLUMNS, whenPresent: AUDIENCE_WHEN_PRESENT },\n creatives: { row: compactCreative, columns: CREATIVE_COLUMNS },\n};\n\nexport function shapeMetaListRows(kind: MetaListKind, rows: MetaRow[], args: Record<string, unknown>): ShapedRows {\n const shaped = withheldSizeHint(kind, shapeListRows(rows, args, PROJECTIONS[kind]));\n if (!(kind in COMPACT_SOURCES) || !shaped.hints?.some((hint) => hint.startsWith(\"--fields matched nothing\"))) {\n return shaped;\n }\n // Meta was asked for the named fields only, so the rows cannot show the ones a typo missed.\n return {\n ...shaped,\n hints: [\n ...shaped.hints,\n `Only the fields --fields names are read from Meta, so these rows list no others: --full --limit 1 shows every field ${NOUNS[kind]} carry.`,\n ],\n };\n}\n\n/** A withheld size reads as Meta's placeholder once, not as a number on every row. */\nfunction withheldSizeHint(kind: MetaListKind, shaped: ShapedRows): ShapedRows {\n if (kind !== \"audiences\" || !shaped.rows.some((row) => row.size === AUDIENCE_SIZE_NOT_REPORTED)) return shaped;\n return { ...shaped, hints: [...(shaped.hints ?? []), AUDIENCE_SIZE_NOTE] };\n}\n\ntype ListedKind = \"campaigns\" | \"adsets\" | \"ads\" | \"audiences\";\n\n/** The fields Meta is asked for to build each compact row (and the hints read beside it). */\nconst COMPACT_SOURCES: Record<ListedKind, readonly string[]> = {\n campaigns: [\n \"id\",\n \"name\",\n \"effective_status\",\n \"daily_budget\",\n \"lifetime_budget\",\n \"created_time\",\n \"issues_info\",\n \"recommendations\",\n \"advantage_state_info\",\n \"adsets\",\n ],\n adsets: [\n ...ADSET_KEYS,\n \"learning_stage_info\",\n \"end_time\",\n \"created_time\",\n \"promoted_object\",\n \"issues_info\",\n \"recommendations\",\n ],\n ads: [\"id\", \"name\", \"adset_id\", \"campaign_id\", \"effective_status\", \"creative\", \"issues_info\", \"created_time\"],\n audiences: [\n \"id\",\n \"name\",\n \"subtype\",\n \"approximate_count_lower_bound\",\n \"approximate_count_upper_bound\",\n \"retention_days\",\n \"time_updated\",\n \"delivery_status\",\n \"operation_status\",\n \"lookalike_spec\",\n ],\n};\n\n/** The fields a listing's own hints read, asked for beside any `--fields`. */\nconst HINT_SOURCES: Partial<Record<ListedKind, readonly string[]>> = {\n campaigns: [\"advantage_state_info\"],\n};\n\n/** A compact column `--fields` may name, and the field Meta keeps it in. */\nconst DERIVED_FROM: Record<string, string> = {\n created_date: \"created_time\",\n updated_date: \"time_updated\",\n learning_stage: \"learning_stage_info\",\n issues: \"issues_info\",\n suggestions: \"recommendations\",\n creative_id: \"creative\",\n link: \"creative\",\n lead_form_id: \"creative\",\n url_tags: \"creative\",\n optimizes_to: \"promoted_object\",\n adset_daily_budget: \"adsets\",\n adset_lifetime_budget: \"adsets\",\n budget_level: \"adsets\",\n size_min: \"approximate_count_lower_bound\",\n size_max: \"approximate_count_upper_bound\",\n delivery: \"delivery_status\",\n seed_id: \"lookalike_spec\",\n};\n\n/** Columns only an audience row derives: campaigns, ad sets and ads keep their own `status`. */\nconst DERIVED_FROM_KIND: Partial<Record<ListedKind, Record<string, string>>> = {\n audiences: {\n size: \"approximate_count_lower_bound,approximate_count_upper_bound\",\n status: \"operation_status\",\n },\n};\n\n/**\n * What a listing asks the server to read from Meta: the source of the compact row,\n * or of each `--fields` path (its top-level key), and everything under `--full`.\n * The server read every field it knows of — an account's ads with their creatives\n * and specs ran to 1 MB and past 60 s — for a table that prints a handful.\n */\nexport function metaListFields(kind: ListedKind, args: Record<string, unknown>): string | undefined {\n const paths =\n typeof args.fields === \"string\"\n ? args.fields\n .split(\",\")\n .map((path) => path.trim())\n .filter(Boolean)\n : [];\n if (paths.length > 0) {\n const tops = paths.map((path) => {\n const top = path.split(\".\")[0] ?? path;\n return DERIVED_FROM_KIND[kind]?.[top] ?? DERIVED_FROM[top] ?? top;\n });\n return [...new Set([\"id\", ...tops, ...(HINT_SOURCES[kind] ?? [])])].join(\",\");\n }\n if (args.full) return undefined;\n return COMPACT_SOURCES[kind].join(\",\");\n}\n\n/** Read the named rows by id, matched by Meta — whatever their status, unless one is named. */\nexport const IDS_ARG = {\n type: \"string\",\n description:\n \"Comma-separated ids: only these rows, whatever their status (unless --effective-status names one). Start here when you have the ids: --ids 120250141735400031,120250141735400032\",\n} as const;\n\nconst NOUNS: Record<MetaListKind, string> = {\n campaigns: \"campaigns\",\n adsets: \"ad sets\",\n ads: \"ads\",\n activities: \"activities\",\n audiences: \"audiences\",\n creatives: \"creatives\",\n};\n\n/**\n * A table of no rows prints nothing at all, which reads as a failed call — so an empty\n * listing says so, and says why when a status filter may be hiding rows.\n */\nexport function writeMetaListRows(kind: MetaListKind, shaped: ShapedRows, format: string, hints: string[] = []): void {\n if (format === \"md\" && shaped.rows.length === 0) {\n process.stdout.write(`${hints.length > 0 ? hints.join(\"\\n\") : `No ${NOUNS[kind]} matched.`}\\n`);\n return;\n }\n writeAdsOutput(shaped.rows, format, shaped.fields, [...hints, ...(shaped.hints ?? [])]);\n}\n\n/** The projection flags every Meta listing shares, worded once for help and `baker schema`. */\nexport const META_LIST_SHAPE_ARGS = {\n fields: {\n type: \"string\",\n description: \"CSV of dotted paths to return instead of the compact row, e.g. id,name,targeting.geo_locations\",\n },\n full: { type: \"boolean\", description: \"Return every field Meta sent (targeting, tracking specs, raw extra_data)\" },\n output: {\n type: \"string\",\n description: \"md|json|csv|jsonl — md (default) prints a table; json returns the rows in the { ok, data } envelope\",\n default: \"md\",\n },\n} as const;\n\ninterface ListArgDef {\n type: string;\n description?: string;\n default?: unknown;\n}\n\n/**\n * `baker schema ads.meta.<list>`, read off the same arg defs the command parses,\n * so the introspection an agent checks before a call cannot promise a flag the\n * command refuses — `--full` on `adsets` was guessed three times in one Session.\n */\nexport function registerMetaListSchema(\n kind: MetaListKind,\n description: string,\n args: Record<string, ListArgDef>,\n alsoReads: readonly CommandRoute[] = [],\n): void {\n registerSchema({\n command: `ads.meta.${kind}`,\n // Read live from Meta, for the account named or the only one.\n routes: [`GET /api/ads/meta/${kind}`, \"GET /api/ads/meta/accounts\", ...alsoReads],\n effect: \"read_live\",\n description,\n args: Object.fromEntries(\n Object.entries(args).map(([name, def]) => [\n name,\n {\n type: def.type,\n description: def.description ?? \"\",\n required: false,\n ...(def.default !== undefined ? { default: def.default } : {}),\n },\n ]),\n ),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAS,KAAK,KAAc,MAAkC;AAC5D,QAAM,SAAkB,CAAC;AACzB,aAAW,OAAO,MAAM;AACtB,QAAI,IAAI,GAAG,MAAM,OAAW,QAAO,GAAG,IAAI,IAAI,GAAG;AAAA,EACnD;AACA,SAAO;AACT;AASA,IAAM,mBAAmB,CAAC,MAAM,QAAQ,oBAAoB,gBAAgB,mBAAmB,cAAc;AAG7G,IAAM,qBAAqB,CAAC,UAAU,aAAa;AAOnD,IAAM,uBAAuB,CAAC,gBAAgB,sBAAsB,uBAAuB;AAC3F,IAAM,wBAAwB,CAAC,GAAG,sBAAsB,GAAG,kBAAkB;AAE7E,SAAS,gBAAgB,KAAuB;AAC9C,QAAM,UAAU,IAAI;AACpB,SAAO;AAAA,IACL,GAAG,KAAK,KAAK,CAAC,MAAM,QAAQ,oBAAoB,gBAAgB,iBAAiB,CAAC;AAAA,IAClF,GAAI,OAAO,YAAY,WAAW,EAAE,cAAc,QAAQ,MAAM,GAAG,EAAE,EAAE,IAAI,CAAC;AAAA,IAC5E,GAAG,mBAAmB,GAAG;AAAA,IACzB,GAAG,YAAY,GAAG;AAAA,EACpB;AACF;AAEA,IAAM,aAAa;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACF;AAEA,IAAM,gBAAgB,CAAC,GAAG,YAAY,kBAAkB,YA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AAe,OAAO,MAAM,QAAQ,OAAO,QAAQ,CAAC,GAAG,OAAO,GAAI,OAAO,SAAS,CAAC,CAAE,CAAC;AACxF;AAGO,IAAM,uBAAuB;AAAA,EAClC,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,aAAa;AAAA,EACf;AAAA,EACA,MAAM,EAAE,MAAM,WAAW,aAAa,2EAA2E;AAAA,EACjH,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,EACX;AACF;AAaO,SAAS,uBACd,MACA,aACA,MACA,YAAqC,CAAC,GAChC;AACN,iBAAe;AAAA,IACb,SAAS,YAAY,IAAI;AAAA;AAAA,IAEzB,QAAQ,CAAC,qBAAqB,IAAI,IAAI,8BAA8B,GAAG,SAAS;AAAA,IAChF,QAAQ;AAAA,IACR;AAAA,IACA,MAAM,OAAO;AAAA,MACX,OAAO,QAAQ,IAAI,EAAE,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM;AAAA,QACxC;AAAA,QACA;AAAA,UACE,MAAM,IAAI;AAAA,UACV,aAAa,IAAI,eAAe;AAAA,UAChC,UAAU;AAAA,UACV,GAAI,IAAI,YAAY,SAAY,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;AAAA,QAC9D;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../api/src/ads-meta/listColumns.ts"],"sourcesContent":["/**\n * The columns a Meta listing reads off the related object the backend expands in\n * the same Graph request — a campaign's ad sets, an ad set's promoted object, an\n * ad's creative. The CLI's compact rows and the channel engine's live lists both\n * print them, so an agent in either answers the question in one read.\n */\n\ntype Row = Record<string, unknown>;\n\nfunction record(value: unknown): Row | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Row) : undefined;\n}\n\nexport function texts(value: unknown, key: string): unknown[] {\n return Array.isArray(value) ? value.map((entry) => record(entry)?.[key]) : [];\n}\n\n/** The distinct non-empty strings among the candidates: none, one as itself, or several as a list. */\nexport function oneOrMany(...candidates: unknown[]): string | string[] | undefined {\n const values = [...new Set(candidates.flat().filter((v): v is string => typeof v === \"string\" && v !== \"\"))];\n if (values.length === 0) return undefined;\n return values.length === 1 ? values[0] : values;\n}\n\n/**\n * A campaign budgeted on its ad sets has no budget of its own. Its row says so\n * (`budget_level: adset`) and carries the sum of its ACTIVE ad sets' budgets, in\n * the same unit as `daily_budget` — `0` when every budgeted ad set is paused, so\n * a campaign about to be reactivated never reads as one whose budget is unknown.\n */\nexport function adSetBudgetColumns(campaign: Row): Row {\n if (campaign.daily_budget !== undefined || campaign.lifetime_budget !== undefined) return {};\n const adsets = record(campaign.adsets)?.data;\n if (!Array.isArray(adsets) || adsets.length === 0) return {};\n const budgets = adsets.map(record);\n const column = (key: string) => {\n const amounts = budgets.map((adset) => ({ active: adset?.status === \"ACTIVE\", amount: Number(adset?.[key]) }));\n if (!amounts.some(({ amount }) => Number.isFinite(amount) && amount > 0)) return undefined;\n return String(amounts.reduce((total, { active, amount }) => (active && amount > 0 ? total + amount : total), 0));\n };\n const daily = column(\"daily_budget\");\n const lifetime = column(\"lifetime_budget\");\n return {\n budget_level: \"adset\",\n ...(daily !== undefined ? { adset_daily_budget: daily } : {}),\n ...(lifetime !== undefined ? { adset_lifetime_budget: lifetime } : {}),\n };\n}\n\n/** The conversion a conversion-optimized ad set bids for — its optimization_goal says nothing without it. */\nexport function optimizesTo(promotedObject: unknown): string | undefined {\n const promoted = record(promotedObject);\n if (!promoted) return undefined;\n if (typeof promoted.custom_conversion_id === \"string\") return `custom conversion ${promoted.custom_conversion_id}`;\n const event = promoted.custom_event_str ?? promoted.custom_event_type;\n return typeof event === \"string\" && event ? event : undefined;\n}\n\n/** A creative's destination, from wherever it keeps it: one URL as itself, a dynamic creative's or a carousel's several as a list. */\nexport function creativeLink(creative: Row): string | string[] | undefined {\n const story = record(creative.object_story_spec);\n const link = record(story?.link_data);\n return oneOrMany(\n creative.link_url,\n link?.link,\n record(record(record(story?.video_data)?.call_to_action)?.value)?.link,\n texts(record(creative.asset_feed_spec)?.link_urls, \"website_url\"),\n texts(link?.child_attachments, \"link\"),\n );\n}\n\nfunction formOf(source: unknown): unknown {\n return record(record(record(source)?.call_to_action)?.value)?.lead_gen_form_id;\n}\n\n/**\n * The instant form a creative's button opens, from every place Meta keeps it: a\n * video's or an image's button, a carousel's cards, a dynamic creative's buttons.\n * Meta allows one form per creative, so several is a list only to show it.\n */\nexport function creativeLeadForm(creative: Row): string | string[] | undefined {\n const story = record(creative.object_story_spec);\n const link = record(story?.link_data);\n const feedButtons = record(creative.asset_feed_spec)?.call_to_actions;\n return oneOrMany(\n formOf(story?.video_data),\n formOf(link),\n Array.isArray(link?.child_attachments) ? link.child_attachments.map(formOf) : [],\n Array.isArray(feedButtons) ? feedButtons.map((button) => record(record(button)?.value)?.lead_gen_form_id) : [],\n );\n}\n\n/** Where an ad sends people, the URL parameters it adds and the instant form it opens, read off its expanded creative. */\nexport function adCreativeColumns(creativeValue: unknown): Row {\n const creative = record(creativeValue);\n if (!creative) return {};\n const link = creativeLink(creative);\n const leadForm = creativeLeadForm(creative);\n return {\n ...(link !== undefined ? { link } : {}),\n ...(leadForm !== undefined ? { lead_form_id: leadForm } : {}),\n ...(typeof creative.url_tags === \"string\" && creative.url_tags ? { url_tags: creative.url_tags } : {}),\n };\n}\n\n/**\n * Meta answers `1000`–`1000` (or `-1`, its documented \"inactive lookalike\") when it\n * withholds an audience's size, not when the audience is small: live on\n * act_1342210013621203 (2026-11-11) an empty customer list read 1000–1000 while a\n * 20-person website audience read 20–20.\n */\nexport function metaSizeWithheld(lower: unknown, upper: unknown): boolean {\n return lower === upper && (lower === 1000 || lower === -1);\n}\n\nexport const AUDIENCE_SIZE_NOT_REPORTED = \"not reported by Meta\";\n\nexport const AUDIENCE_SIZE_NOTE =\n \"size: not reported by Meta — Meta answered 1000–1000 (or -1), a placeholder it gives when it withholds a size, not a count: the audience may hold millions or nobody. Judge it by its delivery column (Meta says there when it is too small to use), by reach in insights or by Ads Manager, never as small.\";\n\n/**\n * `operation_status` codes that say nothing about what can be done with the audience\n * next: none reported, Normal, and the two notices about disuse (100 expiring, 450\n * out of date — the audience still delivers). Every other code is the audience\n * still being built (300 Updating, 414 being replaced, 441 populating) or a problem.\n */\nconst SETTLED_OPERATION_CODES: ReadonlySet<unknown> = new Set([0, 100, 200, 450]);\n\n/**\n * An audience's size and the state of its last operation, as a listing prints them:\n * `size_min` / `size_max` when Meta reported a size, `size` when it withheld one, and\n * `status` only while the audience is still processing or Meta reports a problem.\n */\nexport function audienceColumns(audience: Row): Row {\n const lower = audience.approximate_count_lower_bound;\n const upper = audience.approximate_count_upper_bound;\n const operation = record(audience.operation_status);\n return {\n ...(metaSizeWithheld(lower, upper)\n ? { size: AUDIENCE_SIZE_NOT_REPORTED }\n : {\n ...(lower !== undefined ? { size_min: lower } : {}),\n ...(upper !== undefined ? { size_max: upper } : {}),\n }),\n ...(operation && !SETTLED_OPERATION_CODES.has(operation.code) && typeof operation.description === \"string\"\n ? { status: operation.description }\n : {}),\n };\n}\n"],"mappings":";AASA,SAAS,OAAO,OAAiC;AAC/C,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAAK,QAAgB;AACjG;AAEO,SAAS,MAAM,OAAgB,KAAwB;AAC5D,SAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,IAAI,CAAC,UAAU,OAAO,KAAK,IAAI,GAAG,CAAC,IAAI,CAAC;AAC9E;AAGO,SAAS,aAAa,YAAsD;AACjF,QAAM,SAAS,CAAC,GAAG,IAAI,IAAI,WAAW,KAAK,EAAE,OAAO,CAAC,MAAmB,OAAO,MAAM,YAAY,MAAM,EAAE,CAAC,CAAC;AAC3G,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,SAAO,OAAO,WAAW,IAAI,OAAO,CAAC,IAAI;AAC3C;AAQO,SAAS,mBAA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M,qBACX;AAQF,IAAM,0BAAgD,oBAAI,IAAI,CAAC,GAAG,KAAK,KAAK,GAAG,CAAC;AAOzE,SAAS,gBAAgB,UAAoB;AAClD,QAAM,QAAQ,SAAS;AACvB,QAAM,QAAQ,SAAS;AACvB,QAAM,YAAY,OAAO,SAAS,gBAAgB;AAClD,SAAO;AAAA,IACL,GAAI,iBAAiB,OAAO,KAAK,IAC7B,EAAE,MAAM,2BAA2B,IACnC;AAAA,MACE,GAAI,UAAU,SAAY,EAAE,UAAU,MAAM,IAAI,CAAC;AAAA,MACjD,GAAI,UAAU,SAAY,EAAE,UAAU,MAAM,IAAI,CAAC;AAAA,IACnD;AAAA,IACJ,GAAI,aAAa,CAAC,wBAAwB,IAAI,UAAU,IAAI,KAAK,OAAO,UAAU,gBAAgB,WAC9F,EAAE,QAAQ,UAAU,YAAY,IAChC,CAAC;AAAA,EACP;AACF;","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;A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