@koda-sl/baker-cli 0.883.0 → 0.885.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +6 -1
  2. package/dist/{account-assets-FJFPB7KD.js → account-assets-Q2O3FRUE.js} +6 -6
  3. package/dist/{account-level-CB6I4X5W.js → account-level-NBEQ6R7X.js} +3 -3
  4. package/dist/{account-reads-TSDWJ3A2.js → account-reads-7DPRPWBK.js} +3 -2
  5. package/dist/{account-reads-TSDWJ3A2.js.map → account-reads-7DPRPWBK.js.map} +1 -1
  6. package/dist/{ads-ZSHBQHNK.js → ads-4QBIYBPH.js} +3 -3
  7. package/dist/{ads-G3N76HWA.js → ads-HKPBNXWT.js} +10 -10
  8. package/dist/{adsets-2HV6TJJP.js → adsets-IBLZP6EM.js} +9 -9
  9. package/dist/{analytics-6TNLZ4LA.js → analytics-E5OPCERI.js} +6 -5
  10. package/dist/{analytics-6TNLZ4LA.js.map → analytics-E5OPCERI.js.map} +1 -1
  11. package/dist/{asset-writes-ZOVD5O5X.js → asset-writes-NTEJDVVM.js} +3 -3
  12. package/dist/{audience-writes-36E6ECON.js → audience-writes-DJHKIJP7.js} +2 -2
  13. package/dist/{audiences-65JSGH4L.js → audiences-7TGXZS3M.js} +6 -6
  14. package/dist/{campaigns-PP3MFPJR.js → campaigns-VD7UOTRV.js} +9 -9
  15. package/dist/{catalogs-UYYPZRFW.js → catalogs-H2T4Z6AS.js} +2 -2
  16. package/dist/{changes-7WLOTKVE.js → changes-FQ2NWBJQ.js} +3 -2
  17. package/dist/{changes-7WLOTKVE.js.map → changes-FQ2NWBJQ.js.map} +1 -1
  18. package/dist/{chunk-Z65I6WS6.js → chunk-DX4SRYED.js} +13 -5
  19. package/dist/chunk-DX4SRYED.js.map +1 -0
  20. package/dist/{chunk-J464JWY7.js → chunk-ENTB4ILS.js} +8 -4
  21. package/dist/chunk-ENTB4ILS.js.map +1 -0
  22. package/dist/{chunk-JOQBRK4E.js → chunk-FRWCTFTP.js} +9 -4
  23. package/dist/chunk-FRWCTFTP.js.map +1 -0
  24. package/dist/{chunk-BRHYK4HQ.js → chunk-G7Q43JEZ.js} +5 -4
  25. package/dist/{chunk-BRHYK4HQ.js.map → chunk-G7Q43JEZ.js.map} +1 -1
  26. package/dist/{chunk-BX5AAH7T.js → chunk-IDLSLJIM.js} +4 -2
  27. package/dist/{chunk-BX5AAH7T.js.map → chunk-IDLSLJIM.js.map} +1 -1
  28. package/dist/{chunk-ZGYIG6OM.js → chunk-LUF2VYOK.js} +2 -2
  29. package/dist/chunk-LVLAFUXQ.js +37 -0
  30. package/dist/chunk-LVLAFUXQ.js.map +1 -0
  31. package/dist/{chunk-3F6AXSPB.js → chunk-ZJUUAZKY.js} +2 -2
  32. package/dist/cli.js +6 -6
  33. package/dist/{config-UR3ZKS25.js → config-Z52BRC3M.js} +3 -2
  34. package/dist/{config-UR3ZKS25.js.map → config-Z52BRC3M.js.map} +1 -1
  35. package/dist/{conversion-upload-command-CWMZEFCT.js → conversion-upload-command-ZZ5JYMBL.js} +7 -4
  36. package/dist/conversion-upload-command-ZZ5JYMBL.js.map +1 -0
  37. package/dist/{copy-writes-TEJRR2W2.js → copy-writes-FGMJ7N75.js} +3 -3
  38. package/dist/{creatives-ZYY5OF5U.js → creatives-67CDPYL7.js} +4 -4
  39. package/dist/{custom-conversions-YQPOB2IR.js → custom-conversions-RZB2622Q.js} +4 -4
  40. package/dist/{draft-KMRFGWIO.js → draft-3L5UZ3JP.js} +7 -4
  41. package/dist/draft-3L5UZ3JP.js.map +1 -0
  42. package/dist/{draft-XWJF772C.js → draft-CZEMQHTX.js} +3 -2
  43. package/dist/{draft-XWJF772C.js.map → draft-CZEMQHTX.js.map} +1 -1
  44. package/dist/{draft-5H6MKAKW.js → draft-FOHLBTWV.js} +3 -2
  45. package/dist/{draft-5H6MKAKW.js.map → draft-FOHLBTWV.js.map} +1 -1
  46. package/dist/{draft-OHAOBGVP.js → draft-JPWMFZNZ.js} +243 -8
  47. package/dist/draft-JPWMFZNZ.js.map +1 -0
  48. package/dist/{forecast-WTVRSFFA.js → forecast-SXZBIHFB.js} +3 -2
  49. package/dist/{forecast-WTVRSFFA.js.map → forecast-SXZBIHFB.js.map} +1 -1
  50. package/dist/{ga4-K6ARTEPX.js → ga4-6J3IMDSU.js} +12 -12
  51. package/dist/{google-N3GW4MDV.js → google-F77XV4ZC.js} +59 -40
  52. package/dist/google-F77XV4ZC.js.map +1 -0
  53. package/dist/{hubspot-BG4BI3RU.js → hubspot-24MLH5N7.js} +2 -2
  54. package/dist/{instant-experiences-YXH2AHFI.js → instant-experiences-MF2X374W.js} +2 -2
  55. package/dist/{leads-IGOXMIEW.js → leads-IBXGNXTX.js} +2 -2
  56. package/dist/{media-QOGVG6CU.js → media-YPVGQ535.js} +3 -3
  57. package/dist/{meta-RJH5COPE.js → meta-ZQXCUKHQ.js} +30 -30
  58. package/dist/{page-photos-P2XMKTVF.js → page-photos-BEAMTVP5.js} +2 -2
  59. package/dist/{plan-C5U4U55M.js → plan-JVD6BMEO.js} +3 -2
  60. package/dist/{plan-C5U4U55M.js.map → plan-JVD6BMEO.js.map} +1 -1
  61. package/dist/{read-UXFNPEQ5.js → read-VI63RNL6.js} +3 -2
  62. package/dist/{read-UXFNPEQ5.js.map → read-VI63RNL6.js.map} +1 -1
  63. package/dist/{rule-writes-MSMVQDQO.js → rule-writes-CVP6CH2R.js} +2 -2
  64. package/dist/{rules-UEKJOZTV.js → rules-LZ36YNG3.js} +7 -7
  65. package/dist/{search-terms-WKE47TW5.js → search-terms-SWRRTKBV.js} +3 -2
  66. package/dist/{search-terms-WKE47TW5.js.map → search-terms-SWRRTKBV.js.map} +1 -1
  67. package/dist/{sends-5UCPQZ7F.js → sends-PEQJOPRM.js} +19 -4
  68. package/dist/sends-PEQJOPRM.js.map +1 -0
  69. package/dist/{shopify-NJFARTN3.js → shopify-IRHELCGF.js} +3 -2
  70. package/dist/{shopify-NJFARTN3.js.map → shopify-IRHELCGF.js.map} +1 -1
  71. package/dist/{sources-XYKENWZF.js → sources-CACBM65R.js} +38 -17
  72. package/dist/sources-CACBM65R.js.map +1 -0
  73. package/dist/{studies-TIF7PYEB.js → studies-Y6PGWT66.js} +5 -5
  74. package/dist/{study-writes-RGKBOOJ6.js → study-writes-6F6O6N4E.js} +2 -2
  75. package/dist/{tag-manager-5Q5MHQPL.js → tag-manager-QO6VW57E.js} +10 -10
  76. package/dist/{targeting-YWOOD6YL.js → targeting-FRMVSXXL.js} +2 -2
  77. package/dist/{themes-LWG3LX7O.js → themes-GMZOWC3X.js} +3 -2
  78. package/dist/{themes-LWG3LX7O.js.map → themes-GMZOWC3X.js.map} +1 -1
  79. package/dist/{write-commands-REUTFNJ3.js → write-commands-3BMPDY3K.js} +4 -4
  80. package/dist/{write-commands-IAMIUSK4.js → write-commands-GRBE5V34.js} +3 -2
  81. package/dist/{write-commands-IAMIUSK4.js.map → write-commands-GRBE5V34.js.map} +1 -1
  82. package/dist/{write-commands-JXP2NHRY.js → write-commands-MZUVJBGO.js} +3 -2
  83. package/dist/{write-commands-JXP2NHRY.js.map → write-commands-MZUVJBGO.js.map} +1 -1
  84. package/package.json +1 -1
  85. package/dist/chunk-J464JWY7.js.map +0 -1
  86. package/dist/chunk-JOQBRK4E.js.map +0 -1
  87. package/dist/chunk-Z65I6WS6.js.map +0 -1
  88. package/dist/conversion-upload-command-CWMZEFCT.js.map +0 -1
  89. package/dist/draft-KMRFGWIO.js.map +0 -1
  90. package/dist/draft-OHAOBGVP.js.map +0 -1
  91. package/dist/google-N3GW4MDV.js.map +0 -1
  92. package/dist/sends-5UCPQZ7F.js.map +0 -1
  93. package/dist/sources-XYKENWZF.js.map +0 -1
  94. /package/dist/{account-assets-FJFPB7KD.js.map → account-assets-Q2O3FRUE.js.map} +0 -0
  95. /package/dist/{account-level-CB6I4X5W.js.map → account-level-NBEQ6R7X.js.map} +0 -0
  96. /package/dist/{ads-ZSHBQHNK.js.map → ads-4QBIYBPH.js.map} +0 -0
  97. /package/dist/{ads-G3N76HWA.js.map → ads-HKPBNXWT.js.map} +0 -0
  98. /package/dist/{adsets-2HV6TJJP.js.map → adsets-IBLZP6EM.js.map} +0 -0
  99. /package/dist/{asset-writes-ZOVD5O5X.js.map → asset-writes-NTEJDVVM.js.map} +0 -0
  100. /package/dist/{audience-writes-36E6ECON.js.map → audience-writes-DJHKIJP7.js.map} +0 -0
  101. /package/dist/{audiences-65JSGH4L.js.map → audiences-7TGXZS3M.js.map} +0 -0
  102. /package/dist/{campaigns-PP3MFPJR.js.map → campaigns-VD7UOTRV.js.map} +0 -0
  103. /package/dist/{catalogs-UYYPZRFW.js.map → catalogs-H2T4Z6AS.js.map} +0 -0
  104. /package/dist/{chunk-ZGYIG6OM.js.map → chunk-LUF2VYOK.js.map} +0 -0
  105. /package/dist/{chunk-3F6AXSPB.js.map → chunk-ZJUUAZKY.js.map} +0 -0
  106. /package/dist/{copy-writes-TEJRR2W2.js.map → copy-writes-FGMJ7N75.js.map} +0 -0
  107. /package/dist/{creatives-ZYY5OF5U.js.map → creatives-67CDPYL7.js.map} +0 -0
  108. /package/dist/{custom-conversions-YQPOB2IR.js.map → custom-conversions-RZB2622Q.js.map} +0 -0
  109. /package/dist/{ga4-K6ARTEPX.js.map → ga4-6J3IMDSU.js.map} +0 -0
  110. /package/dist/{hubspot-BG4BI3RU.js.map → hubspot-24MLH5N7.js.map} +0 -0
  111. /package/dist/{instant-experiences-YXH2AHFI.js.map → instant-experiences-MF2X374W.js.map} +0 -0
  112. /package/dist/{leads-IGOXMIEW.js.map → leads-IBXGNXTX.js.map} +0 -0
  113. /package/dist/{media-QOGVG6CU.js.map → media-YPVGQ535.js.map} +0 -0
  114. /package/dist/{meta-RJH5COPE.js.map → meta-ZQXCUKHQ.js.map} +0 -0
  115. /package/dist/{page-photos-P2XMKTVF.js.map → page-photos-BEAMTVP5.js.map} +0 -0
  116. /package/dist/{rule-writes-MSMVQDQO.js.map → rule-writes-CVP6CH2R.js.map} +0 -0
  117. /package/dist/{rules-UEKJOZTV.js.map → rules-LZ36YNG3.js.map} +0 -0
  118. /package/dist/{studies-TIF7PYEB.js.map → studies-Y6PGWT66.js.map} +0 -0
  119. /package/dist/{study-writes-RGKBOOJ6.js.map → study-writes-6F6O6N4E.js.map} +0 -0
  120. /package/dist/{tag-manager-5Q5MHQPL.js.map → tag-manager-QO6VW57E.js.map} +0 -0
  121. /package/dist/{targeting-YWOOD6YL.js.map → targeting-FRMVSXXL.js.map} +0 -0
  122. /package/dist/{write-commands-REUTFNJ3.js.map → write-commands-3BMPDY3K.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/ads/google/draft-account.ts","../src/commands/ads/google/write-shared.ts","../src/commands/ads/google/copy-list-usage.ts","../src/commands/ads/google/draft-status.ts","../src/commands/ads/google/stage-streak.ts"],"sourcesContent":["import type { GoogleDraftListResponse } from \"@baker/api/ads-google\";\n\n/**\n * `--customer-id` on the draft reads. A draft belongs to the chat, not to an account, and may span\n * several; every other Google Ads command takes the flag, so agents carry it here (BAKER-497).\n * `list` narrows to that account and says what the others still hold; `validate` and `show` keep\n * their whole answer, because publish sends every account together and a ref names one op.\n */\n\nfunction changes(n: number, staged: boolean): string {\n const noun = staged ? \"staged change\" : \"change\";\n return n === 1 ? `1 ${noun}` : `${n} ${noun}s`;\n}\n\n/**\n * The draft as one account holds it, with what the rest of the chat's draft holds. `empty` is the\n * readable line for an account holding none of it, where the whole-chat \"nothing staged\" would be false.\n * Only an active draft's other changes are still to publish; a published one's are already done.\n */\nexport function draftInAccount(\n data: GoogleDraftListResponse,\n customerId: string,\n): { data: GoogleDraftListResponse; hints: string[]; empty?: string } {\n const ops = data.ops.filter((op) => op.customerId === customerId);\n const narrowed = {\n ...data,\n count: ops.length,\n ops,\n ...(data.tree ? { tree: data.tree.filter((node) => node.customerId === customerId) } : {}),\n };\n const others = data.ops.filter((op) => op.customerId !== customerId);\n if (others.length === 0) return { data: narrowed, hints: [] };\n const staged = data.status === \"active\";\n const accounts = [...new Set(others.map((op) => op.customerId))];\n const where = `account${accounts.length === 1 ? \"\" : \"s\"} ${accounts.join(\", \")}`;\n const one = others.length === 1;\n if (ops.length === 0) {\n return {\n data: narrowed,\n empty: `No Google Ads changes in account ${customerId} on this chat.`,\n hints: [`This chat's ${changes(others.length, staged)} ${one ? \"is\" : \"are\"} in ${where}, not ${customerId}.`],\n };\n }\n const more = `${others.length} more ${staged ? \"staged \" : \"\"}change${one ? \"\" : \"s\"}`;\n const verb = staged ? (one ? \"publishes\" : \"publish\") : one ? \"is\" : \"are\";\n return {\n data: narrowed,\n hints: [\n `Showing account ${customerId} only. ${more} in ${where} ${verb} ${staged ? \"with this chat too\" : \"on this chat too\"}; \\`baker ads google draft list\\` without --customer-id shows ${one ? \"it\" : \"them\"}.`,\n ],\n };\n}\n\n/** `draft validate --customer-id`: said back, since the verdicts still cover every account. */\nexport function validateAccountHint(customerId: string): string {\n return `Validated this chat's whole draft, not only account ${customerId}: publish sends every account's changes together, so each verdict above counts.`;\n}\n\n/** `draft show --customer-id` naming another account than the op's own. */\nexport function showAccountHint(customerId: string, opCustomerId: string): string | undefined {\n return opCustomerId === customerId ? undefined : `This op is staged in account ${opCustomerId}, not ${customerId}.`;\n}\n","import { readFileSync } from \"node:fs\";\nimport {\n GOOGLE_DRAFT_BATCH_MAX,\n type GoogleDraftListResponse,\n type GoogleDraftOpKind,\n type GoogleDraftStageBatchResponse,\n type GoogleDraftStageResponse,\n googleDraftBatchOpSchema,\n googleDraftOpInputSchema,\n OP_TOO_LARGE_FIX,\n OP_TOO_LARGE_MESSAGE_START,\n toMicros,\n} from \"@baker/api/ads-google\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiPost } from \"../../../client.ts\";\nimport { requireChatId, resolveChatId } from \"../../../env.ts\";\nimport { handleConnectionError, isNotConnectedError } from \"../../../error-handler.ts\";\nimport { repeatedValues } from \"../../../lib/repeatedFlags.ts\";\nimport { type CommandEffectDeclaration, type PayloadSource, payloadArg, withEffect } from \"../../../schemas.ts\";\nimport { payloadFix } from \"../../capabilities/fix.ts\";\nimport { type DraftWhere, draftListWhere, wholeDraftHints } from \"../../draft-where.ts\";\nimport { booleanWordPositionalError } from \"../boolean-word-positional.ts\";\nimport { adCopyHints } from \"../copy-hints.ts\";\nimport { hintLines, withHints } from \"../hints.ts\";\nimport { bareCustomerId, writeJsonEnvelope } from \"../output.ts\";\nimport { unsaidGuidance } from \"../stage-guidance.ts\";\nimport { termsRefusalFix } from \"../terms-output.ts\";\nimport { copyListCountFix } from \"./copy-list-usage.ts\";\nimport { draftInAccount } from \"./draft-account.ts\";\nimport { renderDraftStatus } from \"./draft-status.ts\";\nimport { recordSingleStage, recordTreeStage } from \"./stage-streak.ts\";\n\n/**\n * Shared plumbing for the staged Google Ads write commands. Writes NEVER hit\n * the Google Ads API directly: every command stages an op against this chat's\n * draft (`/api/ads/google/draft/stage`), the dashboard shows it as a pending\n * Google Ads change, and the draft applies as one `GoogleAdsService.Mutate`\n * request per advertiser account when the chat is published. `--customer-id` is\n * required on every write — a draft may span several accounts, so nothing is\n * picked for you.\n */\n\n/** What a staged Google Ads write command does: one op of these kinds onto this chat's draft. */\nexport function googleStaged(...kinds: GoogleDraftOpKind[]): CommandEffectDeclaration {\n return { effect: \"stage\", routes: [\"POST /api/ads/google/draft/stage\"], stages: kinds };\n}\n\n/** A staged write that takes one op or many: several go as one batch (`stageGoogleOps`). */\nexport function googleStagedBatch(...kinds: GoogleDraftOpKind[]): CommandEffectDeclaration {\n return {\n effect: \"stage\",\n routes: [\"POST /api/ads/google/draft/stage\", \"POST /api/ads/google/draft/stage-batch\"],\n stages: kinds,\n };\n}\n\nexport function failWriteValidation(message: string): never {\n writeJsonEnvelope({ ok: false, error: { code: \"VALIDATION_ERROR\", message } });\n process.exit(1);\n}\n\nexport function requireCustomerId(args: Record<string, unknown>): string {\n const given = (args[\"customer-id\"] ?? args.customerId) as string | undefined;\n const raw = given === undefined ? undefined : bareCustomerId(String(given));\n if (!raw || !/^\\d{10}$/.test(raw)) {\n failWriteValidation(\"pass --customer-id as the 10-digit Google Ads customer id (386-508-3115 or 3865083115)\");\n }\n return raw;\n}\n\nexport function requireTarget(args: Record<string, unknown>, entity: string): string {\n // `--flag false` is refused, not documented: citty parses it as the flag set to TRUE plus a stray\n // positional nobody consumes, so on `conversions update --primary` it silently PROMOTES an action\n // into what every Maximize Conversions campaign bids toward. Caught here because this is the only\n // place on this surface that reads positionals, and every target-taking command goes through it.\n const booleanWord = booleanWordPositionalError(args, entity);\n if (booleanWord) {\n failWriteValidation(booleanWord);\n }\n const positional = Array.isArray(args._) ? args._[0] : undefined;\n const target = args.id ?? args.target ?? args.ref ?? positional;\n if (typeof target !== \"string\" || target.length === 0) {\n failWriteValidation(`pass the ${entity} resource name or id as the positional argument`);\n }\n return target;\n}\n\n/**\n * The targets a bulk status command was given: every positional (comma-separated ones split), plus\n * `--file` with one target per line (blank lines and `#` comments skipped), deduped in order. One\n * call then stages them all as one batch instead of one command per row.\n */\nexport function targetEntries(args: Record<string, unknown>, entity: string): string[] {\n const booleanWord = booleanWordPositionalError(args, entity);\n if (booleanWord) {\n failWriteValidation(booleanWord);\n }\n const positionals = Array.isArray(args._) ? args._.filter((v): v is string => typeof v === \"string\") : [];\n const raw = [...positionals.flatMap((v) => v.split(\",\")), ...rawFileEntries(args.file)]\n .map((v) => v.trim())\n .filter(Boolean);\n const targets = [...new Set(raw)];\n if (targets.length === 0) {\n failWriteValidation(`pass the ${entity} resource name(s) as positional arguments and/or --file (one per line)`);\n }\n if (targets.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(`${targets.length} targets exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX} — split them`);\n }\n return targets;\n}\n\n/**\n * The targets an update command was given: one, or several (space- or comma-separated) that each get\n * the same payload, staged as one batch. `--file` here is the payload, never a list of targets.\n */\nexport function updateTargets(args: Record<string, unknown>, entity: string): string[] {\n return Array.isArray(args._) && args._.length > 0\n ? targetEntries({ ...args, file: undefined }, entity)\n : [requireTarget(args, entity)];\n}\n\nexport function requireStringFlag(value: unknown, flag: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n failWriteValidation(`${flag} is required`);\n }\n return value;\n}\n\n/** Money flag in major currency units → micros. */\nexport function microsFlag(value: unknown, flag: string): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const num = Number(value);\n if (Number.isNaN(num) || num <= 0) {\n failWriteValidation(`${flag} must be a positive amount (major currency units, e.g. 50 or 50.00)`);\n }\n return toMicros(num);\n}\n\n/** Split a comma-separated flag into trimmed non-empty values. */\nexport function listFlag(value: unknown): string[] | undefined {\n if (typeof value !== \"string\" || value.length === 0) {\n return undefined;\n }\n const items = value\n .split(\",\")\n .map((v) => v.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\nexport interface KeywordEntry {\n text: string;\n matchType: string;\n}\n\nconst MATCH_TYPES = new Set([\"EXACT\", \"PHRASE\", \"BROAD\"]);\n\n/**\n * One raw keyword entry → { text, matchType }. A trailing `:EXACT|:PHRASE|:BROAD`\n * suffix overrides the default match type; colons and commas aren't legal in Google\n * keyword text, so the syntax is unambiguous.\n */\nfunction parseKeywordEntry(raw: string, defaultMatch: string | undefined): KeywordEntry {\n const colon = raw.lastIndexOf(\":\");\n if (colon > 0) {\n const suffix = raw\n .slice(colon + 1)\n .trim()\n .toUpperCase();\n if (MATCH_TYPES.has(suffix)) {\n return { text: raw.slice(0, colon).trim(), matchType: suffix };\n }\n failWriteValidation(`\"${raw}\": \":${raw.slice(colon + 1)}\" is not a match type (EXACT | PHRASE | BROAD)`);\n }\n if (!defaultMatch) {\n failWriteValidation(`\"${raw}\" has no match type — add a :EXACT/:PHRASE/:BROAD suffix or pass --match-type`);\n }\n return { text: raw, matchType: defaultMatch };\n}\n\n/**\n * Raw --text value(s) → individual entries: repeated flags and comma-separated\n * both work. The repeats have to come off `rawArgs`, because citty parses a\n * repeated flag down to its last value alone.\n */\nfunction rawTextEntries(value: unknown, rawArgs: readonly string[] | undefined): string[] {\n return repeatedValues(rawArgs, \"text\", value)\n .flatMap((v) => v.split(\",\"))\n .map((v) => v.trim())\n .filter(Boolean);\n}\n\n/** Newline-separated keyword file: one `text[:MATCH_TYPE]` per line; blank lines and `#` comments skipped. */\nfunction rawFileEntries(path: unknown): string[] {\n return typeof path === \"string\" && path.length > 0 ? fileLines(path) : [];\n}\n\n/** A text file's entries: one per line, trimmed; blank lines and `#` comments skipped. */\nexport function fileLines(path: string): string[] {\n return readFileSync(path, \"utf8\")\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith(\"#\"));\n}\n\n/**\n * The keyword batch a command was invoked with: comma-separated `--text` entries\n * (optional `:MATCH_TYPE` suffix each) plus `--file` lines, deduped, each falling\n * back to `--match-type`. One entry stages exactly like before; many stage as one batch.\n */\nexport function keywordEntries(args: Record<string, unknown>, rawArgs?: readonly string[]): KeywordEntry[] {\n const defaultMatch = typeof args[\"match-type\"] === \"string\" ? args[\"match-type\"].toUpperCase() : undefined;\n const raw = [...rawTextEntries(args.text, rawArgs), ...rawFileEntries(args.file)];\n if (raw.length === 0) {\n failWriteValidation(\"pass keywords via --text (comma-separated) and/or --file (one per line)\");\n }\n if (raw.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(`${raw.length} keywords exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX}`);\n }\n const entries: KeywordEntry[] = [];\n const seen = new Set<string>();\n for (const item of raw) {\n const entry = parseKeywordEntry(item, defaultMatch);\n const key = JSON.stringify([entry.text, entry.matchType]);\n if (!seen.has(key)) {\n seen.add(key);\n entries.push(entry);\n }\n }\n return entries;\n}\n\n/**\n * The payloads behind `--file`: a path to a JSON file, or the JSON written inline. The file holds one\n * payload object, a JSON array of them, or JSON Lines (one object per line) — many payloads stage as\n * one batch, which is how a bulk change lands in one call instead of hundreds.\n *\n * Inline is here because every doc example already writes it that way — `packages/cli/README.md`\n * and the scaffold's `ads-google.md` both show `--file '{\"type\":\"image\",…}'` — while the arg only\n * ever read a path, so following the documentation answered with a raw ENOENT stack trace. Reading\n * a leading `{` or `[` as the payload makes those examples true rather than making the agent re-learn\n * the one shape that works.\n */\nexport function loadJsonPayloads(path: unknown): Array<Record<string, unknown>> {\n if (typeof path !== \"string\" || path.length === 0) {\n return [];\n }\n const inline = /^\\s*[[{]/.test(path);\n const source = inline ? \"inline JSON\" : path;\n const text = inline ? path : readFileSync(path, \"utf8\");\n return parsedPayloads(text, source).map((item, index, all) => {\n if (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n failWriteValidation(\n all.length === 1 ? `${source} must contain a JSON object` : `${source}: item ${index} must be a JSON object`,\n );\n }\n return item as Record<string, unknown>;\n });\n}\n\n/** One JSON value (an array spreads into its items), else JSON Lines; the JSON error when neither parses. */\nfunction parsedPayloads(text: string, source: string): unknown[] {\n try {\n const parsed = JSON.parse(text) as unknown;\n return Array.isArray(parsed) ? parsed : [parsed];\n } catch (err) {\n if (!(err instanceof SyntaxError)) {\n throw err;\n }\n const lines = text.split(/\\r?\\n/).filter((line) => line.trim().length > 0);\n if (lines.length > 1) {\n return lines.map((line, index) => parseJsonLine(line, index, source));\n }\n failWriteValidation(`${source} is not valid JSON: ${err.message}`);\n }\n}\n\n/** One JSON Lines entry, or the line's own error naming where it is. */\nfunction parseJsonLine(line: string, index: number, source: string): unknown {\n try {\n return JSON.parse(line) as unknown;\n } catch (err) {\n return failWriteValidation(\n `${source} line ${index + 1} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/** The ONE op payload behind `--file`, for commands that change a single entity. */\nexport function loadJsonFileArg(path: unknown): Record<string, unknown> {\n const payloads = loadJsonPayloads(path);\n if (payloads.length > 1) {\n failWriteValidation(\n `this command changes one entity, and --file holds ${payloads.length} payloads — stage many changes from one file with \\`baker ads google draft stage --file\\` (one op per item: {\"kind\",\"customerId\",\"target\"?,\"payload\"?})`,\n );\n }\n return payloads[0] ?? {};\n}\n\n/** Flags override file keys — the file is the base, flags are the overrides. */\nexport function mergePayload(file: Record<string, unknown>, flags: Record<string, unknown>): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...file };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\n/**\n * The `draft amend` patch: exactly one of `--file <path>` (JSON file) or `--patch '<json>'`\n * (inline string), and it must parse to a JSON object — RFC-7386 merge-patch needs an object to\n * merge, and a stray array/scalar would silently no-op or replace the whole payload.\n */\nexport function loadPatchArg(args: Record<string, unknown>): Record<string, unknown> {\n const file = typeof args.file === \"string\" && args.file.length > 0 ? args.file : undefined;\n const inline = typeof args.patch === \"string\" && args.patch.length > 0 ? args.patch : undefined;\n if (Boolean(file) === Boolean(inline)) {\n failWriteValidation(\"pass exactly one of --file <patch.json> or --patch '<json>'\");\n }\n if (file) {\n return loadJsonFileArg(file);\n }\n try {\n const parsed = JSON.parse(inline as string) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n failWriteValidation(\"--patch must be a JSON object\");\n }\n return parsed as Record<string, unknown>;\n } catch (err) {\n if (err instanceof SyntaxError) {\n failWriteValidation(`--patch is not valid JSON: ${err.message}`);\n }\n throw err;\n }\n}\n\nexport function handleGoogleError(err: unknown): never {\n if (err instanceof ApiError) {\n // Covers both \"no connection\" and staging's 403 for an account this company\n // never connected — same remedy either way: connect, and pick the account.\n if (isNotConnectedError(err.code, err.message)) {\n handleConnectionError(\"google_ads\", err.message);\n }\n const terms = termsRefusalFix(err.code, err.message);\n if (terms) {\n writeJsonEnvelope({\n ok: false,\n error: { code: terms.code, message: err.message, retryable: false, fix: terms.fix },\n });\n process.exit(1);\n }\n if (err.message.includes(OP_TOO_LARGE_MESSAGE_START)) {\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"OP_TOO_LARGE\",\n message: err.message,\n retryable: false,\n fix: { action: \"split_the_change\", explanation: OP_TOO_LARGE_FIX },\n },\n });\n process.exit(1);\n }\n writeJsonEnvelope({ ok: false, error: { code: err.code ?? \"API_ERROR\", message: err.message } });\n process.exit(1);\n }\n writeJsonEnvelope({\n ok: false,\n error: { code: \"UNKNOWN\", message: err instanceof Error ? err.message : String(err) },\n });\n process.exit(1);\n}\n\ninterface StageEnvelope extends Record<string, unknown> {\n ok: true;\n data: GoogleDraftStageResponse;\n}\n\n/**\n * A no-op response isn't a failure — the change was already in place, so nothing was\n * staged. Say so explicitly, otherwise the agent re-stages it or reports work it\n * didn't do. `data.reason` says why; repeating it here printed every reason twice (BAKER-390).\n */\nfunction noopHints(data: GoogleDraftStageResponse): string[] {\n return data.staged\n ? []\n : [\n \"NOT STAGED — `data.reason` says why. Nothing to publish for this change; say so rather than reporting it as done.\",\n ];\n}\n\n/**\n * What to tell the agent about the ops a batch didn't stage.\n *\n * Two different things land in `skipped`: a change already in place, and a change Google refuses\n * outright (editing an experiment campaign's status, dates or budget). This hint used to assert the\n * first — \"already in the requested state\" — which read as \"done\" for a refusal the user never heard\n * about. So it leads with each op's own reason and asks for the refusals to be passed on.\n */\nexport function skippedHints(skipped: Array<{ summary: string; reason: string }>, total: number): string[] {\n if (skipped.length === 0) {\n return [];\n }\n const detail = skipped.map((s) => `${s.summary} — ${s.reason}`).join(\"; \");\n return [\n `${skipped.length} of ${total} op(s) NOT STAGED: ${detail}. Don't re-stage them; tell the user which changes couldn't be made and why, then carry on with the rest.`,\n ];\n}\n\n/**\n * Preflight-validates the op against the shared `@baker/api/ads-google`\n * contract (the same schema the backend enforces), then stages it. Prints the\n * staged envelope — ref, mode (always `live`: publishing reaches the real\n * account), summary, warnings.\n */\nexport async function stageGoogleOp(raw: Record<string, unknown>, hints?: string[]): Promise<void> {\n const preflight = googleDraftOpInputSchema.safeParse(raw);\n if (!preflight.success) {\n const fields = preflight.error.issues.map((issue) => ({ path: issue.path.join(\".\"), message: issue.message }));\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: fields.map((f) => (f.path ? `${f.path}: ${f.message}` : f.message)).join(\"; \"),\n fields,\n fix: copyListCountFix(raw, preflight.error.issues) ?? payloadFix(\"google-ads\", googleDraftOpInputSchema, raw),\n },\n });\n process.exit(1);\n }\n try {\n const chatId = requireChatId();\n const response = await apiPost<StageEnvelope>(\"/api/ads/google/draft/stage\", { chatId, op: preflight.data });\n const allHints = [\n ...noopHints(response.data),\n ...recordSingleStage(chatId, preflight.data.kind),\n ...recordTreeStage(chatId, response.data),\n ...unsaidGuidance(chatId, hints ?? []),\n ...(await adCopyHints(preflight.data)),\n ];\n writeJsonEnvelope(withHints(response, allHints));\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\n/** Stage a create op: `{ kind, customerId, payload }`. */\nexport async function stageCreate(\n kind: string,\n customerId: string,\n payload: Record<string, unknown>,\n hints?: string[],\n): Promise<void> {\n await stageGoogleOp({ kind, customerId, payload }, hints);\n}\n\ninterface StageBatchEnvelope extends Record<string, unknown> {\n ok: true;\n data: GoogleDraftStageBatchResponse;\n}\n\n/**\n * A batch reads every target's before-state and checks each op against the account, which for a few\n * hundred removals outlasts the default 60 s. Timing out early reported a batch as failed that went on\n * to stage, so a retry then collided with the ops it had already staged.\n */\nconst STAGE_BATCH_TIMEOUT_MS = 5 * 60_000;\n\n/** `--full` on every command that stages a batch: the compact result lists only the ops that need a look. */\nexport const STAGE_FULL_ARG = {\n type: \"boolean\",\n description:\n \"List every staged op with its ref and summary (default: counts, the `as` → ref names, and only the ops with warnings)\",\n} as const;\n\n/**\n * What a batch stage prints by default: counts by kind, the ref each `\"as\"` name became (later calls\n * name the ref), and only the ops that carry a warning. A batch of 384 negatives printed one object\n * per op — 85 KB of the agent's own input echoed back with `\"warnings\": []` — so agents cut it with\n * `head`, which also cuts a late op's warning and the hints (BAKER-4005, BAKER-3464).\n */\nfunction stageBatchView(\n data: GoogleDraftStageBatchResponse,\n full: boolean,\n): GoogleDraftStageBatchResponse & { byKind?: Record<string, number>; refs?: Record<string, string> } {\n if (full) {\n return data;\n }\n const { ops, ...rest } = data;\n const byKind: Record<string, number> = {};\n const refs: Record<string, string> = {};\n for (const op of ops) {\n byKind[op.kind] = (byKind[op.kind] ?? 0) + 1;\n if (op.as) refs[op.as] = op.ref;\n }\n return {\n ...rest,\n byKind,\n ...(Object.keys(refs).length > 0 ? { refs } : {}),\n ops: ops.filter((op) => op.warnings.length > 0),\n };\n}\n\n/**\n * Stage several ops as ONE request (`/stage-batch`) — all-or-nothing on the backend,\n * one rate-limit hit instead of one per keyword. A single op falls through to the\n * plain stage path so its envelope (and amend behavior) stays exactly as before.\n * Prints `stageBatchView`: compact unless `full`.\n */\nexport async function stageGoogleOps(\n rawOps: Array<Record<string, unknown>>,\n hints?: string[],\n full = false,\n): Promise<void> {\n if (rawOps.length === 1 && rawOps[0]) {\n await stageGoogleOp(rawOps[0], hints);\n return;\n }\n const ops: unknown[] = [];\n for (const [index, raw] of rawOps.entries()) {\n const preflight = googleDraftBatchOpSchema.safeParse(raw);\n if (!preflight.success) {\n const fields = preflight.error.issues.map((issue) => ({\n path: `ops[${index}].${issue.path.join(\".\")}`,\n message: issue.message,\n }));\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: fields.map((f) => `${f.path}: ${f.message}`).join(\"; \"),\n fields,\n fix: copyListCountFix(raw, preflight.error.issues) ?? payloadFix(\"google-ads\", googleDraftOpInputSchema, raw),\n },\n });\n process.exit(1);\n }\n ops.push(preflight.data);\n }\n try {\n const chatId = requireChatId();\n const response = await apiPost<StageBatchEnvelope>(\n \"/api/ads/google/draft/stage-batch\",\n { chatId, ops },\n { timeoutMs: STAGE_BATCH_TIMEOUT_MS },\n );\n const view = stageBatchView(response.data, full);\n const omitted = response.data.ops.length - view.ops.length;\n const allHints = [\n ...skippedHints(response.data.skipped ?? [], ops.length),\n ...(omitted > 0\n ? [\n `${omitted} staged ops without a warning are left out. They are already staged — do not stage them again; read their refs with \\`baker ads google draft list --json\\` (pass --full on a later stage to print every op).`,\n ]\n : []),\n ...unsaidGuidance(chatId, hints ?? []),\n ...(await adCopyHints(ops)),\n ];\n writeJsonEnvelope(withHints({ ...response, data: view }, allHints));\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\n/** Stage an update op: `{ kind, customerId, target, payload }`. */\nexport async function stageUpdate(\n kind: string,\n customerId: string,\n target: string,\n payload: Record<string, unknown>,\n hints?: string[],\n): Promise<void> {\n await stageGoogleOp({ kind, customerId, target, payload }, hints);\n}\n\n/** Stage a target-only op (pause/resume/remove/detach): `{ kind, customerId, target }`. */\nexport async function stageTarget(kind: string, customerId: string, target: string, hints?: string[]): Promise<void> {\n await stageGoogleOp({ kind, customerId, target }, hints);\n}\n\nexport async function draftAction(path: string, body: Record<string, unknown>, chat?: unknown): Promise<void> {\n try {\n const chatId = resolveChatId(chat);\n const response = await apiPost<Record<string, unknown>>(path, { chatId, ...body });\n writeJsonEnvelope(response);\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\ninterface DraftListEnvelope extends Record<string, unknown> {\n ok: boolean;\n data?: GoogleDraftListResponse;\n}\n\n/**\n * List the staged draft. By default renders a readable campaign ▸ ad group ▸ ad status tree so the\n * agent can review everything it has staged at a glance; `--json` returns the raw envelope for tools,\n * and `--full` that envelope with every op's payload.\n */\nexport async function draftListAction(\n json: boolean,\n chat?: unknown,\n full = false,\n customerId?: string,\n selected?: { where: DraftWhere; selector: string },\n): Promise<void> {\n try {\n const chatId = resolveChatId(chat);\n const listed = await apiPost<DraftListEnvelope>(\"/api/ads/google/draft\", {\n chatId,\n ...(full || selected ? { full: true } : {}),\n });\n const inAccount =\n customerId !== undefined && listed.ok && listed.data ? draftInAccount(listed.data, customerId) : undefined;\n const response = inAccount ? withHints({ ...listed, data: inAccount.data }, inAccount.hints) : listed;\n if (selected && response.ok && response.data) {\n const narrowed = draftListWhere(response.data, selected.where, selected.selector);\n writeJsonEnvelope(withHints({ ...response, data: narrowed.data }, narrowed.hints));\n return;\n }\n if (json || full || !response.ok || !response.data) {\n const whole =\n response.ok && response.data\n ? wholeDraftHints(response.data.ops, \"baker ads google draft list\", \"google.\")\n : [];\n writeJsonEnvelope(withHints(response, whole));\n return;\n }\n process.stdout.write(`${inAccount?.empty ?? renderDraftStatus(response.data)}${hintLines(response)}\\n`);\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\nexport const customerIdArg = {\n \"customer-id\": { type: \"string\" as const, description: \"10-digit Google Ads customer id\" },\n};\n/** The entity a command changes, read by position the way `requireTarget` reads it — declared so --help shows it. */\nexport function targetArg(entity: string) {\n return {\n id: {\n type: \"positional\" as const,\n description: `The ${entity} to change: its id or resource name (customers/…)`,\n required: false,\n },\n };\n}\n\nconst PAYLOAD_FIELDS = \"run `baker schema` on this command for every field the payload takes\";\n\nfunction payloadShape(kind: string): () => PayloadSource {\n return () => ({ union: googleDraftOpInputSchema, kind });\n}\n\n/** `--file` for a command that stages one `kind` op; `baker schema` prints that op's payload shape. */\nexport function fileArg(kind: string) {\n return {\n file: payloadArg(\n {\n type: \"string\" as const,\n description: `The op payload: a JSON file path, or the JSON object inline (flags override it) — ${PAYLOAD_FIELDS}`,\n },\n payloadShape(kind),\n ),\n };\n}\n\n/** `--file` that stages one or many `kind` ops; `baker schema` prints that op's payload shape. */\nexport function fileBatchArg(kind: string) {\n return {\n file: payloadArg(\n {\n type: \"string\" as const,\n description: `The op payload: a JSON file path or inline JSON — one object, or a JSON array / JSON Lines of objects to stage many in one call (up to 500) — ${PAYLOAD_FIELDS}`,\n },\n payloadShape(kind),\n ),\n };\n}\n\n/** A create command whose payload is a JSON file or inline JSON — one object or an array staged as one batch. */\nexport function fileCreateCommand(\n name: string,\n kind: GoogleDraftOpKind,\n description: string,\n hints?: string[] | ((payload: Record<string, unknown>) => string[]),\n) {\n return withEffect(\n googleStagedBatch(kind),\n defineCommand({\n meta: { name, description },\n args: { ...customerIdArg, ...fileBatchArg(kind), full: STAGE_FULL_ARG },\n run: async ({ args }) => {\n const customerId = requireCustomerId(args);\n const payloads = loadJsonPayloads(args.file);\n if (payloads.length === 0 || payloads.some((payload) => Object.keys(payload).length === 0)) {\n failWriteValidation(`${kind} needs --file with the op payload (one object, or a JSON array to stage many)`);\n }\n if (payloads.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(\n `${payloads.length} payloads exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX} — split the file`,\n );\n }\n const payloadHints = [\n ...new Set(payloads.flatMap((payload) => (typeof hints === \"function\" ? hints(payload) : (hints ?? [])))),\n ];\n await stageGoogleOps(\n payloads.map((payload) => ({ kind, customerId, payload })),\n payloadHints,\n args.full === true,\n );\n },\n }),\n );\n}\n\n/**\n * `--bid-modifier` as a number, validated against the range Google actually accepts.\n *\n * Rejecting the (0, 0.1) gap here rather than at the backend is the point: 0 and 0.1 are a hundredth\n * apart in value and mean \"never serve\" versus \"bid a tenth\", so a typo between them is a real spend\n * decision, and the error should arrive before anything is staged.\n */\nexport function bidModifierFlag(value: unknown): number {\n if (value === undefined || value === null || value === \"\") {\n failWriteValidation(\n \"--bid-modifier is required: 1 for no adjustment, 1.25 to bid 25% more, 0.9 to bid 10% less, 0 to stop serving on a device\",\n );\n }\n const num = Number(value);\n if (Number.isNaN(num) || num < 0 || num > 10 || (num > 0 && num < 0.1)) {\n failWriteValidation(\"--bid-modifier must be 0 (stop serving on it) or between 0.1 and 10.0\");\n }\n return num;\n}\n","import type { z } from \"zod\";\n\n/** Appended to each copy flag's help, so `--help` and `baker schema` say how to pass a comma. */\nexport const AD_COPY_LIST_USAGE =\n \"repeat the flag once per item, or pass one comma-separated list and wrap an item that contains a comma in double quotes: '\\\"Fast, free quotes\\\",Book today'. A flag given once is read as a list, so a lone item with a comma needs its double quotes too: '\\\"Fast, free quotes\\\"'\";\n\n/** The op's copy-list fields, by the flag an agent passes them with. */\nconst COPY_LIST_FLAG: Readonly<Record<string, string>> = {\n headlines: \"--headlines\",\n descriptions: \"--descriptions\",\n longHeadlines: \"--long-headlines\",\n};\n\ninterface CountRefusal {\n flag: string;\n count: number | undefined;\n bound: string;\n tooMany: boolean;\n}\n\nfunction valueAt(root: unknown, path: readonly PropertyKey[]): unknown {\n let node = root;\n for (const key of path) {\n if (node === null || typeof node !== \"object\") return undefined;\n node = (node as Record<PropertyKey, unknown>)[key];\n }\n return node;\n}\n\nfunction countRefusal(op: unknown, issue: z.core.$ZodIssue): CountRefusal | undefined {\n if ((issue.code !== \"too_big\" && issue.code !== \"too_small\") || issue.origin !== \"array\") return undefined;\n const flag = COPY_LIST_FLAG[String(issue.path.at(-1))];\n if (!flag) return undefined;\n const value = valueAt(op, issue.path);\n const count = Array.isArray(value) ? value.length : undefined;\n return issue.code === \"too_big\"\n ? { flag, count, bound: `at most ${issue.maximum}`, tooMany: true }\n : { flag, count, bound: `at least ${issue.minimum}`, tooMany: false };\n}\n\n/**\n * The fix for a stage refused only for how many headlines, descriptions or long headlines it has.\n *\n * That is a limit on a field the agent named correctly, so the generic \"read `baker capabilities`,\n * do not guess another field name\" sent it through draft list, schema and --help before it saw the\n * cause. Too many items is usually copy cut at its commas — a flag given once is a comma-separated\n * list, so \"Rated 4,5/5\" becomes two items — which is why that case names the forms that keep a\n * comma. Undefined when anything else was refused too, so the capabilities pointer still covers it.\n */\nexport function copyListCountFix(\n op: unknown,\n issues: readonly z.core.$ZodIssue[],\n): { action: string; explanation: string } | undefined {\n const refusals = issues.map((issue) => countRefusal(op, issue));\n if (refusals.length === 0 || refusals.some((refusal) => refusal === undefined)) return undefined;\n const counted = refusals.filter((refusal): refusal is CountRefusal => refusal !== undefined);\n const limits = counted\n .map(({ flag, count, bound }) => `${flag} has ${count ?? \"the wrong number of\"} items; this ad takes ${bound}.`)\n .join(\" \");\n const commaCause = counted.some((refusal) => refusal.tooMany)\n ? ' If you meant fewer items, the copy was cut at its commas: a flag given once is read as a comma-separated list, so an item with a comma in it (\"Fast, free quotes\", a decimal like \"4,5/5\") becomes two. To keep a comma, ' +\n `${AD_COPY_LIST_USAGE} — or put the content in --file as JSON.`\n : \"\";\n return {\n action: \"fix_copy_list_count\",\n explanation: `${limits}${commaCause} ${commaCause ? \"Otherwise add\" : \"Add\"} or drop items to fit the limit, then stage again; the field names are right.`,\n };\n}\n","import type {\n GoogleDraftListResponse,\n GoogleDraftStatusCollection,\n GoogleDraftStatusNode,\n} from \"@baker/api/ads-google\";\n\n/**\n * Render the staged Google Ads draft as a readable campaign ▸ ad group ▸ ad tree — the CLI\n * counterpart to the dashboard's Google Ads tab, so an agent can review everything it has staged\n * with one command instead of reading raw JSON. Pure: takes the draft-list response, returns text.\n */\n\nconst OPERATION_LABELS: Record<string, string> = {\n create: \"Creating\",\n update: \"Updating\",\n pause: \"Pausing\",\n resume: \"Resuming\",\n remove: \"Removing\",\n upload: \"Uploading\",\n};\n\n/** The same verbs once the publish has run: a published draft reports what happened, not what is staged. */\nconst APPLIED_LABELS: Record<string, string> = {\n create: \"Created\",\n update: \"Updated\",\n pause: \"Paused\",\n resume: \"Resumed\",\n remove: \"Removed\",\n upload: \"Uploaded\",\n};\n\n/** Folded changes that did not land (\"1 change failed\", \"2 changes skipped\"), named beside the node's own outcome. */\nfunction notAppliedText(node: GoogleDraftStatusNode): string | undefined {\n const { failed = 0, skipped = 0 } = node.foldedNotApplied ?? {};\n const changes = (n: number) => `${n} change${n === 1 ? \"\" : \"s\"}`;\n const parts = [\n ...(failed > 0 ? [`${changes(failed)} failed`] : []),\n ...(skipped > 0 ? [`${changes(skipped)} skipped`] : []),\n ];\n return parts.length > 0 ? parts.join(\", \") : undefined;\n}\n\nfunction outcomeBadge(node: GoogleDraftStatusNode, result: NonNullable<GoogleDraftStatusNode[\"result\"]>): string {\n const verb = node.operation ?? \"update\";\n if (result === \"applied\") {\n return node.operation ? (APPLIED_LABELS[verb] ?? \"Applied\") : \"Changes applied\";\n }\n if (result === \"simulated\") {\n return `Simulated (${verb})`;\n }\n if (result === \"failed\") {\n return node.operation ? `Failed to ${verb}` : \"Failed\";\n }\n return \"Skipped\";\n}\n\nfunction badge(node: GoogleDraftStatusNode): string {\n const label = node.result\n ? outcomeBadge(node, node.result)\n : ((node.operation ? OPERATION_LABELS[node.operation] : undefined) ?? (node.existing ? \"on Google Ads\" : \"staged\"));\n const parts = [label, ...(node.status && node.status !== label ? [node.status] : [])];\n const notApplied = notAppliedText(node);\n return [...parts, ...(notApplied ? [notApplied] : [])].join(\" · \");\n}\n\nfunction collectionLine(collection: GoogleDraftStatusCollection): string | undefined {\n const parts: string[] = [];\n if (collection.added > 0) {\n parts.push(`+${collection.added}`);\n }\n if (collection.existing > 0) {\n parts.push(`${collection.existing} existing`);\n }\n if (collection.removed > 0) {\n parts.push(`-${collection.removed}`);\n }\n // Neither an add nor a remove — a member that stays in the set with a changed value (a device's\n // bid adjustment). Left out, a draft whose only criterion change is one printed no line at all.\n if ((collection.updated ?? 0) > 0) {\n parts.push(`~${collection.updated}`);\n }\n return parts.length > 0 ? `${collection.label}: ${parts.join(\", \")}` : undefined;\n}\n\n/**\n * Every advertiser account the tree touches. A draft may legitimately span\n * several, and a criterion id is derived from the keyword's text and match type\n * — so the same keyword carries the same id in every account. The account is\n * printed on each node once there is more than one, and left off when there is not.\n */\nfunction accountsInTree(nodes: readonly GoogleDraftStatusNode[]): Set<string> {\n const accounts = new Set<string>();\n const walk = (node: GoogleDraftStatusNode): void => {\n accounts.add(node.customerId);\n for (const child of node.children) {\n walk(child);\n }\n };\n for (const node of nodes) {\n walk(node);\n }\n return accounts;\n}\n\nfunction renderNode(node: GoogleDraftStatusNode, depth: number, lines: string[], showAccount: boolean): void {\n const indent = \" \".repeat(depth);\n const account = showAccount ? ` · account ${node.customerId}` : \"\";\n const ref = node.ref ? ` · ${node.ref}` : \"\";\n lines.push(`${indent}• ${node.name} · ${badge(node)}${account}${ref}`);\n for (const warning of node.warnings ?? []) {\n lines.push(`${indent} ⚠ ${warning}`);\n }\n for (const folded of node.folded ?? []) {\n lines.push(`${indent} ${folded.summary} · ${folded.ref}`);\n }\n for (const collection of node.collections) {\n const line = collectionLine(collection);\n if (line) {\n lines.push(`${indent} ${line}`);\n }\n }\n for (const child of node.children) {\n renderNode(child, depth + 1, lines, showAccount);\n }\n}\n\nconst RESOURCE_ENTITIES = new Set([\n \"sharedSet\",\n \"biddingStrategy\",\n \"audience\",\n \"customAudience\",\n \"combinedAudience\",\n \"conversionAction\",\n \"label\",\n \"budget\",\n \"asset\",\n]);\n\nfunction renderSection(title: string, nodes: GoogleDraftStatusNode[], lines: string[], showAccount: boolean): void {\n if (nodes.length === 0) {\n return;\n }\n lines.push(\"\");\n lines.push(title);\n for (const node of nodes) {\n renderNode(node, 1, lines, showAccount);\n }\n}\n\nfunction renderAdvisories(data: GoogleDraftListResponse, lines: string[]): void {\n const advisories = data.advisories ?? [];\n // Every advisory is phrased as something to settle BEFORE publishing. On a published draft there\n // is nothing left to settle here, and printing them reads as work still outstanding on this chat.\n if (advisories.length === 0 || data.status === \"applied\") {\n return;\n }\n lines.push(\"\");\n // Two kinds of finding share this block: build-out nudges (\"this ad group has one ad\") and\n // whole-draft coherence findings (\"this campaign will report zero conversions\", \"two of your\n // campaigns bid on the same keyword\"). The coherence ones come first and cost money, so the\n // heading no longer frames the block as optional polish.\n lines.push(\"Advisories (non-blocking, checked across the whole draft — settle these before you publish)\");\n for (const advisory of advisories) {\n lines.push(` • ${advisory.message}`);\n }\n}\n\n/**\n * What the publish did, once there is a publish to report.\n *\n * A published Google Ads draft rendered exactly like a staged one — same count, every op still\n * reading \"Creating\" — so the surface `.claude/rules/cli-env.md` sends an agent to for the outcome\n * could not answer, and a failed op was invisible in the human output while sitting in the JSON\n * envelope the whole time. Found by publishing a BUSINESS_LOGO link that Google refused with\n * \"Customer is not verified\": the draft still read \"4 staged changes\". LinkedIn fixed the same\n * shape first; this is its counterpart.\n */\nfunction renderOutcome(data: GoogleDraftListResponse, lines: string[]): void {\n const counts = new Map<string, number>();\n for (const op of data.ops) {\n const status = op.result?.status ?? \"pending\";\n counts.set(status, (counts.get(status) ?? 0) + 1);\n }\n const summary = [...counts].map(([status, count]) => `${count} ${status}`).join(\", \");\n lines.push(`Google Ads — published · ${summary || `${data.count} op(s)`} · ${data.mode}`);\n // A failure is the reason to read this at all, so it is named with its error rather than left as\n // a number to go and look up.\n for (const op of data.ops) {\n const status = op.result?.status;\n if (status !== \"failed\" && status !== \"skipped\") {\n continue;\n }\n const reason = op.result?.error ?? op.result?.skippedBecause ?? \"no reason recorded\";\n lines.push(` ✗ ${op.summary} — ${status}: ${reason}`);\n }\n // Google answers \"applied\" to a field it accepted and never stored (a portfolio's bid ceiling),\n // so the read-back after publish is the only thing that knows the change did not land as sent.\n for (const op of data.ops) {\n const verification = op.result?.verification;\n if (op.result?.status === \"applied\" && verification?.status === \"drifted\") {\n lines.push(` ⚠ ${op.summary} — not as sent: ${verification.note ?? \"Google Ads shows something else\"}`);\n }\n }\n}\n\nexport function renderDraftStatus(data: GoogleDraftListResponse): string {\n if (data.status === \"none\" || data.count === 0) {\n return \"No staged Google Ads changes on this chat.\";\n }\n const modeNote =\n data.mode === \"live\"\n ? \"Live — publishing writes directly to Google Ads.\"\n : \"Simulated — publishing completes the whole draft without calling Google Ads.\";\n const lines: string[] = [];\n if (data.status === \"applied\") {\n renderOutcome(data, lines);\n } else if (data.status === \"publishing\") {\n lines.push(`Google Ads — publishing ${data.count} change${data.count === 1 ? \"\" : \"s\"} · ${data.mode}`);\n } else {\n lines.push(`Google Ads — ${data.count} staged change${data.count === 1 ? \"\" : \"s\"} · ${data.mode}`);\n }\n lines.push(modeNote);\n\n const tree = data.tree ?? [];\n const showAccount = accountsInTree(tree).size > 1;\n renderSection(\n \"Shared resources\",\n tree.filter((node) => RESOURCE_ENTITIES.has(node.entity)),\n lines,\n showAccount,\n );\n renderSection(\n \"Campaigns\",\n tree.filter((node) => node.entity === \"campaign\"),\n lines,\n showAccount,\n );\n const rest = tree.filter((node) => !RESOURCE_ENTITIES.has(node.entity) && node.entity !== \"campaign\");\n renderSection(\"Other\", rest, lines, showAccount);\n renderAdvisories(data, lines);\n\n return lines.join(\"\\n\");\n}\n","import { type GoogleDraftStageResponse, isCreateKind } from \"@baker/api/ads-google\";\nimport { cacheGet, cacheSet } from \"../cache.ts\";\nimport { loopWarnings } from \"../output.ts\";\n\n/**\n * Bulk work done as a loop of single commands — one `keywords update` per keyword, one\n * `negative-keywords remove` per term — is one request, one rate-limit hit and one tool call per row;\n * production saw 1,284 of them. The CLI cannot see the loop from inside one call, so it remembers the\n * last few single stages per chat and, once the same kind repeats, says how to do the rest in one call.\n */\n\nexport interface StageStreak {\n kind: string;\n count: number;\n lastAt: number;\n}\n\n/** Singles further apart than this are separate decisions, not a loop. */\nconst STREAK_WINDOW_MS = 5 * 60_000;\n/** The streak length that reads as a loop. */\nconst STREAK_THRESHOLD = 5;\n\nexport function nextStageStreak(previous: StageStreak | undefined, kind: string, now: number): StageStreak {\n const continues = previous && previous.kind === kind && now - previous.lastAt <= STREAK_WINDOW_MS;\n return { kind, count: continues ? previous.count + 1 : 1, lastAt: now };\n}\n\n/** The one-call form of a kind, where a command has one beside `draft stage --file`. */\nconst BATCH_FORMS: Record<string, string> = {\n \"google.keyword.add\": \"`keywords add --file keywords.txt` (one term[:MATCH_TYPE] per line)\",\n \"google.keyword.update\":\n \"`keywords pause|resume <resource name> <resource name>…` (or --file, one per line) for status\",\n \"google.keyword.remove\": \"`draft stage --file` with one google.keyword.remove per target\",\n \"google.negativeKeyword.add\":\n \"`negative-keywords add --ad-group-id <id>,<id> --file terms.txt` (every term on every ad group)\",\n \"google.sharedSetMember.add\": \"`keyword-lists add --file terms.txt`\",\n \"google.sharedSetMember.remove\": '`keyword-lists remove --list-ref <id> --text \"a,b,c\"`',\n};\n\nexport function stageStreakHints(streak: StageStreak): string[] {\n if (streak.count < STREAK_THRESHOLD) {\n return [];\n }\n const form = BATCH_FORMS[streak.kind];\n return [\n `LOOP: that is ${streak.count} ${streak.kind} ops staged one command at a time. Stop looping — put every remaining change in one file and stage them in ONE call: \\`baker ads google draft stage --file ops.json --customer-id <id>\\` (a JSON array of {\"kind\",\"target\"?,\"payload\"?}, up to 500, any mix of kinds)${form ? `, or ${form}` : \"\"}. Fix staged ops together with \\`draft amend --file\\`.`,\n ];\n}\n\nconst STREAK_CACHE = \"stage-streak\";\n\n/** Record one single stage on this chat and return the nudge it earns, if any. Never throws. */\nexport function recordSingleStage(chatId: string, kind: string): string[] {\n try {\n const streak = nextStageStreak(cacheGet<StageStreak>(STREAK_CACHE, chatId)?.data, kind, Date.now());\n cacheSet(STREAK_CACHE, chatId, streak, STREAK_WINDOW_MS);\n const hints = stageStreakHints(streak);\n // Also on stderr: agents pipe each stage through a filter that keeps only `ok`, which drops the\n // hint from the JSON — 26 times in one Session. stderr reaches the agent past any such filter.\n for (const hint of hints) process.stderr.write(`${hint}\\n`);\n return hints;\n } catch {\n return [];\n }\n}\n\nconst TREE_CACHE = \"stage-tree\";\n\n/**\n * A single create (not an update merged into a staged one) that depends on a create staged earlier in this chat is a new campaign tree being\n * built one level at a time. Each level changes kind, so the LOOP streak never fires; this says once\n * per chat (per window) how to stage the rest in one call. Never throws.\n */\nexport function recordTreeStage(chatId: string, staged: GoogleDraftStageResponse): string[] {\n try {\n if (!staged.staged || staged.amended || !isCreateKind(staged.kind) || staged.dependsOn.length === 0) {\n return [];\n }\n if (cacheGet<boolean>(TREE_CACHE, chatId)?.data) {\n return [];\n }\n cacheSet(TREE_CACHE, chatId, true, STREAK_WINDOW_MS);\n return loopWarnings([\n `TREE: this ${staged.kind} hangs off a create staged earlier in this chat — a new campaign tree built one command per entity. Stage everything still to build (ad groups, keywords, ads, assets and their links) in ONE call: \\`baker ads google draft stage --file ops.json --customer-id <id>\\`, giving each create a name with \"as\": \"g_temp_<name>\" so later ops in the same file can point at it (refs staged earlier still work).`,\n ]);\n } catch {\n return [];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,CAAC,YAAa,OAAO,UAAU,aAAa,MAAM,OAAO,IAAK,SAAS,CAAC,CAAG,CAAC;AAAA,QAC1G;AACA,cAAM;AAAA,UACJ,SAAS,IAAI,CAAC,aAAa,EAAE,MAAM,YAAY,QAAQ,EAAE;AAAA,UACzD;AAAA,UACA,KAAK,SAAS;AAAA,QAChB;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;AASO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,IAAI;AACzD;AAAA,MACE;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,OAAO,KAAK;AACxB,MAAI,OAAO,MAAM,GAAG,KAAK,MAAM,KAAK,MAAM,MAAO,MAAM,KAAK,MAAM,KAAM;AACtE,wBAAoB,uEAAuE;AAAA,EAC7F;AACA,SAAO;AACT;","names":["changes"]}
@@ -153,7 +153,7 @@ function requireTarget(args, entity) {
153
153
  }
154
154
  return target;
155
155
  }
156
- function preflightOp(raw) {
156
+ function preflightOp(raw, at = "") {
157
157
  const preflight = metaDraftOpInputSchema.safeParse(raw);
158
158
  if (!preflight.success) {
159
159
  const fields = preflight.error.issues.map((issue) => ({ path: issue.path.join("."), message: issue.message }));
@@ -161,7 +161,7 @@ function preflightOp(raw) {
161
161
  ok: false,
162
162
  error: {
163
163
  code: "VALIDATION_ERROR",
164
- message: fields.map((field) => field.path ? `${field.path}: ${field.message}` : field.message).join("; "),
164
+ message: `${at}${fields.map((field) => field.path ? `${field.path}: ${field.message}` : field.message).join("; ")}`,
165
165
  fields,
166
166
  fix: payloadFix("meta-ads", metaDraftOpInputSchema, raw)
167
167
  }
@@ -182,7 +182,7 @@ async function stageOp(raw, extraHints = []) {
182
182
  }
183
183
  }
184
184
  async function stageOps(raws) {
185
- const ops = raws.map(preflightOp);
185
+ const ops = raws.map((raw) => preflightOp(raw));
186
186
  const chatId = requireChatId();
187
187
  const staged = [];
188
188
  for (const op of ops) {
@@ -223,8 +223,9 @@ export {
223
223
  upper,
224
224
  numberFlag,
225
225
  requireTarget,
226
+ preflightOp,
226
227
  stageOp,
227
228
  stageOps,
228
229
  stageStatusChange
229
230
  };
230
- //# sourceMappingURL=chunk-BRHYK4HQ.js.map
231
+ //# sourceMappingURL=chunk-G7Q43JEZ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/ads/meta/write-shared.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { type MetaDraftOpInput, type MetaDraftStageResponse, metaDraftOpInputSchema } from \"@baker/api/ads-meta\";\nimport { apiPost } from \"../../../client.ts\";\nimport { requireChatId } from \"../../../env.ts\";\nimport { repeatedValues } from \"../../../lib/repeatedFlags.ts\";\nimport { type CommandEffectDeclaration, payloadArg } from \"../../../schemas.ts\";\nimport { payloadFix } from \"../../capabilities/fix.ts\";\nimport { booleanWordPositionalError } from \"../boolean-word-positional.ts\";\nimport { adCopyHints } from \"../copy-hints.ts\";\nimport { withHints } from \"../hints.ts\";\nimport { writeJsonEnvelope } from \"../output.ts\";\nimport { handleMetaError, resolveAccountIdArg } from \"./shared.ts\";\n\n/**\n * Shared plumbing for the staged Meta write commands. Writes NEVER hit Meta\n * directly: every command stages an op against this chat's draft\n * (`/api/ads/meta/draft/stage`), the dashboard shows it as a pending Meta\n * change, and it applies when the chat is published.\n */\n\n/** `--file` for a command that stages one `kind` op; `baker schema` prints that op's payload shape. */\nexport function fileArg(kind: MetaDraftOpInput[\"kind\"], description: string) {\n return {\n file: payloadArg(\n {\n type: \"string\" as const,\n description: `${description} — run \\`baker schema\\` on this command for every field the payload takes`,\n },\n () => ({ union: metaDraftOpInputSchema, kind }),\n ),\n };\n}\n\n/** Backend account ids are bare numeric — strip the `act_` prefix resolveAccountIdArg adds. */\nexport async function bareAccountId(args: Record<string, unknown>): Promise<string> {\n return (await resolveAccountIdArg(args)).replace(/^act_/, \"\");\n}\n\n/** What every staged Meta write command does: one op onto this chat's draft, for the account it names or the only one. */\nexport const META_STAGED: CommandEffectDeclaration = {\n effect: \"stage\",\n routes: [\"POST /api/ads/meta/draft/stage\", \"GET /api/ads/meta/accounts\"],\n};\n\n/** A staged Meta write command, with the kinds of op it stages: what Baker's API offers it as (`@baker/api/agent-engine/found-ads-meta`). */\nexport function metaStages(...kinds: string[]): CommandEffectDeclaration {\n return { ...META_STAGED, stages: kinds };\n}\n\nexport function failWriteValidation(message: string): never {\n writeJsonEnvelope({ ok: false, error: { code: \"VALIDATION_ERROR\", message } });\n process.exit(1);\n}\n\n/** Deleting is permanent, so it only stages through `delete`, whose description carries that warning. */\nexport function refuseDeleteByUpdate(payload: Record<string, unknown>, group: \"campaigns\" | \"adsets\" | \"ads\"): void {\n if (payload.status === \"DELETED\") {\n failWriteValidation(\n `update does not delete — deleting is permanent. Use \\`baker ads meta ${group} delete <id>\\` if the user asked to delete; otherwise pause or archive.`,\n );\n }\n}\n\n/**\n * `--file`: a JSON file path, or the JSON itself when it starts with `{` — the shape Google's\n * `--file` already takes and the one an agent writes first for a short payload (a customer list of\n * a few people).\n */\nexport function loadJsonFileArg(path: unknown): Record<string, unknown> {\n if (typeof path !== \"string\" || path.length === 0) {\n return {};\n }\n const inline = /^\\s*\\{/.test(path);\n const source = inline ? \"inline JSON\" : path;\n try {\n const parsed = JSON.parse(inline ? path : readFileSync(path, \"utf8\")) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n failWriteValidation(`${source} must contain a JSON object`);\n }\n return parsed as Record<string, unknown>;\n } catch (err) {\n if (err instanceof SyntaxError) {\n failWriteValidation(`${source} is not valid JSON: ${err.message}`);\n }\n throw err;\n }\n}\n\n/** Flags override file keys — the file is the base, flags are the overrides. */\nexport function mergePayload(file: Record<string, unknown>, flags: Record<string, unknown>): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...file };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\nexport function parseMoneyFlag(\n amount: unknown,\n currency: unknown,\n flag: string,\n): { amount: string; currencyCode?: string } | undefined {\n if (amount === undefined || amount === null || amount === \"\") {\n return undefined;\n }\n if (currency === undefined || currency === null || currency === \"\") {\n // Meta ad accounts are single-currency — the backend fills it in.\n return { amount: String(amount) };\n }\n if (typeof currency !== \"string\" || currency.length !== 3) {\n failWriteValidation(`${flag} got an invalid --currency (expected a 3-letter code like USD)`);\n }\n return { amount: String(amount), currencyCode: currency.toUpperCase() };\n}\n\n/** Accepts ISO dates (2026-07-10), ISO datetimes, or epoch millis. */\nexport function parseDateFlag(value: unknown, flag: string): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const raw = String(value);\n if (/^\\d{10,}$/.test(raw)) {\n return Number(raw);\n }\n const parsed = Date.parse(raw);\n if (Number.isNaN(parsed)) {\n failWriteValidation(`${flag} must be an ISO date (2026-07-10) or epoch milliseconds`);\n }\n return parsed;\n}\n\n/** Split a comma-separated flag into a trimmed, non-empty array. */\nexport function listFlag(value: unknown): string[] | undefined {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n return undefined;\n }\n const items = value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\n/**\n * A list flag that may be repeated as well as comma-separated\n * (`--countries ES,FR --countries DE`). citty keeps only a repeated flag's last\n * value, so the values are read from the command line (`repeatedValues`).\n */\nexport function repeatedListFlag(\n rawArgs: readonly string[] | undefined,\n flag: string,\n parsed: unknown,\n): string[] | undefined {\n const items = repeatedValues(rawArgs, flag, parsed)\n .flatMap((value) => value.split(\",\"))\n .map((item) => item.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\nexport function upper(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value.toUpperCase() : undefined;\n}\n\nexport function numberFlag(value: unknown, flag: string): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const n = Number(value);\n if (!Number.isFinite(n)) {\n failWriteValidation(`${flag} must be a number`);\n }\n return n;\n}\n\n/**\n * Accepts whichever positional the command declared (`id`, `target`, `ref`) or the raw positional.\n *\n * `--flag false` is refused first: citty turns it into the flag set to TRUE plus a stray positional,\n * so on `campaigns duplicate 6123 --replace false` the copy stages AND the live original is staged\n * for pause — the opposite of what was typed, with an \"ok\" receipt. This is the only place on this\n * surface that reads positionals, and every target-taking command goes through it.\n */\nexport function requireTarget(args: Record<string, unknown>, entity: string): string {\n const inverted = booleanWordPositionalError(args, entity);\n if (inverted !== undefined) {\n failWriteValidation(inverted);\n }\n const positional = Array.isArray(args._) ? args._[0] : undefined;\n const target = args.id ?? args.target ?? args.ref ?? positional;\n if (typeof target !== \"string\" || target.length === 0) {\n failWriteValidation(`pass the ${entity} id as the positional argument`);\n }\n return target;\n}\n\ninterface StageEnvelope extends Record<string, unknown> {\n ok: true;\n data: MetaDraftStageResponse;\n}\n\n/**\n * Preflight-validates the op against the shared `@baker/api/ads-meta` contract\n * (same schema the backend enforces), then stages it. Prints the staged\n * envelope — ref, mode (always `live`: publishing reaches the real ad account),\n * summary, warnings.\n */\n/** The op parsed against the shared contract, or the validation envelope printed and the process ended. */\nfunction preflightOp(raw: Record<string, unknown>) {\n const preflight = metaDraftOpInputSchema.safeParse(raw);\n if (!preflight.success) {\n const fields = preflight.error.issues.map((issue) => ({ path: issue.path.join(\".\"), message: issue.message }));\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: fields.map((field) => (field.path ? `${field.path}: ${field.message}` : field.message)).join(\"; \"),\n fields,\n fix: payloadFix(\"meta-ads\", metaDraftOpInputSchema, raw),\n },\n });\n process.exit(1);\n }\n return preflight.data;\n}\n\nexport async function stageOp(raw: Record<string, unknown>, extraHints: readonly string[] = []): Promise<void> {\n const op = preflightOp(raw);\n try {\n const chatId = requireChatId();\n const response = await apiPost<StageEnvelope>(\"/api/ads/meta/draft/stage\", { chatId, op });\n const copyHints = await adCopyHints(op);\n writeJsonEnvelope(withHints(response, [...copyHints, ...extraHints]));\n } catch (err) {\n handleMetaError(err);\n }\n}\n\n/**\n * Stage several ops as one command and print one envelope: each staged op's\n * receipt, in order. Stops at the first refusal, which names the op it was —\n * the ones before it stay staged, and the envelope says which.\n */\nexport async function stageOps(raws: readonly Record<string, unknown>[]): Promise<void> {\n const ops = raws.map(preflightOp);\n const chatId = requireChatId();\n const staged: MetaDraftStageResponse[] = [];\n for (const op of ops) {\n try {\n const response = await apiPost<StageEnvelope>(\"/api/ads/meta/draft/stage\", { chatId, op });\n staged.push(response.data);\n } catch (err) {\n if (staged.length > 0) {\n process.stderr.write(`staged before the refusal: ${staged.map((entry) => entry.ref).join(\", \")}\\n`);\n }\n handleMetaError(err);\n }\n }\n writeJsonEnvelope({ ok: true, data: staged });\n}\n\nexport async function stageStatusChange(input: {\n kind: \"campaign.update\" | \"adSet.update\" | \"adCreative.update\" | \"ad.update\" | \"customAudience.update\";\n accountId: string;\n target: string;\n status: \"ACTIVE\" | \"PAUSED\" | \"ARCHIVED\" | \"DELETED\";\n}): Promise<void> {\n await stageOp({\n kind: input.kind,\n accountId: input.accountId,\n target: input.target,\n payload: { status: input.status },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAqBtB,SAAS,QAAQ,MAAgC,aAAqB;AAC3E,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,QACE,MAAM;AAAA,QACN,aAAa,GAAG,WAAW;AAAA,MAC7B;AAAA,MACA,OAAO,EAAE,OAAO,wBAAwB,KAAK;AAAA,IAC/C;AAAA,EACF;AACF;AAGA,eAAsB,cAAc,MAAgD;AAClF,UAAQ,MAAM,oBAAoB,IAAI,GAAG,QAAQ,SAAS,EAAE;AAC9D;AAGO,IAAM,cAAwC;AAAA,EACnD,QAAQ;AAAA,EACR,QAAQ,CAAC,kCAAkC,4BAA4B;AACzE;AAGO,SAAS,cAAc,OAA2C;AACvE,SAAO,EAAE,GAAG,aAAa,QAAQ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sBAAkB,UAAU,UAAU,CAAC,GAAG,WAAW,GAAG,UAAU,CAAC,CAAC;AAAA,EACtE,SAAS,KAAK;AACZ,oBAAgB,GAAG;AAAA,EACrB;AACF;AAOA,eAAsB,SAAS,MAAyD;AACtF,QAAM,MAAM,KAAK,IAAI,WAAW;AAChC,QAAM,SAAS,cAAc;AAC7B,QAAM,SAAmC,CAAC;AAC1C,aAAW,MAAM,KAAK;AACpB,QAAI;AACF,YAAM,WAAW,MAAM,QAAuB,6BAA6B,EAAE,QAAQ,GAAG,CAAC;AACzF,aAAO,KAAK,SAAS,IAAI;AAAA,IAC3B,SAAS,KAAK;AACZ,UAAI,OAAO,SAAS,GAAG;AACrB,gBAAQ,OAAO,MAAM,8BAA8B,OAAO,IAAI,CAAC,UAAU,MAAM,GAAG,EAAE,KAAK,IAAI,CAAC;AAAA,CAAI;AAAA,MACpG;AACA,sBAAgB,GAAG;AAAA,IACrB;AAAA,EACF;AACA,oBAAkB,EAAE,IAAI,MAAM,MAAM,OAAO,CAAC;AAC9C;AAEA,eAAsB,kBAAkB,OAKtB;AAChB,QAAM,QAAQ;AAAA,IACZ,MAAM,MAAM;AAAA,IACZ,WAAW,MAAM;AAAA,IACjB,QAAQ,MAAM;AAAA,IACd,SAAS,EAAE,QAAQ,MAAM,OAAO;AAAA,EAClC,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/commands/ads/meta/write-shared.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { type MetaDraftOpInput, type MetaDraftStageResponse, metaDraftOpInputSchema } from \"@baker/api/ads-meta\";\nimport { apiPost } from \"../../../client.ts\";\nimport { requireChatId } from \"../../../env.ts\";\nimport { repeatedValues } from \"../../../lib/repeatedFlags.ts\";\nimport { type CommandEffectDeclaration, payloadArg } from \"../../../schemas.ts\";\nimport { payloadFix } from \"../../capabilities/fix.ts\";\nimport { booleanWordPositionalError } from \"../boolean-word-positional.ts\";\nimport { adCopyHints } from \"../copy-hints.ts\";\nimport { withHints } from \"../hints.ts\";\nimport { writeJsonEnvelope } from \"../output.ts\";\nimport { handleMetaError, resolveAccountIdArg } from \"./shared.ts\";\n\n/**\n * Shared plumbing for the staged Meta write commands. Writes NEVER hit Meta\n * directly: every command stages an op against this chat's draft\n * (`/api/ads/meta/draft/stage`), the dashboard shows it as a pending Meta\n * change, and it applies when the chat is published.\n */\n\n/** `--file` for a command that stages one `kind` op; `baker schema` prints that op's payload shape. */\nexport function fileArg(kind: MetaDraftOpInput[\"kind\"], description: string) {\n return {\n file: payloadArg(\n {\n type: \"string\" as const,\n description: `${description} — run \\`baker schema\\` on this command for every field the payload takes`,\n },\n () => ({ union: metaDraftOpInputSchema, kind }),\n ),\n };\n}\n\n/** Backend account ids are bare numeric — strip the `act_` prefix resolveAccountIdArg adds. */\nexport async function bareAccountId(args: Record<string, unknown>): Promise<string> {\n return (await resolveAccountIdArg(args)).replace(/^act_/, \"\");\n}\n\n/** What every staged Meta write command does: one op onto this chat's draft, for the account it names or the only one. */\nexport const META_STAGED: CommandEffectDeclaration = {\n effect: \"stage\",\n routes: [\"POST /api/ads/meta/draft/stage\", \"GET /api/ads/meta/accounts\"],\n};\n\n/** A staged Meta write command, with the kinds of op it stages: what Baker's API offers it as (`@baker/api/agent-engine/found-ads-meta`). */\nexport function metaStages(...kinds: string[]): CommandEffectDeclaration {\n return { ...META_STAGED, stages: kinds };\n}\n\nexport function failWriteValidation(message: string): never {\n writeJsonEnvelope({ ok: false, error: { code: \"VALIDATION_ERROR\", message } });\n process.exit(1);\n}\n\n/** Deleting is permanent, so it only stages through `delete`, whose description carries that warning. */\nexport function refuseDeleteByUpdate(payload: Record<string, unknown>, group: \"campaigns\" | \"adsets\" | \"ads\"): void {\n if (payload.status === \"DELETED\") {\n failWriteValidation(\n `update does not delete — deleting is permanent. Use \\`baker ads meta ${group} delete <id>\\` if the user asked to delete; otherwise pause or archive.`,\n );\n }\n}\n\n/**\n * `--file`: a JSON file path, or the JSON itself when it starts with `{` — the shape Google's\n * `--file` already takes and the one an agent writes first for a short payload (a customer list of\n * a few people).\n */\nexport function loadJsonFileArg(path: unknown): Record<string, unknown> {\n if (typeof path !== \"string\" || path.length === 0) {\n return {};\n }\n const inline = /^\\s*\\{/.test(path);\n const source = inline ? \"inline JSON\" : path;\n try {\n const parsed = JSON.parse(inline ? path : readFileSync(path, \"utf8\")) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n failWriteValidation(`${source} must contain a JSON object`);\n }\n return parsed as Record<string, unknown>;\n } catch (err) {\n if (err instanceof SyntaxError) {\n failWriteValidation(`${source} is not valid JSON: ${err.message}`);\n }\n throw err;\n }\n}\n\n/** Flags override file keys — the file is the base, flags are the overrides. */\nexport function mergePayload(file: Record<string, unknown>, flags: Record<string, unknown>): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...file };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\nexport function parseMoneyFlag(\n amount: unknown,\n currency: unknown,\n flag: string,\n): { amount: string; currencyCode?: string } | undefined {\n if (amount === undefined || amount === null || amount === \"\") {\n return undefined;\n }\n if (currency === undefined || currency === null || currency === \"\") {\n // Meta ad accounts are single-currency — the backend fills it in.\n return { amount: String(amount) };\n }\n if (typeof currency !== \"string\" || currency.length !== 3) {\n failWriteValidation(`${flag} got an invalid --currency (expected a 3-letter code like USD)`);\n }\n return { amount: String(amount), currencyCode: currency.toUpperCase() };\n}\n\n/** Accepts ISO dates (2026-07-10), ISO datetimes, or epoch millis. */\nexport function parseDateFlag(value: unknown, flag: string): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const raw = String(value);\n if (/^\\d{10,}$/.test(raw)) {\n return Number(raw);\n }\n const parsed = Date.parse(raw);\n if (Number.isNaN(parsed)) {\n failWriteValidation(`${flag} must be an ISO date (2026-07-10) or epoch milliseconds`);\n }\n return parsed;\n}\n\n/** Split a comma-separated flag into a trimmed, non-empty array. */\nexport function listFlag(value: unknown): string[] | undefined {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n return undefined;\n }\n const items = value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\n/**\n * A list flag that may be repeated as well as comma-separated\n * (`--countries ES,FR --countries DE`). citty keeps only a repeated flag's last\n * value, so the values are read from the command line (`repeatedValues`).\n */\nexport function repeatedListFlag(\n rawArgs: readonly string[] | undefined,\n flag: string,\n parsed: unknown,\n): string[] | undefined {\n const items = repeatedValues(rawArgs, flag, parsed)\n .flatMap((value) => value.split(\",\"))\n .map((item) => item.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\nexport function upper(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value.toUpperCase() : undefined;\n}\n\nexport function numberFlag(value: unknown, flag: string): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const n = Number(value);\n if (!Number.isFinite(n)) {\n failWriteValidation(`${flag} must be a number`);\n }\n return n;\n}\n\n/**\n * Accepts whichever positional the command declared (`id`, `target`, `ref`) or the raw positional.\n *\n * `--flag false` is refused first: citty turns it into the flag set to TRUE plus a stray positional,\n * so on `campaigns duplicate 6123 --replace false` the copy stages AND the live original is staged\n * for pause — the opposite of what was typed, with an \"ok\" receipt. This is the only place on this\n * surface that reads positionals, and every target-taking command goes through it.\n */\nexport function requireTarget(args: Record<string, unknown>, entity: string): string {\n const inverted = booleanWordPositionalError(args, entity);\n if (inverted !== undefined) {\n failWriteValidation(inverted);\n }\n const positional = Array.isArray(args._) ? args._[0] : undefined;\n const target = args.id ?? args.target ?? args.ref ?? positional;\n if (typeof target !== \"string\" || target.length === 0) {\n failWriteValidation(`pass the ${entity} id as the positional argument`);\n }\n return target;\n}\n\ninterface StageEnvelope extends Record<string, unknown> {\n ok: true;\n data: MetaDraftStageResponse;\n}\n\n/**\n * Preflight-validates the op against the shared `@baker/api/ads-meta` contract\n * (same schema the backend enforces), then stages it. Prints the staged\n * envelope — ref, mode (always `live`: publishing reaches the real ad account),\n * summary, warnings.\n */\n/** The op parsed against the shared contract, or the validation envelope printed and the process ended. */\nexport function preflightOp(raw: Record<string, unknown>, at = \"\") {\n const preflight = metaDraftOpInputSchema.safeParse(raw);\n if (!preflight.success) {\n const fields = preflight.error.issues.map((issue) => ({ path: issue.path.join(\".\"), message: issue.message }));\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `${at}${fields.map((field) => (field.path ? `${field.path}: ${field.message}` : field.message)).join(\"; \")}`,\n fields,\n fix: payloadFix(\"meta-ads\", metaDraftOpInputSchema, raw),\n },\n });\n process.exit(1);\n }\n return preflight.data;\n}\n\nexport async function stageOp(raw: Record<string, unknown>, extraHints: readonly string[] = []): Promise<void> {\n const op = preflightOp(raw);\n try {\n const chatId = requireChatId();\n const response = await apiPost<StageEnvelope>(\"/api/ads/meta/draft/stage\", { chatId, op });\n const copyHints = await adCopyHints(op);\n writeJsonEnvelope(withHints(response, [...copyHints, ...extraHints]));\n } catch (err) {\n handleMetaError(err);\n }\n}\n\n/**\n * Stage several ops as one command and print one envelope: each staged op's\n * receipt, in order. Stops at the first refusal, which names the op it was —\n * the ones before it stay staged, and the envelope says which.\n */\nexport async function stageOps(raws: readonly Record<string, unknown>[]): Promise<void> {\n const ops = raws.map((raw) => preflightOp(raw));\n const chatId = requireChatId();\n const staged: MetaDraftStageResponse[] = [];\n for (const op of ops) {\n try {\n const response = await apiPost<StageEnvelope>(\"/api/ads/meta/draft/stage\", { chatId, op });\n staged.push(response.data);\n } catch (err) {\n if (staged.length > 0) {\n process.stderr.write(`staged before the refusal: ${staged.map((entry) => entry.ref).join(\", \")}\\n`);\n }\n handleMetaError(err);\n }\n }\n writeJsonEnvelope({ ok: true, data: staged });\n}\n\nexport async function stageStatusChange(input: {\n kind: \"campaign.update\" | \"adSet.update\" | \"adCreative.update\" | \"ad.update\" | \"customAudience.update\";\n accountId: string;\n target: string;\n status: \"ACTIVE\" | \"PAUSED\" | \"ARCHIVED\" | \"DELETED\";\n}): Promise<void> {\n await stageOp({\n kind: input.kind,\n accountId: input.accountId,\n target: input.target,\n payload: { status: input.status },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAqBtB,SAAS,QAAQ,MAAgC,aAAqB;AAC3E,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,QACE,MAAM;AAAA,QACN,aAAa,GAAG,WAAW;AAAA,MAC7B;AAAA,MACA,OAAO,EAAE,OAAO,wBAAwB,KAAK;AAAA,IAC/C;AAAA,EACF;AACF;AAGA,eAAsB,cAAc,MAAgD;AAClF,UAAQ,MAAM,oBAAoB,IAAI,GAAG,QAAQ,SAAS,EAAE;AAC9D;AAGO,IAAM,cAAwC;AAAA,EACnD,QAAQ;AAAA,EACR,QAAQ,CAAC,kCAAkC,4BAA4B;AACzE;AAGO,SAAS,cAAc,OAA2C;AACvE,SAAO,EAAE,GAAG,aAAa,QAAQ,MAAM;AACzC;AAEO,SAAS,oBAAoB,SAAwB;AAC1D,oBAAkB,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,oBAAoB,QAAQ,EAAE,CAAC;AAC7E,UAAQ,KAAK,CAAC;AAChB;AAGO,SAAS,qBAAqB,SAAkC,OAA6C;AAClH,MAAI,QAAQ,WAAW,WAAW;AAChC;AAAA,MACE,6EAAwE,KAAK;AAAA,IAC/E;AAAA,EACF;AACF;AAOO,SAAS,gBAAgB,MAAwC;AACtE,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAAG;AACjD,WAAO,CAAC;AAAA,EACV;AACA,QAAM,SAAS,SAAS,KAAK,IAAI;AACjC,QAAM,SAAS,SAAS,gBAAgB;AACxC,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,SAAS,OAAO,aAAa,MAAM,MAAM,CAAC;AACpE,QAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,M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,CAAC;AAAA,CAAI;AAAA,MACpG;AACA,sBAAgB,GAAG;AAAA,IACrB;AAAA,EACF;AACA,oBAAkB,EAAE,IAAI,MAAM,MAAM,OAAO,CAAC;AAC9C;AAEA,eAAsB,kBAAkB,OAKtB;AAChB,QAAM,QAAQ;AAAA,IACZ,MAAM,MAAM;AAAA,IACZ,WAAW,MAAM;AAAA,IACjB,QAAQ,MAAM;AAAA,IACd,SAAS,EAAE,QAAQ,MAAM,OAAO;AAAA,EAClC,CAAC;AACH;","names":[]}
@@ -384,7 +384,9 @@ var sourcesResponseSchema = z2.strictObject({
384
384
  /** Only when the request carried `backfill`. */
385
385
  backfill: backfillResultSchema.optional(),
386
386
  /** What this chat has staged, when one is attached: applied at Publish, dropped with a discard. */
387
- staged: z2.array(stagedSourceOpSchema).optional()
387
+ staged: z2.array(stagedSourceOpSchema).optional(),
388
+ /** The source this request made or changed at once, by id: a write outside a chat, or an address inside one. */
389
+ applied: z2.string().optional()
388
390
  }),
389
391
  hints: z2.array(z2.string()).optional()
390
392
  });
@@ -393,4 +395,4 @@ export {
393
395
  hubspotDefaultMapping,
394
396
  hubspotTriggerInputSchema
395
397
  };
396
- //# sourceMappingURL=chunk-BX5AAH7T.js.map
398
+ //# sourceMappingURL=chunk-IDLSLJIM.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../api/src/event-sources/hubspot.ts","../../api/src/event-sources/wire.ts","../../api/src/event-sources/activecampaign.ts"],"sourcesContent":["/**\n * What a HubSpot event reads by default, spelled as the same templates an\n * address's mapping uses — so the sheet shows one table for both, and a row\n * can be repointed at any property, or typed.\n *\n * ## Why defaults and not a fixed read\n *\n * The read used to be hard-wired: email from `email`, the Google click from\n * `hs_google_click_id`, and nothing anybody could change. Real accounts keep\n * the email under `work_email`, the deal value under a custom number\n * property, and a click id under whatever the tracking template wrote. The\n * defaults are HubSpot's standard names, which is where most accounts keep\n * them; every row is a template a person or the agent can change, and the\n * picker is the account's own property list, read live — never this table.\n *\n * An empty stored mapping means these — the same rule as an address, where\n * empty means \"the guess\".\n *\n * ## Three objects, one spelling\n *\n * A mention names a property of the object watched: `{{email}}` on a\n * contact source, `{{amount}}` on a deal source, `{{hs_pipeline_stage}}` on\n * a lead source, `{{id}}` the record's own id on any of them. A deal or a\n * lead source also reads the contact its record is about, through the\n * `contact.` namespace: `{{contact.email}}`, `{{contact.id}}`. The namespace\n * is what keeps the objects' properties apart in one table, and it is\n * spelled the way the Forms builder spells a nested field.\n */\n\nimport type { SourceField } from \"./fields\";\nimport type { HubspotObject } from \"./hubspotTrigger\";\nimport { mentionOf } from \"./template\";\n\n/** The variable that is the record's own id rather than a property: `{{id}}`. */\nexport const HUBSPOT_CONTACT_ID_VARIABLE = \"id\";\n\n/** On a deal source, the associated contact's properties are read as `{{contact.<property>}}`. */\nexport const HUBSPOT_CONTACT_PREFIX = \"contact.\";\n\n/** The path for a property of a deal's contact: `contact.email`. */\nexport function contactPath(property: string): string {\n return `${HUBSPOT_CONTACT_PREFIX}${property}`;\n}\n\n/** The contact property a `contact.<property>` path names, or null for a path of the record itself. */\nexport function contactPropertyOf(path: string): string | null {\n return path.startsWith(HUBSPOT_CONTACT_PREFIX) ? path.slice(HUBSPOT_CONTACT_PREFIX.length) : null;\n}\n\n/** HubSpot's standard contact property behind each field, where one exists. */\nexport const HUBSPOT_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = {\n email: \"email\",\n phone: \"phone\",\n external_id: HUBSPOT_CONTACT_ID_VARIABLE,\n first_name: \"firstname\",\n last_name: \"lastname\",\n city: \"city\",\n postal_code: \"zip\",\n country: \"country\",\n gclid: \"hs_google_click_id\",\n fbclid: \"hs_facebook_click_id\",\n};\n\n/**\n * The person's rows read off the record's associated contact, for an object\n * that is about somebody rather than being them.\n */\nconst throughContact: Readonly<Partial<Record<SourceField, string>>> = Object.fromEntries(\n Object.entries(HUBSPOT_DEFAULT_PROPERTIES).map(([field, property]) => [field, contactPath(property)]),\n);\n\n/**\n * The same for a deal: the person is the deal's contact, the amount is the\n * deal's own — HubSpot keeps it as `amount` in `deal_currency_code`, on\n * every account, which is the one row a contact source could never fill by\n * default.\n */\nexport const HUBSPOT_DEAL_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = {\n ...throughContact,\n value: \"amount\",\n currency: \"deal_currency_code\",\n};\n\n/**\n * The same for a lead. A lead is an interest in somebody, not an amount: it\n * has no `amount` and no currency of its own, so the value rows stay empty\n * and the funnel counts the step rather than money. Anyone who keeps a figure\n * on a custom lead property can still point `value` at it by hand.\n */\nexport const HUBSPOT_LEAD_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = throughContact;\n\nconst DEFAULTS: Readonly<Record<HubspotObject, Readonly<Partial<Record<SourceField, string>>>>> = {\n contact: HUBSPOT_DEFAULT_PROPERTIES,\n deal: HUBSPOT_DEAL_DEFAULT_PROPERTIES,\n lead: HUBSPOT_LEAD_DEFAULT_PROPERTIES,\n};\n\n/** The mapping a HubSpot event starts with: its name as the event, the standard properties for the rest. */\nexport function hubspotDefaultMapping(\n sourceName: string,\n object: HubspotObject = \"contact\",\n): Partial<Record<SourceField, string>> {\n const mapping: Partial<Record<SourceField, string>> = { event_name: sourceName };\n for (const [field, property] of Object.entries(DEFAULTS[object])) {\n mapping[field as SourceField] = mentionOf(property);\n }\n return mapping;\n}\n\n/**\n * The mapping in force for a HubSpot event: what was saved, else the defaults.\n * Keyed by field, or by `properties.<key>` for an extra property of the event.\n */\nexport function hubspotMappingInForce(\n sourceName: string,\n stored: Readonly<Record<string, string>>,\n object: HubspotObject = \"contact\",\n): Record<string, string> {\n const explicit = Object.entries(stored).filter(([, template]) => template.trim() !== \"\");\n if (explicit.length > 0) return Object.fromEntries(explicit);\n return hubspotDefaultMapping(sourceName, object);\n}\n","/**\n * The contract between `baker analytics sources` and `POST /api/analytics/sources`,\n * and the address a source is given.\n *\n * One request shape with one optional operation in it, and every call answers\n * with the full list afterwards — the CLI never has to make a second request\n * to see what it just did, and the \"what arrived\" question is answered by the\n * same read that answers \"what exists\".\n */\nimport { z } from \"zod\";\nimport { REJECTION_MESSAGES, validateEventName } from \"../event-ingest/validation\";\nimport { ACTIVECAMPAIGN_WEBHOOK_STATES, activeCampaignEventsSchema } from \"./activecampaign\";\nimport { mappingRowProblem } from \"./fields\";\nimport {\n CONDITION_LOGICS,\n HUBSPOT_DEAL_CONTACTS,\n HUBSPOT_OBJECTS,\n HUBSPOT_PROPERTY_KINDS,\n type HubspotTriggerInput,\n onlyCondition,\n TRIGGER_CONDITIONS_MAX,\n triggerProblem,\n} from \"./hubspotTrigger\";\n\n/** Mirrors `EVENT_SOURCE_KINDS` / the status validator in the backend schema; this package must not depend on convex. */\nexport const SOURCE_KINDS = [\"webhook\", \"hubspot\", \"activecampaign\"] as const;\nexport type SourceKind = (typeof SOURCE_KINDS)[number];\nexport const SOURCE_STATUSES = [\"learning\", \"counting\", \"paused\"] as const;\nexport type SourceStatus = (typeof SOURCE_STATUSES)[number];\n\nexport const SOURCE_NAME_MAX = 80;\n\n/**\n * What a source may be called — which is the ingest door's own rule, because a\n * source's name IS the `event_name` every event it raises carries.\n *\n * Held here rather than at each door, and that is the whole point of it being\n * here. A name this refuses is not a bad label, it is a **source that can\n * never count anything**: every arrival is rejected `invalid_name`, the card\n * goes on reading \"Counting\", and the only trace is one red line per event on\n * a feed somebody has to think to open. That happened — a HubSpot source\n * called \"Matrícula Realizada\", refused for ever by a rule that was ASCII-only\n * — and the reason it could happen is that three doors took a name and none of\n * them knew the rule.\n *\n * `MAX_EVENT_NAME` is the same 80 as {@link SOURCE_NAME_MAX} and\n * `validateEventName` checks it, so the bound is stated once even though both\n * constants exist.\n */\nexport const sourceNameSchema = z\n .string()\n .trim()\n .min(1)\n .max(SOURCE_NAME_MAX)\n .refine((name) => validateEventName(name) === null, REJECTION_MESSAGES.invalid_name);\n\n/** Where a source's arrivals go: the token is the whole path after this. */\nexport const EVENT_SOURCE_PATH_PREFIX = \"/v1/sources/\";\n\n/**\n * The address to hand a tool, given the branded host published for this\n * environment — the same fallback rule as `eventIngestUrl`.\n */\nexport function eventSourceUrl(brandedUrl: string | undefined, convexSiteUrl: string, token: string): string {\n const base = (brandedUrl || convexSiteUrl).replace(/\\/$/, \"\");\n return `${base}${EVENT_SOURCE_PATH_PREFIX}${token}`;\n}\n\nconst sourceIdSchema = z.string().min(1);\n\n/**\n * Canonical field → template (`template.ts`): literal text with `{{path}}`\n * mentions, or a bare path. A `properties.<key>` row is an extra property of\n * the event (`fields.ts`). Anything else is refused so a typo cannot become a\n * silent no-op.\n */\nexport const sourceMappingSchema = z.record(z.string(), z.string().min(1)).superRefine((mapping, ctx) => {\n for (const row of Object.keys(mapping)) {\n const problem = mappingRowProblem(row);\n if (problem !== null) ctx.addIssue({ code: \"custom\", message: problem, path: [row] });\n }\n});\n\n/** ISO 4217, upper case: what `POST /v1/events` accepts as `currency`. */\nexport const currencyCodeSchema = z\n .string()\n .trim()\n .toUpperCase()\n .regex(/^[A-Z]{3}$/, \"A currency is a three-letter code, like EUR or USD.\");\n\n/** What a HubSpot source is a trigger on: a contact (the default), a deal or a lead. */\nexport const hubspotObjectSchema = z.enum(HUBSPOT_OBJECTS);\n/** For a deal: whose event it is — the deal's first contact, or every contact on it. */\nexport const hubspotDealContactsSchema = z.enum(HUBSPOT_DEAL_CONTACTS);\n\n/**\n * One condition of a HubSpot trigger — *when a contact's* (or *a deal's*)\n * [property] [operator] [values] (`hubspotTrigger.ts`).\n */\nexport const hubspotConditionInputSchema = z.strictObject({\n property: z.string().trim().min(1),\n /** One of the property's kind's operators (`baker hubspot contacts properties` lists them); `is` when unsaid. */\n operator: z.string().trim().min(1).default(\"is\"),\n /** As HubSpot spells them: an option's internal value, a number, a `YYYY-MM-DD`, `true`/`false`. None for an empty check, two for a between, several for a list. */\n values: z.array(z.string().trim().min(1)).max(50).default([]),\n});\n\nconst conditionLogicSchema = z.enum(CONDITION_LOGICS);\n\nconst conditionGroupInputSchema = z.strictObject({\n logic: conditionLogicSchema,\n conditions: z.array(hubspotConditionInputSchema).min(1).max(TRIGGER_CONDITIONS_MAX),\n});\n\nconst combinedInputSchema = z\n .strictObject({\n /** How the rows combine: `And` (every one) or `Or` (any one) — a Form's filter's \"Match AND / OR\". */\n logic: conditionLogicSchema.default(\"And\"),\n /** Conditions, and groups of conditions with their own logic, one level deep. */\n conditions: z\n .array(z.union([hubspotConditionInputSchema, conditionGroupInputSchema]))\n .min(1)\n .max(TRIGGER_CONDITIONS_MAX),\n })\n .superRefine((trigger, context) => {\n const problem = triggerProblem(trigger);\n if (problem !== null) context.addIssue({ code: \"custom\", message: problem });\n });\n\n/**\n * What a HubSpot source watches: one condition, or several combined — the\n * way a Form's filter combines them. A single condition is the short\n * spelling, and is read as a trigger of that one condition.\n */\nexport const hubspotTriggerInputSchema = z\n .union([combinedInputSchema, hubspotConditionInputSchema])\n .transform((input): HubspotTriggerInput => (\"conditions\" in input ? input : onlyCondition(input)));\n\nconst hubspotConditionSchema = hubspotConditionInputSchema.extend({\n propertyLabel: z.string(),\n kind: z.enum(HUBSPOT_PROPERTY_KINDS),\n /** A select that holds several values at once (`a;b`); decides what HubSpot may filter on. */\n multiple: z.boolean().optional(),\n valueLabels: z.array(z.string()),\n});\n\nconst hubspotTriggerFields = {\n logic: conditionLogicSchema,\n conditions: z.array(\n z.union([\n hubspotConditionSchema,\n z.strictObject({ logic: conditionLogicSchema, conditions: z.array(hubspotConditionSchema) }),\n ]),\n ),\n};\n\n/** The trigger as stored on a source: every condition resolved, and on its object. */\nexport const hubspotWatchSchema = z.strictObject({\n ...hubspotTriggerFields,\n object: hubspotObjectSchema,\n contacts: hubspotDealContactsSchema.optional(),\n});\nexport type HubspotWatchView = z.infer<typeof hubspotWatchSchema>;\n\n/** A sample record as the preview shows it: its id and the properties it holds, empty ones dropped. */\nconst sampleRecordSchema = z.strictObject({ id: z.string(), properties: z.record(z.string(), z.string()) });\n\n/** What a HubSpot event would count today, asked before it is made: the trigger and the properties to read off the sample. */\nexport const hubspotPreviewRequestSchema = z.strictObject({\n object: hubspotObjectSchema.default(\"contact\"),\n trigger: hubspotTriggerInputSchema,\n /** Property names to read off the sample; `id` is always there. On a deal or a lead, `contact.<name>` reads its first contact. */\n properties: z.array(z.string().trim().min(1)).max(60).optional(),\n /** The record to draw the preview from — an id, or text to search (an email or a name for a contact, a deal's or a lead's name). The one most recently at the trigger when unsaid. */\n contact: z.string().trim().min(1).max(200).optional(),\n /** A total for each value of the trigger's one dropdown `is` condition, beside the combined one — sizing a funnel in one call. */\n breakdown: z.boolean().optional(),\n});\nexport type HubspotPreviewRequest = z.infer<typeof hubspotPreviewRequestSchema>;\n\nexport const hubspotPreviewSchema = z.strictObject({\n /** Records satisfying the trigger today — the ones that will NOT be counted. */\n total: z.number(),\n /** False when the trigger has more combinations than HubSpot's search takes, so `total` is only near. */\n exact: z.boolean().optional(),\n /**\n * The sample record the trigger is on, with the properties asked for and\n * the contacts behind it, first first; none when nothing fits.\n *\n * One field rather than one per object: a contact source's record *is* the\n * person and its `contacts` is empty, while a deal's and a lead's carry the\n * people the event is about. Three parallel nullable fields, exactly one of\n * them ever set, would say the same thing and let a caller read the wrong one.\n */\n record: sampleRecordSchema.extend({ contacts: z.array(sampleRecordSchema) }).nullable(),\n /** Only on a `breakdown`: each value of the condition with how many records are at it today, in the order asked. */\n counts: z.array(z.strictObject({ value: z.string(), total: z.number() })).optional(),\n});\nexport type HubspotPreview = z.infer<typeof hubspotPreviewSchema>;\n\nexport const sourcesRequestSchema = z.strictObject({\n /** The company's own server door: made once, `counting` from the start, the same address for ever after. */\n server: z.strictObject({}).optional(),\n create: z.strictObject({ name: sourceNameSchema }).optional(),\n /** A HubSpot event: read every five minutes, counting from now. The labels are looked up server-side. */\n createHubspot: z\n .strictObject({\n name: sourceNameSchema.optional(),\n /** A contact, a deal or a lead. A deal's and a lead's event is about its contact, read through `contact.<property>` rows. */\n object: hubspotObjectSchema.default(\"contact\"),\n trigger: hubspotTriggerInputSchema,\n /** On a deal: the deal's first contact (the default), or every contact on it, each its own event. */\n contacts: hubspotDealContactsSchema.optional(),\n /** Rows to read off the record, over the defaults; the same table `map` writes. */\n mapping: sourceMappingSchema.optional(),\n /** A number property on the record to read as the amount; needs `currency` beside it. Sugar over the mapping's `value` and `currency` rows. */\n amountProperty: z.string().trim().min(1).optional(),\n currency: currencyCodeSchema.optional(),\n })\n .optional(),\n /**\n * An ActiveCampaign source: ActiveCampaign's own webhook, made on the\n * account when this is applied, sending the events picked here. Each raises\n * `activecampaign.<type>` and counts from then on.\n */\n createActiveCampaign: z\n .strictObject({\n name: sourceNameSchema.optional(),\n /** ActiveCampaign's event names (`subscribe`, `deal_update`, …); the lead and deal moments when unsaid. */\n events: activeCampaignEventsSchema.optional(),\n /** Which connection, when the company has more than one. */\n account: z.string().trim().min(1).optional(),\n })\n .optional(),\n /** Change what a HubSpot event watches. It counts from now on under the new trigger; the rows stay. The object cannot change: the rows read it. */\n setTrigger: z\n .strictObject({\n sourceId: sourceIdSchema,\n trigger: hubspotTriggerInputSchema,\n contacts: hubspotDealContactsSchema.optional(),\n })\n .optional(),\n /** Ask HubSpot what a trigger would count today, and read one real record, without making anything. */\n preview: hubspotPreviewRequestSchema.optional(),\n /** Change where a HubSpot-read source takes its amount from; no `amountProperty` clears it. Sugar over `map`. */\n setAmount: z\n .strictObject({\n sourceId: sourceIdSchema,\n amountProperty: z.string().trim().min(1).optional(),\n currency: currencyCodeSchema.optional(),\n })\n .optional(),\n /**\n * Count a HubSpot event's history: every moment its trigger came to hold\n * since `since`, read out of HubSpot's own property history.\n *\n * Not the thing a source deliberately refuses to do. A source never\n * backfills the **present state** — somebody who already satisfies a\n * condition is not an event today — and this reports only moments HubSpot\n * has a timestamp for, so nothing is invented. Dry unless `write`.\n */\n backfill: z\n .strictObject({\n sourceId: sourceIdSchema,\n /** ISO instant, or Unix milliseconds. Bounded by the 400 days the store keeps. */\n since: z.union([z.string().trim().min(1), z.number()]),\n /**\n * Where a capped run carries on from: only records last changed at or\n * before this instant are read.\n *\n * The **read** is what it bounds, never the history. Records are chosen\n * most-recently-changed first, so a run that reaches its cap has covered\n * the newest of them and the rest are the ones nearest `since` — which\n * no shorter window can reach, because shortening one only drops\n * candidates from the old end and hands back the same newest records\n * again. `reachedBack` is the value to pass here, and the moments each\n * record is then judged on are still the whole of `since` to now.\n */\n before: z.union([z.string().trim().min(1), z.number()]).optional(),\n /** Without it, nothing is counted and the answer says what would be. */\n write: z.boolean().optional(),\n })\n .optional(),\n map: z.strictObject({ sourceId: sourceIdSchema, mapping: sourceMappingSchema }).optional(),\n pause: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n resume: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n remove: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n});\nexport type SourcesRequest = z.infer<typeof sourcesRequestSchema>;\n/** The request as a caller writes it, before the schema fills its defaults — what the CLI builds. */\nexport type SourcesRequestInput = z.input<typeof sourcesRequestSchema>;\n\n/** A delivery that arrived and was refused — mirrors `sourceRefusalValidator` in the backend schema. */\nexport const sourceRefusalSchema = z.strictObject({\n at: z.number(),\n count: z.number(),\n code: z.string(),\n reason: z.string(),\n});\n\nexport const detectedFieldSchema = z.strictObject({\n path: z.string(),\n confidence: z.enum([\"key\", \"value\"]),\n});\n\n/** Whether HubSpot's journal is being told to keep the changes a source watches. */\nexport const HUBSPOT_LISTENING_STATES = [\"listening\", \"not_configured\", \"failed\"] as const;\nexport type HubspotListeningState = (typeof HUBSPOT_LISTENING_STATES)[number];\n\nexport const sourceViewSchema = z.strictObject({\n id: z.string(),\n kind: z.enum(SOURCE_KINDS),\n name: z.string(),\n status: z.enum(SOURCE_STATUSES),\n /** The address a tool posts to. A HubSpot source has none: Baker calls HubSpot. */\n url: z.string().optional(),\n /** What a HubSpot source watches, and on which object. */\n hubspot: hubspotWatchSchema.optional(),\n /**\n * What an ActiveCampaign source listens to, and whether ActiveCampaign has\n * the webhook that sends it: `listening` once it is made, `not_configured`\n * until then, `failed` when ActiveCampaign refused it — `detail` says why.\n */\n activecampaign: z\n .strictObject({\n events: z.array(z.string()),\n webhook: z.strictObject({ state: z.enum(ACTIVECAMPAIGN_WEBHOOK_STATES), detail: z.string().optional() }),\n })\n .optional(),\n /** A HubSpot source counts changes from here on; one HubSpot reports from before it is dropped. Moves when the trigger changes. */\n countingSince: z.number().optional(),\n /**\n * Whether HubSpot is keeping this source's changes for Baker, as last\n * checked: `listening` when the app's journal subscription on the account\n * names the property; `not_configured` when the app has not been told yet\n * (or cannot be, with no credentials); `failed` when HubSpot refused the\n * subscription. `detail` says what to do.\n */\n listening: z.strictObject({ state: z.enum(HUBSPOT_LISTENING_STATES), detail: z.string().optional() }).optional(),\n /** Why the last delivery could not be counted, in product words; absent when the last one was. */\n lastError: z.string().optional(),\n lastArrivalAt: z.number().optional(),\n /**\n * What its last delivery **refused, event by event** — which `lastError` is\n * not and `lastArrivalAt` cannot be. A source refusing everything it\n * receives has no arrival and no read failure, so without this it reads as\n * one nobody has sent anything to. `refusalWords` turns it into the\n * sentence a person is shown. Cleared by the next delivery that counts.\n */\n lastRefusal: sourceRefusalSchema.optional(),\n /** The first send, masked, while learning. Kept once confirmed. */\n sample: z.strictObject({ receivedAt: z.number(), body: z.string() }).optional(),\n /** Field → template; empty means the guess (an address) or the defaults (a HubSpot read). */\n mapping: z.record(z.string(), z.string()),\n /** The guess over the sample, for the sheet to prefill and the CLI to suggest. */\n detected: z.record(z.string(), detectedFieldSchema).optional(),\n /** Every path the sample's first item holds, with its masked value — what the picker offers. */\n paths: z.array(z.strictObject({ path: z.string(), value: z.string() })).optional(),\n /** `baker` when the sample already parses as the `POST /v1/events` contract and needs no mapping. */\n format: z.enum([\"baker\", \"foreign\"]).optional(),\n});\nexport type SourceView = z.infer<typeof sourceViewSchema>;\n\n/**\n * One change to the company's sources, staged inside a chat and applied when\n * it is published. `ref` is the source's id, or a `src_temp_*` for one the\n * chat makes.\n */\nexport const stagedSourceOpSchema = z.strictObject({\n kind: z.enum([\"create\", \"setTrigger\", \"map\", \"status\", \"remove\"]),\n ref: z.string(),\n name: z.string(),\n summary: z.string(),\n /** On a create: what the source will watch and read. */\n hubspot: hubspotWatchSchema.optional(),\n /** On an ActiveCampaign create: the events its webhook will send. */\n activecampaign: z.strictObject({ events: z.array(z.string()) }).optional(),\n mapping: z.record(z.string(), z.string()).optional(),\n status: z.enum([\"paused\", \"counting\"]).optional(),\n});\nexport type StagedSourceOp = z.infer<typeof stagedSourceOpSchema>;\n\n/** What a backfill found, and — on a `write` run — what became of it. */\nexport const backfillResultSchema = z.strictObject({\n sourceId: z.string(),\n name: z.string(),\n since: z.number(),\n /** Records whose history was read. */\n examined: z.number(),\n /** Moments the trigger came to hold, across them. */\n entries: z.number(),\n /** Of those, already counted — the journal got there first, or a previous run did. */\n alreadyCounted: z.number(),\n /** What a `write` run would hand over, or did. */\n pending: z.number(),\n /** Whether the read stopped at its cap; {@link BackfillResult.reachedBack} is where to carry on from. */\n capped: z.boolean(),\n /**\n * How far back the read got: the instant the oldest record it examined was\n * last changed. Only on a capped run, and it is the next run's `before`.\n */\n reachedBack: z.number().optional(),\n counted: z.number().optional(),\n refused: z.number().optional(),\n refusedReason: z.string().optional(),\n});\nexport type BackfillResult = z.infer<typeof backfillResultSchema>;\n\nexport const sourcesResponseSchema = z.strictObject({\n ok: z.literal(true),\n data: z.strictObject({\n sources: z.array(sourceViewSchema),\n /** Only when the request carried `preview`. */\n preview: hubspotPreviewSchema.optional(),\n /** Only when the request carried `backfill`. */\n backfill: backfillResultSchema.optional(),\n /** What this chat has staged, when one is attached: applied at Publish, dropped with a discard. */\n staged: z.array(stagedSourceOpSchema).optional(),\n }),\n hints: z.array(z.string()).optional(),\n});\nexport type SourcesResponse = z.infer<typeof sourcesResponseSchema>;\n","/**\n * What an ActiveCampaign source can listen to: ActiveCampaign's own webhook\n * events, and the event name each one raises in Baker.\n *\n * The list is ActiveCampaign's, read from `GET /api/3/webhook/events` — an\n * account answers with exactly these 27 — and the words are ours, for the\n * picker and the change list. Every event a source raises is called\n * `activecampaign.<type>`, whatever the source is called, so a scheduled agent\n * narrowed to `activecampaign.deal_update` runs for any connected account and\n * `properties.baker_source` says which source it came through.\n */\nimport { z } from \"zod\";\n\nexport const ACTIVECAMPAIGN_WEBHOOK_EVENTS = {\n subscribe: \"A contact subscribes to a list\",\n unsubscribe: \"A contact unsubscribes\",\n update: \"A contact's details change\",\n contact_tag_added: \"A tag is added to a contact\",\n contact_tag_removed: \"A tag is removed from a contact\",\n subscriber_note: \"A note is added to a contact\",\n contact_task_add: \"A task is added to a contact\",\n sent: \"A campaign starts sending\",\n open: \"A contact opens a campaign\",\n click: \"A contact clicks a link in a campaign\",\n reply: \"A contact replies to a campaign\",\n forward: \"A contact forwards a campaign\",\n share: \"A contact shares a campaign\",\n bounce: \"A campaign email bounces\",\n list_add: \"A list is created\",\n deal_add: \"A deal is created\",\n deal_update: \"A deal changes\",\n deal_note_add: \"A note is added to a deal\",\n deal_task_add: \"A task is added to a deal\",\n deal_task_complete: \"A deal task is completed\",\n deal_pipeline_add: \"A pipeline is created\",\n deal_stage_add: \"A deal stage is created\",\n deal_tasktype_add: \"A deal task type is created\",\n account_add: \"An account is created\",\n account_update: \"An account changes\",\n account_contact_add: \"A contact is added to an account\",\n account_contact_update: \"A contact on an account changes\",\n} as const;\n\nexport type ActiveCampaignWebhookEvent = keyof typeof ACTIVECAMPAIGN_WEBHOOK_EVENTS;\n\nexport const ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES = Object.keys(\n ACTIVECAMPAIGN_WEBHOOK_EVENTS,\n) as readonly ActiveCampaignWebhookEvent[];\n\n/** Who may have caused an event: a contact, a user, an automation, the API — all of them, so nothing is missed. */\nexport const ACTIVECAMPAIGN_WEBHOOK_SOURCES = [\"public\", \"admin\", \"api\", \"system\"] as const;\n\n/** What a new source listens to when nobody says: the lead and deal moments a marketer asks about first. */\nexport const ACTIVECAMPAIGN_DEFAULT_EVENTS: readonly ActiveCampaignWebhookEvent[] = [\n \"subscribe\",\n \"contact_tag_added\",\n \"deal_add\",\n \"deal_update\",\n];\n\n/** The source's name when nobody gives one. */\nexport const ACTIVECAMPAIGN_SOURCE_NAME = \"ActiveCampaign\";\n\nconst EVENT_PREFIX = \"activecampaign.\";\n\n/** The Baker event an ActiveCampaign webhook event raises: `subscribe` → `activecampaign.subscribe`. */\nexport function activeCampaignEventName(type: string): string {\n return `${EVENT_PREFIX}${type}`;\n}\n\n/** The ActiveCampaign event behind a Baker event name, or null when it is not one. */\nexport function activeCampaignEventOf(eventName: string): ActiveCampaignWebhookEvent | null {\n if (!eventName.startsWith(EVENT_PREFIX)) return null;\n const type = eventName.slice(EVENT_PREFIX.length);\n return type in ACTIVECAMPAIGN_WEBHOOK_EVENTS ? (type as ActiveCampaignWebhookEvent) : null;\n}\n\n/** The words for one event, falling back to ActiveCampaign's own name for one this list does not know. */\nexport function activeCampaignEventLabel(type: string): string {\n return type in ACTIVECAMPAIGN_WEBHOOK_EVENTS\n ? ACTIVECAMPAIGN_WEBHOOK_EVENTS[type as ActiveCampaignWebhookEvent]\n : type;\n}\n\n/**\n * The events a source listens to, as the CLI and the dashboard hand them in:\n * ActiveCampaign's names, or Baker's `activecampaign.<type>` spelling of them,\n * deduplicated, in the catalogue's order.\n */\nexport const activeCampaignEventsSchema = z\n .array(z.string().trim().min(1))\n .min(1, \"Pick at least one ActiveCampaign event to listen to.\")\n .max(ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.length)\n .transform((raw, ctx) => {\n const picked = new Set<ActiveCampaignWebhookEvent>();\n for (const item of raw) {\n const type = activeCampaignEventOf(item) ?? (item in ACTIVECAMPAIGN_WEBHOOK_EVENTS ? item : null);\n if (type === null) {\n ctx.addIssue({\n code: \"custom\",\n message: `\"${item}\" is not an ActiveCampaign event. Pick from: ${ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.join(\", \")}.`,\n });\n return z.NEVER;\n }\n picked.add(type as ActiveCampaignWebhookEvent);\n }\n return ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.filter((type) => picked.has(type));\n });\n\n/** Whether ActiveCampaign has the webhook that sends a source its events, as last checked. */\nexport const ACTIVECAMPAIGN_WEBHOOK_STATES = [\"listening\", \"not_configured\", \"failed\"] as const;\nexport type ActiveCampaignWebhookState = (typeof ACTIVECAMPAIGN_WEBHOOK_STATES)[number];\n"],"mappings":";;;;;;;;;;;;;;;;;AAkCO,IAAM,8BAA8B;AAGpC,IAAM,yBAAyB;AAG/B,SAAS,YAAY,UAA0B;AACpD,SAAO,GAAG,sBAAsB,GAAG,QAAQ;AAC7C;AAQO,IAAM,6BAA6E;AAAA,EACxF,OAAO;AAAA,EACP,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AACV;AAMA,IAAM,iBAAiE,OAAO;AAAA,EAC5E,OAAO,QAAQ,0BAA0B,EAAE,IAAI,CAAC,CAAC,OAAO,QAAQ,MAAM,CAAC,OAAO,YAAY,QAAQ,CAAC,CAAC;AACtG;AAQO,IAAM,kCAAkF;AAAA,EAC7F,GAAG;AAAA,EACH,OAAO;AAAA,EACP,UAAU;AACZ;AAQO,IAAM,kCAAkF;AAE/F,IAAM,WAA4F;AAAA,EAChG,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AACR;AAGO,SAAS,sBACd,YACA,SAAwB,WACc;AACtC,QAAM,UAAgD,EAAE,YAAY,WAAW;AAC/E,aAAW,CAAC,OAAO,QAAQ,KAAK,OAAO,QAAQ,SAAS,MAAM,CAAC,GAAG;AAChE,YAAQ,KAAoB,IAAI,UAAU,QAAQ;AAAA,EACpD;AACA,SAAO;AACT;;;AClGA,SAAS,KAAAA,UAAS;;;ACElB,SAAS,SAAS;AAEX,IAAM,gCAAgC;AAAA,EAC3C,WAAW;AAAA,EACX,aAAa;AAAA,EACb,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AAOA,GAAE,OAAO,GAAGA,GAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACnD,QAAQA,GAAE,KAAK,CAAC,UAAU,UAAU,CAAC,EAAE,SAAS;AAClD,CAAC;AAIM,IAAM,uBAAuBA,GAAE,aAAa;AAAA,EACjD,UAAUA,GAAE,OAAO;AAAA,EACnB,MAAMA,GAAE,OAAO;AAAA,EACf,OAAOA,GAAE,OAAO;AAAA;AAAA,EAEhB,UAAUA,GAAE,OAAO;AAAA;AAAA,EAEnB,SAASA,GAAE,OAAO;AAAA;AAAA,EAElB,gBAAgBA,GAAE,OAAO;AAAA;AAAA,EAEzB,SAASA,GAAE,OAAO;AAAA;AAAA,EAElB,QAAQA,GAAE,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlB,aAAaA,GAAE,OAAO,EAAE,SAAS;AAAA,EACjC,SAASA,GAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,SAASA,GAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,eAAeA,GAAE,OAAO,EAAE,SAAS;AACrC,CAAC;AAGM,IAAM,wBAAwBA,GAAE,aAAa;AAAA,EAClD,IAAIA,GAAE,QAAQ,IAAI;AAAA,EAClB,MAAMA,GAAE,aAAa;AAAA,IACnB,SAASA,GAAE,MAAM,gBAAgB;AAAA;AAAA,IAEjC,SAAS,qBAAqB,SAAS;AAAA;AAAA,IAEvC,UAAU,qBAAqB,SAAS;AAAA;AAAA,IAExC,QAAQA,GAAE,MAAM,oBAAoB,EAAE,SAAS;AAAA,EACjD,CAAC;AAAA,EACD,OAAOA,GAAE,MAAMA,GAAE,OAAO,CAAC,EAAE,SAAS;AACtC,CAAC;","names":["z","z","z"]}
1
+ {"version":3,"sources":["../../api/src/event-sources/hubspot.ts","../../api/src/event-sources/wire.ts","../../api/src/event-sources/activecampaign.ts"],"sourcesContent":["/**\n * What a HubSpot event reads by default, spelled as the same templates an\n * address's mapping uses — so the sheet shows one table for both, and a row\n * can be repointed at any property, or typed.\n *\n * ## Why defaults and not a fixed read\n *\n * The read used to be hard-wired: email from `email`, the Google click from\n * `hs_google_click_id`, and nothing anybody could change. Real accounts keep\n * the email under `work_email`, the deal value under a custom number\n * property, and a click id under whatever the tracking template wrote. The\n * defaults are HubSpot's standard names, which is where most accounts keep\n * them; every row is a template a person or the agent can change, and the\n * picker is the account's own property list, read live — never this table.\n *\n * An empty stored mapping means these — the same rule as an address, where\n * empty means \"the guess\".\n *\n * ## Three objects, one spelling\n *\n * A mention names a property of the object watched: `{{email}}` on a\n * contact source, `{{amount}}` on a deal source, `{{hs_pipeline_stage}}` on\n * a lead source, `{{id}}` the record's own id on any of them. A deal or a\n * lead source also reads the contact its record is about, through the\n * `contact.` namespace: `{{contact.email}}`, `{{contact.id}}`. The namespace\n * is what keeps the objects' properties apart in one table, and it is\n * spelled the way the Forms builder spells a nested field.\n */\n\nimport type { SourceField } from \"./fields\";\nimport type { HubspotObject } from \"./hubspotTrigger\";\nimport { mentionOf } from \"./template\";\n\n/** The variable that is the record's own id rather than a property: `{{id}}`. */\nexport const HUBSPOT_CONTACT_ID_VARIABLE = \"id\";\n\n/** On a deal source, the associated contact's properties are read as `{{contact.<property>}}`. */\nexport const HUBSPOT_CONTACT_PREFIX = \"contact.\";\n\n/** The path for a property of a deal's contact: `contact.email`. */\nexport function contactPath(property: string): string {\n return `${HUBSPOT_CONTACT_PREFIX}${property}`;\n}\n\n/** The contact property a `contact.<property>` path names, or null for a path of the record itself. */\nexport function contactPropertyOf(path: string): string | null {\n return path.startsWith(HUBSPOT_CONTACT_PREFIX) ? path.slice(HUBSPOT_CONTACT_PREFIX.length) : null;\n}\n\n/** HubSpot's standard contact property behind each field, where one exists. */\nexport const HUBSPOT_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = {\n email: \"email\",\n phone: \"phone\",\n external_id: HUBSPOT_CONTACT_ID_VARIABLE,\n first_name: \"firstname\",\n last_name: \"lastname\",\n city: \"city\",\n postal_code: \"zip\",\n country: \"country\",\n gclid: \"hs_google_click_id\",\n fbclid: \"hs_facebook_click_id\",\n};\n\n/**\n * The person's rows read off the record's associated contact, for an object\n * that is about somebody rather than being them.\n */\nconst throughContact: Readonly<Partial<Record<SourceField, string>>> = Object.fromEntries(\n Object.entries(HUBSPOT_DEFAULT_PROPERTIES).map(([field, property]) => [field, contactPath(property)]),\n);\n\n/**\n * The same for a deal: the person is the deal's contact, the amount is the\n * deal's own — HubSpot keeps it as `amount` in `deal_currency_code`, on\n * every account, which is the one row a contact source could never fill by\n * default.\n */\nexport const HUBSPOT_DEAL_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = {\n ...throughContact,\n value: \"amount\",\n currency: \"deal_currency_code\",\n};\n\n/**\n * The same for a lead. A lead is an interest in somebody, not an amount: it\n * has no `amount` and no currency of its own, so the value rows stay empty\n * and the funnel counts the step rather than money. Anyone who keeps a figure\n * on a custom lead property can still point `value` at it by hand.\n */\nexport const HUBSPOT_LEAD_DEFAULT_PROPERTIES: Readonly<Partial<Record<SourceField, string>>> = throughContact;\n\nconst DEFAULTS: Readonly<Record<HubspotObject, Readonly<Partial<Record<SourceField, string>>>>> = {\n contact: HUBSPOT_DEFAULT_PROPERTIES,\n deal: HUBSPOT_DEAL_DEFAULT_PROPERTIES,\n lead: HUBSPOT_LEAD_DEFAULT_PROPERTIES,\n};\n\n/** The mapping a HubSpot event starts with: its name as the event, the standard properties for the rest. */\nexport function hubspotDefaultMapping(\n sourceName: string,\n object: HubspotObject = \"contact\",\n): Partial<Record<SourceField, string>> {\n const mapping: Partial<Record<SourceField, string>> = { event_name: sourceName };\n for (const [field, property] of Object.entries(DEFAULTS[object])) {\n mapping[field as SourceField] = mentionOf(property);\n }\n return mapping;\n}\n\n/**\n * The mapping in force for a HubSpot event: what was saved, else the defaults.\n * Keyed by field, or by `properties.<key>` for an extra property of the event.\n */\nexport function hubspotMappingInForce(\n sourceName: string,\n stored: Readonly<Record<string, string>>,\n object: HubspotObject = \"contact\",\n): Record<string, string> {\n const explicit = Object.entries(stored).filter(([, template]) => template.trim() !== \"\");\n if (explicit.length > 0) return Object.fromEntries(explicit);\n return hubspotDefaultMapping(sourceName, object);\n}\n","/**\n * The contract between `baker analytics sources` and `POST /api/analytics/sources`,\n * and the address a source is given.\n *\n * One request shape with one optional operation in it, and every call answers\n * with the full list afterwards — the CLI never has to make a second request\n * to see what it just did, and the \"what arrived\" question is answered by the\n * same read that answers \"what exists\".\n */\nimport { z } from \"zod\";\nimport { REJECTION_MESSAGES, validateEventName } from \"../event-ingest/validation\";\nimport { ACTIVECAMPAIGN_WEBHOOK_STATES, activeCampaignEventsSchema } from \"./activecampaign\";\nimport { mappingRowProblem } from \"./fields\";\nimport {\n CONDITION_LOGICS,\n HUBSPOT_DEAL_CONTACTS,\n HUBSPOT_OBJECTS,\n HUBSPOT_PROPERTY_KINDS,\n type HubspotTriggerInput,\n onlyCondition,\n TRIGGER_CONDITIONS_MAX,\n triggerProblem,\n} from \"./hubspotTrigger\";\n\n/** Mirrors `EVENT_SOURCE_KINDS` / the status validator in the backend schema; this package must not depend on convex. */\nexport const SOURCE_KINDS = [\"webhook\", \"hubspot\", \"activecampaign\"] as const;\nexport type SourceKind = (typeof SOURCE_KINDS)[number];\nexport const SOURCE_STATUSES = [\"learning\", \"counting\", \"paused\"] as const;\nexport type SourceStatus = (typeof SOURCE_STATUSES)[number];\n\nexport const SOURCE_NAME_MAX = 80;\n\n/**\n * What a source may be called — which is the ingest door's own rule, because a\n * source's name IS the `event_name` every event it raises carries.\n *\n * Held here rather than at each door, and that is the whole point of it being\n * here. A name this refuses is not a bad label, it is a **source that can\n * never count anything**: every arrival is rejected `invalid_name`, the card\n * goes on reading \"Counting\", and the only trace is one red line per event on\n * a feed somebody has to think to open. That happened — a HubSpot source\n * called \"Matrícula Realizada\", refused for ever by a rule that was ASCII-only\n * — and the reason it could happen is that three doors took a name and none of\n * them knew the rule.\n *\n * `MAX_EVENT_NAME` is the same 80 as {@link SOURCE_NAME_MAX} and\n * `validateEventName` checks it, so the bound is stated once even though both\n * constants exist.\n */\nexport const sourceNameSchema = z\n .string()\n .trim()\n .min(1)\n .max(SOURCE_NAME_MAX)\n .refine((name) => validateEventName(name) === null, REJECTION_MESSAGES.invalid_name);\n\n/** Where a source's arrivals go: the token is the whole path after this. */\nexport const EVENT_SOURCE_PATH_PREFIX = \"/v1/sources/\";\n\n/**\n * The address to hand a tool, given the branded host published for this\n * environment — the same fallback rule as `eventIngestUrl`.\n */\nexport function eventSourceUrl(brandedUrl: string | undefined, convexSiteUrl: string, token: string): string {\n const base = (brandedUrl || convexSiteUrl).replace(/\\/$/, \"\");\n return `${base}${EVENT_SOURCE_PATH_PREFIX}${token}`;\n}\n\nconst sourceIdSchema = z.string().min(1);\n\n/**\n * Canonical field → template (`template.ts`): literal text with `{{path}}`\n * mentions, or a bare path. A `properties.<key>` row is an extra property of\n * the event (`fields.ts`). Anything else is refused so a typo cannot become a\n * silent no-op.\n */\nexport const sourceMappingSchema = z.record(z.string(), z.string().min(1)).superRefine((mapping, ctx) => {\n for (const row of Object.keys(mapping)) {\n const problem = mappingRowProblem(row);\n if (problem !== null) ctx.addIssue({ code: \"custom\", message: problem, path: [row] });\n }\n});\n\n/** ISO 4217, upper case: what `POST /v1/events` accepts as `currency`. */\nexport const currencyCodeSchema = z\n .string()\n .trim()\n .toUpperCase()\n .regex(/^[A-Z]{3}$/, \"A currency is a three-letter code, like EUR or USD.\");\n\n/** What a HubSpot source is a trigger on: a contact (the default), a deal or a lead. */\nexport const hubspotObjectSchema = z.enum(HUBSPOT_OBJECTS);\n/** For a deal: whose event it is — the deal's first contact, or every contact on it. */\nexport const hubspotDealContactsSchema = z.enum(HUBSPOT_DEAL_CONTACTS);\n\n/**\n * One condition of a HubSpot trigger — *when a contact's* (or *a deal's*)\n * [property] [operator] [values] (`hubspotTrigger.ts`).\n */\nexport const hubspotConditionInputSchema = z.strictObject({\n property: z.string().trim().min(1),\n /** One of the property's kind's operators (`baker hubspot contacts properties` lists them); `is` when unsaid. */\n operator: z.string().trim().min(1).default(\"is\"),\n /** As HubSpot spells them: an option's internal value, a number, a `YYYY-MM-DD`, `true`/`false`. None for an empty check, two for a between, several for a list. */\n values: z.array(z.string().trim().min(1)).max(50).default([]),\n});\n\nconst conditionLogicSchema = z.enum(CONDITION_LOGICS);\n\nconst conditionGroupInputSchema = z.strictObject({\n logic: conditionLogicSchema,\n conditions: z.array(hubspotConditionInputSchema).min(1).max(TRIGGER_CONDITIONS_MAX),\n});\n\nconst combinedInputSchema = z\n .strictObject({\n /** How the rows combine: `And` (every one) or `Or` (any one) — a Form's filter's \"Match AND / OR\". */\n logic: conditionLogicSchema.default(\"And\"),\n /** Conditions, and groups of conditions with their own logic, one level deep. */\n conditions: z\n .array(z.union([hubspotConditionInputSchema, conditionGroupInputSchema]))\n .min(1)\n .max(TRIGGER_CONDITIONS_MAX),\n })\n .superRefine((trigger, context) => {\n const problem = triggerProblem(trigger);\n if (problem !== null) context.addIssue({ code: \"custom\", message: problem });\n });\n\n/**\n * What a HubSpot source watches: one condition, or several combined — the\n * way a Form's filter combines them. A single condition is the short\n * spelling, and is read as a trigger of that one condition.\n */\nexport const hubspotTriggerInputSchema = z\n .union([combinedInputSchema, hubspotConditionInputSchema])\n .transform((input): HubspotTriggerInput => (\"conditions\" in input ? input : onlyCondition(input)));\n\nconst hubspotConditionSchema = hubspotConditionInputSchema.extend({\n propertyLabel: z.string(),\n kind: z.enum(HUBSPOT_PROPERTY_KINDS),\n /** A select that holds several values at once (`a;b`); decides what HubSpot may filter on. */\n multiple: z.boolean().optional(),\n valueLabels: z.array(z.string()),\n});\n\nconst hubspotTriggerFields = {\n logic: conditionLogicSchema,\n conditions: z.array(\n z.union([\n hubspotConditionSchema,\n z.strictObject({ logic: conditionLogicSchema, conditions: z.array(hubspotConditionSchema) }),\n ]),\n ),\n};\n\n/** The trigger as stored on a source: every condition resolved, and on its object. */\nexport const hubspotWatchSchema = z.strictObject({\n ...hubspotTriggerFields,\n object: hubspotObjectSchema,\n contacts: hubspotDealContactsSchema.optional(),\n});\nexport type HubspotWatchView = z.infer<typeof hubspotWatchSchema>;\n\n/** A sample record as the preview shows it: its id and the properties it holds, empty ones dropped. */\nconst sampleRecordSchema = z.strictObject({ id: z.string(), properties: z.record(z.string(), z.string()) });\n\n/** What a HubSpot event would count today, asked before it is made: the trigger and the properties to read off the sample. */\nexport const hubspotPreviewRequestSchema = z.strictObject({\n object: hubspotObjectSchema.default(\"contact\"),\n trigger: hubspotTriggerInputSchema,\n /** Property names to read off the sample; `id` is always there. On a deal or a lead, `contact.<name>` reads its first contact. */\n properties: z.array(z.string().trim().min(1)).max(60).optional(),\n /** The record to draw the preview from — an id, or text to search (an email or a name for a contact, a deal's or a lead's name). The one most recently at the trigger when unsaid. */\n contact: z.string().trim().min(1).max(200).optional(),\n /** A total for each value of the trigger's one dropdown `is` condition, beside the combined one — sizing a funnel in one call. */\n breakdown: z.boolean().optional(),\n});\nexport type HubspotPreviewRequest = z.infer<typeof hubspotPreviewRequestSchema>;\n\nexport const hubspotPreviewSchema = z.strictObject({\n /** Records satisfying the trigger today — the ones that will NOT be counted. */\n total: z.number(),\n /** False when the trigger has more combinations than HubSpot's search takes, so `total` is only near. */\n exact: z.boolean().optional(),\n /**\n * The sample record the trigger is on, with the properties asked for and\n * the contacts behind it, first first; none when nothing fits.\n *\n * One field rather than one per object: a contact source's record *is* the\n * person and its `contacts` is empty, while a deal's and a lead's carry the\n * people the event is about. Three parallel nullable fields, exactly one of\n * them ever set, would say the same thing and let a caller read the wrong one.\n */\n record: sampleRecordSchema.extend({ contacts: z.array(sampleRecordSchema) }).nullable(),\n /** Only on a `breakdown`: each value of the condition with how many records are at it today, in the order asked. */\n counts: z.array(z.strictObject({ value: z.string(), total: z.number() })).optional(),\n});\nexport type HubspotPreview = z.infer<typeof hubspotPreviewSchema>;\n\nexport const sourcesRequestSchema = z.strictObject({\n /** The company's own server door: made once, `counting` from the start, the same address for ever after. */\n server: z.strictObject({}).optional(),\n create: z.strictObject({ name: sourceNameSchema }).optional(),\n /** A HubSpot event: read every five minutes, counting from now. The labels are looked up server-side. */\n createHubspot: z\n .strictObject({\n name: sourceNameSchema.optional(),\n /** A contact, a deal or a lead. A deal's and a lead's event is about its contact, read through `contact.<property>` rows. */\n object: hubspotObjectSchema.default(\"contact\"),\n trigger: hubspotTriggerInputSchema,\n /** On a deal: the deal's first contact (the default), or every contact on it, each its own event. */\n contacts: hubspotDealContactsSchema.optional(),\n /** Rows to read off the record, over the defaults; the same table `map` writes. */\n mapping: sourceMappingSchema.optional(),\n /** A number property on the record to read as the amount; needs `currency` beside it. Sugar over the mapping's `value` and `currency` rows. */\n amountProperty: z.string().trim().min(1).optional(),\n currency: currencyCodeSchema.optional(),\n })\n .optional(),\n /**\n * An ActiveCampaign source: ActiveCampaign's own webhook, made on the\n * account when this is applied, sending the events picked here. Each raises\n * `activecampaign.<type>` and counts from then on.\n */\n createActiveCampaign: z\n .strictObject({\n name: sourceNameSchema.optional(),\n /** ActiveCampaign's event names (`subscribe`, `deal_update`, …); the lead and deal moments when unsaid. */\n events: activeCampaignEventsSchema.optional(),\n /** Which connection, when the company has more than one. */\n account: z.string().trim().min(1).optional(),\n })\n .optional(),\n /** Change what a HubSpot event watches. It counts from now on under the new trigger; the rows stay. The object cannot change: the rows read it. */\n setTrigger: z\n .strictObject({\n sourceId: sourceIdSchema,\n trigger: hubspotTriggerInputSchema,\n contacts: hubspotDealContactsSchema.optional(),\n })\n .optional(),\n /** Ask HubSpot what a trigger would count today, and read one real record, without making anything. */\n preview: hubspotPreviewRequestSchema.optional(),\n /** Change where a HubSpot-read source takes its amount from; no `amountProperty` clears it. Sugar over `map`. */\n setAmount: z\n .strictObject({\n sourceId: sourceIdSchema,\n amountProperty: z.string().trim().min(1).optional(),\n currency: currencyCodeSchema.optional(),\n })\n .optional(),\n /**\n * Count a HubSpot event's history: every moment its trigger came to hold\n * since `since`, read out of HubSpot's own property history.\n *\n * Not the thing a source deliberately refuses to do. A source never\n * backfills the **present state** — somebody who already satisfies a\n * condition is not an event today — and this reports only moments HubSpot\n * has a timestamp for, so nothing is invented. Dry unless `write`.\n */\n backfill: z\n .strictObject({\n sourceId: sourceIdSchema,\n /** ISO instant, or Unix milliseconds. Bounded by the 400 days the store keeps. */\n since: z.union([z.string().trim().min(1), z.number()]),\n /**\n * Where a capped run carries on from: only records last changed at or\n * before this instant are read.\n *\n * The **read** is what it bounds, never the history. Records are chosen\n * most-recently-changed first, so a run that reaches its cap has covered\n * the newest of them and the rest are the ones nearest `since` — which\n * no shorter window can reach, because shortening one only drops\n * candidates from the old end and hands back the same newest records\n * again. `reachedBack` is the value to pass here, and the moments each\n * record is then judged on are still the whole of `since` to now.\n */\n before: z.union([z.string().trim().min(1), z.number()]).optional(),\n /** Without it, nothing is counted and the answer says what would be. */\n write: z.boolean().optional(),\n })\n .optional(),\n map: z.strictObject({ sourceId: sourceIdSchema, mapping: sourceMappingSchema }).optional(),\n pause: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n resume: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n remove: z.strictObject({ sourceId: sourceIdSchema }).optional(),\n});\nexport type SourcesRequest = z.infer<typeof sourcesRequestSchema>;\n/** The request as a caller writes it, before the schema fills its defaults — what the CLI builds. */\nexport type SourcesRequestInput = z.input<typeof sourcesRequestSchema>;\n\n/** A delivery that arrived and was refused — mirrors `sourceRefusalValidator` in the backend schema. */\nexport const sourceRefusalSchema = z.strictObject({\n at: z.number(),\n count: z.number(),\n code: z.string(),\n reason: z.string(),\n});\n\nexport const detectedFieldSchema = z.strictObject({\n path: z.string(),\n confidence: z.enum([\"key\", \"value\"]),\n});\n\n/** Whether HubSpot's journal is being told to keep the changes a source watches. */\nexport const HUBSPOT_LISTENING_STATES = [\"listening\", \"not_configured\", \"failed\"] as const;\nexport type HubspotListeningState = (typeof HUBSPOT_LISTENING_STATES)[number];\n\nexport const sourceViewSchema = z.strictObject({\n id: z.string(),\n kind: z.enum(SOURCE_KINDS),\n name: z.string(),\n status: z.enum(SOURCE_STATUSES),\n /** The address a tool posts to. A HubSpot source has none: Baker calls HubSpot. */\n url: z.string().optional(),\n /** What a HubSpot source watches, and on which object. */\n hubspot: hubspotWatchSchema.optional(),\n /**\n * What an ActiveCampaign source listens to, and whether ActiveCampaign has\n * the webhook that sends it: `listening` once it is made, `not_configured`\n * until then, `failed` when ActiveCampaign refused it — `detail` says why.\n */\n activecampaign: z\n .strictObject({\n events: z.array(z.string()),\n webhook: z.strictObject({ state: z.enum(ACTIVECAMPAIGN_WEBHOOK_STATES), detail: z.string().optional() }),\n })\n .optional(),\n /** A HubSpot source counts changes from here on; one HubSpot reports from before it is dropped. Moves when the trigger changes. */\n countingSince: z.number().optional(),\n /**\n * Whether HubSpot is keeping this source's changes for Baker, as last\n * checked: `listening` when the app's journal subscription on the account\n * names the property; `not_configured` when the app has not been told yet\n * (or cannot be, with no credentials); `failed` when HubSpot refused the\n * subscription. `detail` says what to do.\n */\n listening: z.strictObject({ state: z.enum(HUBSPOT_LISTENING_STATES), detail: z.string().optional() }).optional(),\n /** Why the last delivery could not be counted, in product words; absent when the last one was. */\n lastError: z.string().optional(),\n lastArrivalAt: z.number().optional(),\n /**\n * What its last delivery **refused, event by event** — which `lastError` is\n * not and `lastArrivalAt` cannot be. A source refusing everything it\n * receives has no arrival and no read failure, so without this it reads as\n * one nobody has sent anything to. `refusalWords` turns it into the\n * sentence a person is shown. Cleared by the next delivery that counts.\n */\n lastRefusal: sourceRefusalSchema.optional(),\n /** The first send, masked, while learning. Kept once confirmed. */\n sample: z.strictObject({ receivedAt: z.number(), body: z.string() }).optional(),\n /** Field → template; empty means the guess (an address) or the defaults (a HubSpot read). */\n mapping: z.record(z.string(), z.string()),\n /** The guess over the sample, for the sheet to prefill and the CLI to suggest. */\n detected: z.record(z.string(), detectedFieldSchema).optional(),\n /** Every path the sample's first item holds, with its masked value — what the picker offers. */\n paths: z.array(z.strictObject({ path: z.string(), value: z.string() })).optional(),\n /** `baker` when the sample already parses as the `POST /v1/events` contract and needs no mapping. */\n format: z.enum([\"baker\", \"foreign\"]).optional(),\n});\nexport type SourceView = z.infer<typeof sourceViewSchema>;\n\n/**\n * One change to the company's sources, staged inside a chat and applied when\n * it is published. `ref` is the source's id, or a `src_temp_*` for one the\n * chat makes.\n */\nexport const stagedSourceOpSchema = z.strictObject({\n kind: z.enum([\"create\", \"setTrigger\", \"map\", \"status\", \"remove\"]),\n ref: z.string(),\n name: z.string(),\n summary: z.string(),\n /** On a create: what the source will watch and read. */\n hubspot: hubspotWatchSchema.optional(),\n /** On an ActiveCampaign create: the events its webhook will send. */\n activecampaign: z.strictObject({ events: z.array(z.string()) }).optional(),\n mapping: z.record(z.string(), z.string()).optional(),\n status: z.enum([\"paused\", \"counting\"]).optional(),\n});\nexport type StagedSourceOp = z.infer<typeof stagedSourceOpSchema>;\n\n/** What a backfill found, and — on a `write` run — what became of it. */\nexport const backfillResultSchema = z.strictObject({\n sourceId: z.string(),\n name: z.string(),\n since: z.number(),\n /** Records whose history was read. */\n examined: z.number(),\n /** Moments the trigger came to hold, across them. */\n entries: z.number(),\n /** Of those, already counted — the journal got there first, or a previous run did. */\n alreadyCounted: z.number(),\n /** What a `write` run would hand over, or did. */\n pending: z.number(),\n /** Whether the read stopped at its cap; {@link BackfillResult.reachedBack} is where to carry on from. */\n capped: z.boolean(),\n /**\n * How far back the read got: the instant the oldest record it examined was\n * last changed. Only on a capped run, and it is the next run's `before`.\n */\n reachedBack: z.number().optional(),\n counted: z.number().optional(),\n refused: z.number().optional(),\n refusedReason: z.string().optional(),\n});\nexport type BackfillResult = z.infer<typeof backfillResultSchema>;\n\nexport const sourcesResponseSchema = z.strictObject({\n ok: z.literal(true),\n data: z.strictObject({\n sources: z.array(sourceViewSchema),\n /** Only when the request carried `preview`. */\n preview: hubspotPreviewSchema.optional(),\n /** Only when the request carried `backfill`. */\n backfill: backfillResultSchema.optional(),\n /** What this chat has staged, when one is attached: applied at Publish, dropped with a discard. */\n staged: z.array(stagedSourceOpSchema).optional(),\n /** The source this request made or changed at once, by id: a write outside a chat, or an address inside one. */\n applied: z.string().optional(),\n }),\n hints: z.array(z.string()).optional(),\n});\nexport type SourcesResponse = z.infer<typeof sourcesResponseSchema>;\n","/**\n * What an ActiveCampaign source can listen to: ActiveCampaign's own webhook\n * events, and the event name each one raises in Baker.\n *\n * The list is ActiveCampaign's, read from `GET /api/3/webhook/events` — an\n * account answers with exactly these 27 — and the words are ours, for the\n * picker and the change list. Every event a source raises is called\n * `activecampaign.<type>`, whatever the source is called, so a scheduled agent\n * narrowed to `activecampaign.deal_update` runs for any connected account and\n * `properties.baker_source` says which source it came through.\n */\nimport { z } from \"zod\";\n\nexport const ACTIVECAMPAIGN_WEBHOOK_EVENTS = {\n subscribe: \"A contact subscribes to a list\",\n unsubscribe: \"A contact unsubscribes\",\n update: \"A contact's details change\",\n contact_tag_added: \"A tag is added to a contact\",\n contact_tag_removed: \"A tag is removed from a contact\",\n subscriber_note: \"A note is added to a contact\",\n contact_task_add: \"A task is added to a contact\",\n sent: \"A campaign starts sending\",\n open: \"A contact opens a campaign\",\n click: \"A contact clicks a link in a campaign\",\n reply: \"A contact replies to a campaign\",\n forward: \"A contact forwards a campaign\",\n share: \"A contact shares a campaign\",\n bounce: \"A campaign email bounces\",\n list_add: \"A list is created\",\n deal_add: \"A deal is created\",\n deal_update: \"A deal changes\",\n deal_note_add: \"A note is added to a deal\",\n deal_task_add: \"A task is added to a deal\",\n deal_task_complete: \"A deal task is completed\",\n deal_pipeline_add: \"A pipeline is created\",\n deal_stage_add: \"A deal stage is created\",\n deal_tasktype_add: \"A deal task type is created\",\n account_add: \"An account is created\",\n account_update: \"An account changes\",\n account_contact_add: \"A contact is added to an account\",\n account_contact_update: \"A contact on an account changes\",\n} as const;\n\nexport type ActiveCampaignWebhookEvent = keyof typeof ACTIVECAMPAIGN_WEBHOOK_EVENTS;\n\nexport const ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES = Object.keys(\n ACTIVECAMPAIGN_WEBHOOK_EVENTS,\n) as readonly ActiveCampaignWebhookEvent[];\n\n/** Who may have caused an event: a contact, a user, an automation, the API — all of them, so nothing is missed. */\nexport const ACTIVECAMPAIGN_WEBHOOK_SOURCES = [\"public\", \"admin\", \"api\", \"system\"] as const;\n\n/** What a new source listens to when nobody says: the lead and deal moments a marketer asks about first. */\nexport const ACTIVECAMPAIGN_DEFAULT_EVENTS: readonly ActiveCampaignWebhookEvent[] = [\n \"subscribe\",\n \"contact_tag_added\",\n \"deal_add\",\n \"deal_update\",\n];\n\n/** The source's name when nobody gives one. */\nexport const ACTIVECAMPAIGN_SOURCE_NAME = \"ActiveCampaign\";\n\nconst EVENT_PREFIX = \"activecampaign.\";\n\n/** The Baker event an ActiveCampaign webhook event raises: `subscribe` → `activecampaign.subscribe`. */\nexport function activeCampaignEventName(type: string): string {\n return `${EVENT_PREFIX}${type}`;\n}\n\n/** The ActiveCampaign event behind a Baker event name, or null when it is not one. */\nexport function activeCampaignEventOf(eventName: string): ActiveCampaignWebhookEvent | null {\n if (!eventName.startsWith(EVENT_PREFIX)) return null;\n const type = eventName.slice(EVENT_PREFIX.length);\n return type in ACTIVECAMPAIGN_WEBHOOK_EVENTS ? (type as ActiveCampaignWebhookEvent) : null;\n}\n\n/** The words for one event, falling back to ActiveCampaign's own name for one this list does not know. */\nexport function activeCampaignEventLabel(type: string): string {\n return type in ACTIVECAMPAIGN_WEBHOOK_EVENTS\n ? ACTIVECAMPAIGN_WEBHOOK_EVENTS[type as ActiveCampaignWebhookEvent]\n : type;\n}\n\n/**\n * The events a source listens to, as the CLI and the dashboard hand them in:\n * ActiveCampaign's names, or Baker's `activecampaign.<type>` spelling of them,\n * deduplicated, in the catalogue's order.\n */\nexport const activeCampaignEventsSchema = z\n .array(z.string().trim().min(1))\n .min(1, \"Pick at least one ActiveCampaign event to listen to.\")\n .max(ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.length)\n .transform((raw, ctx) => {\n const picked = new Set<ActiveCampaignWebhookEvent>();\n for (const item of raw) {\n const type = activeCampaignEventOf(item) ?? (item in ACTIVECAMPAIGN_WEBHOOK_EVENTS ? item : null);\n if (type === null) {\n ctx.addIssue({\n code: \"custom\",\n message: `\"${item}\" is not an ActiveCampaign event. Pick from: ${ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.join(\", \")}.`,\n });\n return z.NEVER;\n }\n picked.add(type as ActiveCampaignWebhookEvent);\n }\n return ACTIVECAMPAIGN_WEBHOOK_EVENT_TYPES.filter((type) => picked.has(type));\n });\n\n/** Whether ActiveCampaign has the webhook that sends a source its events, as last checked. */\nexport const ACTIVECAMPAIGN_WEBHOOK_STATES = [\"listening\", \"not_configured\", \"failed\"] as const;\nexport type ActiveCampaignWebhookState = (typeof ACTIVECAMPAIGN_WEBHOOK_STATES)[number];\n"],"mappings":";;;;;;;;;;;;;;;;;AAkCO,IAAM,8BAA8B;AAGpC,IAAM,yBAAyB;AAG/B,SAAS,YAAY,UAA0B;AACpD,SAAO,GAAG,sBAAsB,GAAG,QAAQ;AAC7C;AAQO,IAAM,6BAA6E;AAAA,EACxF,OAAO;AAAA,EACP,OAAO;AAAA,EACP,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AACV;AAMA,IAAM,iBAAiE,OAAO;AAAA,EAC5E,OAAO,QAAQ,0BAA0B,EAAE,IAAI,CAAC,CAAC,OAAO,QAAQ,MAAM,CAAC,OAAO,YAAY,QAAQ,CAAC,CAAC;AACtG;AAQO,IAAM,kCAAkF;AAAA,EAC7F,GAAG;AAAA,EACH,OAAO;AAAA,EACP,UAAU;AACZ;AAQO,IAAM,kCAAkF;AAE/F,IAAM,WAA4F;AAAA,EAChG,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AACR;AAGO,SAAS,sBACd,YACA,SAAwB,WACc;A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AAS;AAAA;AAAA,IAE/C,SAASA,GAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,CAAC;AAAA,EACD,OAAOA,GAAE,MAAMA,GAAE,OAAO,CAAC,EAAE,SAAS;AACtC,CAAC;","names":["z","z","z"]}
@@ -2,7 +2,7 @@ import {
2
2
  failWriteValidation,
3
3
  parseDateFlag,
4
4
  parseMoneyFlag
5
- } from "./chunk-BRHYK4HQ.js";
5
+ } from "./chunk-G7Q43JEZ.js";
6
6
  import {
7
7
  repeatedValues
8
8
  } from "./chunk-ERSX3MKH.js";
@@ -284,4 +284,4 @@ export {
284
284
  clearFromFlags,
285
285
  clearArg
286
286
  };
287
- //# sourceMappingURL=chunk-ZGYIG6OM.js.map
287
+ //# sourceMappingURL=chunk-LUF2VYOK.js.map
@@ -0,0 +1,37 @@
1
+ import {
2
+ cacheGet,
3
+ cacheSet
4
+ } from "./chunk-7W5KGO5H.js";
5
+
6
+ // src/commands/ads/stage-guidance.ts
7
+ var GUIDANCE = /* @__PURE__ */ new Set();
8
+ function guidance(...hints) {
9
+ for (const hint of hints) GUIDANCE.add(hint);
10
+ return hints;
11
+ }
12
+ var GUIDANCE_CACHE = "stage-guidance";
13
+ var GUIDANCE_WINDOW_MS = 30 * 6e4;
14
+ function unsaidGuidance(chatId, hints) {
15
+ return hints.filter((hint) => {
16
+ if (!GUIDANCE.has(hint)) {
17
+ return true;
18
+ }
19
+ try {
20
+ const key = `${chatId}
21
+ ${hint}`;
22
+ if (cacheGet(GUIDANCE_CACHE, key)?.data) {
23
+ return false;
24
+ }
25
+ cacheSet(GUIDANCE_CACHE, key, true, GUIDANCE_WINDOW_MS);
26
+ return true;
27
+ } catch {
28
+ return true;
29
+ }
30
+ });
31
+ }
32
+
33
+ export {
34
+ guidance,
35
+ unsaidGuidance
36
+ };
37
+ //# sourceMappingURL=chunk-LVLAFUXQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/ads/stage-guidance.ts"],"sourcesContent":["import { cacheGet, cacheSet } from \"./cache.ts\";\n\n/** Every hint a command declares as guidance — the same text whatever was staged. */\nconst GUIDANCE = new Set<string>();\n\n/**\n * Declare a command's standing guidance: text that says the same thing on every call, unlike a\n * warning about the op just staged. It is said once in a chat (`unsaidGuidance`), not on every stage.\n */\nexport function guidance(...hints: string[]): string[] {\n for (const hint of hints) GUIDANCE.add(hint);\n return hints;\n}\n\nconst GUIDANCE_CACHE = \"stage-guidance\";\n/** How long a command's guidance stays said in a chat: a long build hears it again, a loop does not. */\nconst GUIDANCE_WINDOW_MS = 30 * 60_000;\n\n/**\n * The hints to print, less the guidance this chat was already given in the last half hour. The same\n * paragraph on every stage made one `assets attach` print 1,150 bytes for a 239-byte answer, so\n * agents grepped every stage down to a few lines — and cut the hints that mattered with it\n * (BAKER-390). A warning about the op itself is always printed. Never throws: without the cache,\n * everything is said.\n */\nexport function unsaidGuidance(chatId: string, hints: readonly string[]): string[] {\n return hints.filter((hint) => {\n if (!GUIDANCE.has(hint)) {\n return true;\n }\n try {\n const key = `${chatId}\\n${hint}`;\n if (cacheGet<boolean>(GUIDANCE_CACHE, key)?.data) {\n return false;\n }\n cacheSet(GUIDANCE_CACHE, key, true, GUIDANCE_WINDOW_MS);\n return true;\n } catch {\n return true;\n }\n });\n}\n"],"mappings":";;;;;;AAGA,IAAM,WAAW,oBAAI,IAAY;AAM1B,SAAS,YAAY,OAA2B;AACrD,aAAW,QAAQ,MAAO,UAAS,IAAI,IAAI;AAC3C,SAAO;AACT;AAEA,IAAM,iBAAiB;AAEvB,IAAM,qBAAqB,KAAK;AASzB,SAAS,eAAe,QAAgB,OAAoC;AACjF,SAAO,MAAM,OAAO,CAAC,SAAS;AAC5B,QAAI,CAAC,SAAS,IAAI,IAAI,GAAG;AACvB,aAAO;AAAA,IACT;AACA,QAAI;AACF,YAAM,MAAM,GAAG,MAAM;AAAA,EAAK,IAAI;AAC9B,UAAI,SAAkB,gBAAgB,GAAG,GAAG,MAAM;AAChD,eAAO;AAAA,MACT;AACA,eAAS,gBAAgB,KAAK,MAAM,kBAAkB;AACtD,aAAO;AAAA,IACT,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -5,7 +5,7 @@ import {
5
5
  requireTarget,
6
6
  stageOp,
7
7
  stageOps
8
- } from "./chunk-BRHYK4HQ.js";
8
+ } from "./chunk-G7Q43JEZ.js";
9
9
  import {
10
10
  repeatedValues
11
11
  } from "./chunk-ERSX3MKH.js";
@@ -216,4 +216,4 @@ export {
216
216
  labelsAttachCommand,
217
217
  labelsDetachCommand
218
218
  };
219
- //# sourceMappingURL=chunk-3F6AXSPB.js.map
219
+ //# sourceMappingURL=chunk-ZJUUAZKY.js.map