@koda-sl/baker-cli 0.879.0 → 0.881.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 (98) hide show
  1. package/README.md +5 -1
  2. package/dist/{account-6EJ22A7X.js → account-AIW3XGWG.js} +2 -2
  3. package/dist/{account-assets-ZY4UYCHQ.js → account-assets-FJFPB7KD.js} +54 -46
  4. package/dist/account-assets-FJFPB7KD.js.map +1 -0
  5. package/dist/{account-level-Z4Z5PUA6.js → account-level-CB6I4X5W.js} +4 -4
  6. package/dist/{accounts-JILEWVP6.js → accounts-2USPMXA2.js} +2 -2
  7. package/dist/{activities-JHKNRR3M.js → activities-DYI25TF4.js} +21 -12
  8. package/dist/activities-DYI25TF4.js.map +1 -0
  9. package/dist/{ads-7NUK2UOG.js → ads-G3N76HWA.js} +27 -19
  10. package/dist/ads-G3N76HWA.js.map +1 -0
  11. package/dist/{ads-SWRPUDVK.js → ads-WERB3QK5.js} +2 -2
  12. package/dist/{adsets-JF3CBKOU.js → adsets-2HV6TJJP.js} +48 -30
  13. package/dist/adsets-2HV6TJJP.js.map +1 -0
  14. package/dist/{asset-writes-HXFRHFWF.js → asset-writes-ZOVD5O5X.js} +4 -4
  15. package/dist/{audience-writes-PT6RLJAK.js → audience-writes-36E6ECON.js} +29 -15
  16. package/dist/audience-writes-36E6ECON.js.map +1 -0
  17. package/dist/{audiences-G3PRPIY4.js → audiences-65JSGH4L.js} +27 -15
  18. package/dist/audiences-65JSGH4L.js.map +1 -0
  19. package/dist/{businesses-3N6CTZ2Q.js → businesses-5AEHP23G.js} +2 -2
  20. package/dist/{campaigns-FN56B6B7.js → campaigns-PP3MFPJR.js} +29 -18
  21. package/dist/campaigns-PP3MFPJR.js.map +1 -0
  22. package/dist/{catalogs-N2I2GNHS.js → catalogs-UYYPZRFW.js} +3 -3
  23. package/dist/{chunk-SNQKL66G.js → chunk-3F6AXSPB.js} +2 -2
  24. package/dist/{chunk-6MFVGM3F.js → chunk-AMCW2IG7.js} +14 -3
  25. package/dist/chunk-AMCW2IG7.js.map +1 -0
  26. package/dist/{chunk-6XXKYTD5.js → chunk-BRHYK4HQ.js} +2 -2
  27. package/dist/{chunk-2W6ILA5Z.js → chunk-LDL5VBBD.js} +87 -8
  28. package/dist/chunk-LDL5VBBD.js.map +1 -0
  29. package/dist/{chunk-JV6O52V6.js → chunk-ZGYIG6OM.js} +2 -2
  30. package/dist/cli.js +1 -1
  31. package/dist/{copy-writes-YXVKXBQC.js → copy-writes-TEJRR2W2.js} +4 -4
  32. package/dist/{creatives-3AQ3EEUL.js → creatives-ZYY5OF5U.js} +32 -19
  33. package/dist/creatives-ZYY5OF5U.js.map +1 -0
  34. package/dist/{custom-conversions-XNYZOJYY.js → custom-conversions-YQPOB2IR.js} +27 -15
  35. package/dist/custom-conversions-YQPOB2IR.js.map +1 -0
  36. package/dist/{draft-3P2XHRWX.js → draft-OHAOBGVP.js} +2 -2
  37. package/dist/{insights-VD4QINO7.js → insights-PBJODKMY.js} +129 -28
  38. package/dist/insights-PBJODKMY.js.map +1 -0
  39. package/dist/{instant-experiences-KCAH5ONN.js → instant-experiences-YXH2AHFI.js} +3 -3
  40. package/dist/{leads-HU4GA6T4.js → leads-IGOXMIEW.js} +3 -3
  41. package/dist/{media-NHO7QT2A.js → media-QOGVG6CU.js} +3 -3
  42. package/dist/{meta-SOPDFYYK.js → meta-RJH5COPE.js} +40 -40
  43. package/dist/{page-photos-6PRIPJJE.js → page-photos-P2XMKTVF.js} +3 -3
  44. package/dist/{pages-Q4W64A3N.js → pages-O7NXGSBG.js} +2 -2
  45. package/dist/{pixels-HOOILVHZ.js → pixels-I7S5N76B.js} +26 -12
  46. package/dist/pixels-I7S5N76B.js.map +1 -0
  47. package/dist/{preview-3TA3ILQ5.js → preview-5CK5INGO.js} +2 -2
  48. package/dist/{rule-writes-TKNWMP3S.js → rule-writes-MSMVQDQO.js} +3 -3
  49. package/dist/{rules-BNNJXDYI.js → rules-UEKJOZTV.js} +41 -24
  50. package/dist/rules-UEKJOZTV.js.map +1 -0
  51. package/dist/{shared-3C5ZX44Q.js → shared-PPAWDMRF.js} +16 -4
  52. package/dist/{studies-5YCUBVK5.js → studies-TIF7PYEB.js} +33 -16
  53. package/dist/studies-TIF7PYEB.js.map +1 -0
  54. package/dist/{study-writes-CD3D23LK.js → study-writes-RGKBOOJ6.js} +3 -3
  55. package/dist/{targeting-BNJVE7XS.js → targeting-YWOOD6YL.js} +3 -3
  56. package/dist/{videos-RS3G65UV.js → videos-OF6PAPP2.js} +2 -2
  57. package/dist/{write-commands-PD3BEWWZ.js → write-commands-REUTFNJ3.js} +7 -7
  58. package/package.json +1 -1
  59. package/dist/account-assets-ZY4UYCHQ.js.map +0 -1
  60. package/dist/activities-JHKNRR3M.js.map +0 -1
  61. package/dist/ads-7NUK2UOG.js.map +0 -1
  62. package/dist/adsets-JF3CBKOU.js.map +0 -1
  63. package/dist/audience-writes-PT6RLJAK.js.map +0 -1
  64. package/dist/audiences-G3PRPIY4.js.map +0 -1
  65. package/dist/campaigns-FN56B6B7.js.map +0 -1
  66. package/dist/chunk-2W6ILA5Z.js.map +0 -1
  67. package/dist/chunk-6MFVGM3F.js.map +0 -1
  68. package/dist/creatives-3AQ3EEUL.js.map +0 -1
  69. package/dist/custom-conversions-XNYZOJYY.js.map +0 -1
  70. package/dist/insights-VD4QINO7.js.map +0 -1
  71. package/dist/pixels-HOOILVHZ.js.map +0 -1
  72. package/dist/rules-BNNJXDYI.js.map +0 -1
  73. package/dist/studies-5YCUBVK5.js.map +0 -1
  74. /package/dist/{account-6EJ22A7X.js.map → account-AIW3XGWG.js.map} +0 -0
  75. /package/dist/{account-level-Z4Z5PUA6.js.map → account-level-CB6I4X5W.js.map} +0 -0
  76. /package/dist/{accounts-JILEWVP6.js.map → accounts-2USPMXA2.js.map} +0 -0
  77. /package/dist/{ads-SWRPUDVK.js.map → ads-WERB3QK5.js.map} +0 -0
  78. /package/dist/{asset-writes-HXFRHFWF.js.map → asset-writes-ZOVD5O5X.js.map} +0 -0
  79. /package/dist/{businesses-3N6CTZ2Q.js.map → businesses-5AEHP23G.js.map} +0 -0
  80. /package/dist/{catalogs-N2I2GNHS.js.map → catalogs-UYYPZRFW.js.map} +0 -0
  81. /package/dist/{chunk-SNQKL66G.js.map → chunk-3F6AXSPB.js.map} +0 -0
  82. /package/dist/{chunk-6XXKYTD5.js.map → chunk-BRHYK4HQ.js.map} +0 -0
  83. /package/dist/{chunk-JV6O52V6.js.map → chunk-ZGYIG6OM.js.map} +0 -0
  84. /package/dist/{copy-writes-YXVKXBQC.js.map → copy-writes-TEJRR2W2.js.map} +0 -0
  85. /package/dist/{draft-3P2XHRWX.js.map → draft-OHAOBGVP.js.map} +0 -0
  86. /package/dist/{instant-experiences-KCAH5ONN.js.map → instant-experiences-YXH2AHFI.js.map} +0 -0
  87. /package/dist/{leads-HU4GA6T4.js.map → leads-IGOXMIEW.js.map} +0 -0
  88. /package/dist/{media-NHO7QT2A.js.map → media-QOGVG6CU.js.map} +0 -0
  89. /package/dist/{meta-SOPDFYYK.js.map → meta-RJH5COPE.js.map} +0 -0
  90. /package/dist/{page-photos-6PRIPJJE.js.map → page-photos-P2XMKTVF.js.map} +0 -0
  91. /package/dist/{pages-Q4W64A3N.js.map → pages-O7NXGSBG.js.map} +0 -0
  92. /package/dist/{preview-3TA3ILQ5.js.map → preview-5CK5INGO.js.map} +0 -0
  93. /package/dist/{rule-writes-TKNWMP3S.js.map → rule-writes-MSMVQDQO.js.map} +0 -0
  94. /package/dist/{shared-3C5ZX44Q.js.map → shared-PPAWDMRF.js.map} +0 -0
  95. /package/dist/{study-writes-CD3D23LK.js.map → study-writes-RGKBOOJ6.js.map} +0 -0
  96. /package/dist/{targeting-BNJVE7XS.js.map → targeting-YWOOD6YL.js.map} +0 -0
  97. /package/dist/{videos-RS3G65UV.js.map → videos-OF6PAPP2.js.map} +0 -0
  98. /package/dist/{write-commands-PD3BEWWZ.js.map → write-commands-REUTFNJ3.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../api/src/ads-meta/insightsActions.ts","../../api/src/ads-meta/insightsCompare.ts","../../api/src/ads-meta/insightsPeriod.ts","../../api/src/ads-meta/insightsIntents.ts","../src/commands/ads/meta/insights.ts","../src/commands/ads/meta/placement-delivery.ts"],"sourcesContent":["/**\n * The compact view of Meta's insights action arrays (`actions`,\n * `cost_per_action_type`, `conversions`, …).\n *\n * Meta returns one conversion under up to six names — `complete_registration`,\n * `omni_complete_registration`, `offsite_conversion.fb_pixel_complete_registration`,\n * `onsite_web_…` — with the same count, beside every engagement count the\n * account ever had (likes, saves, unlikes, video views). A one-month revenue\n * read ran to ~35 entries per row and 3.7 KB, and agents cut it with `head -c`\n * past the spend figure (BAKER-855). So by default each alias family becomes one\n * entry under its plain name, and engagement and Meta's combined \"+ 20s calls\" /\n * \"+ Meta leads\" restatements are dropped from the mixed arrays. `--action-types`\n * keeps only the named ones; `--full` skips this module.\n */\n\ntype InsightsRow = Record<string, unknown>;\ntype ActionEntry = Record<string, unknown> & { action_type: string };\n\n/** Arrays that mix every action type; single-purpose arrays (video watch, outbound clicks) are only de-aliased. */\nconst MIXED_ACTION_FIELDS = new Set([\n \"actions\",\n \"unique_actions\",\n \"action_values\",\n \"cost_per_action_type\",\n \"cost_per_unique_action_type\",\n \"conversions\",\n \"conversion_values\",\n \"cost_per_conversion\",\n]);\n\nconst ENGAGEMENT_TYPES = new Set([\n \"page_engagement\",\n \"post_engagement\",\n \"post\",\n \"comment\",\n \"like\",\n \"photo_view\",\n \"video_view\",\n \"post_reaction\",\n \"post_interaction_gross\",\n \"post_interaction_net\",\n]);\n\n/** `onsite_conversion.post_save`, `…post_net_like`, `…post_unlike` and the rest of the post counters. */\nconst ENGAGEMENT_PREFIX = \"onsite_conversion.post_\";\n\n/** Meta's sums of a conversion with another result (`offsite_lead_add_20_s_calls`), each already its own entry. */\nconst COMBINED_TYPE = /_add_(?:\\d+_s_calls|meta_leads)$/;\n\n/** The channel prefixes Meta puts in front of one conversion's name; `omni_` is the cross-channel total. */\nconst ALIAS_PREFIXES = [\n \"omni_\",\n \"offsite_conversion.fb_pixel_\",\n \"onsite_web_app_\",\n \"onsite_web_\",\n \"app_custom_event.fb_mobile_\",\n];\n\n/** On-Facebook lead forms report under their own names; `lead` is the total that includes them. */\nconst LEAD_ALIASES = new Set([\"onsite_conversion.lead_grouped\", \"leadgen_grouped\"]);\n\n/** A custom event (`offsite_conversion.fb_pixel_custom.<Name>`) keeps its full name: it has no alias. */\nfunction canonicalType(type: string): string {\n if (LEAD_ALIASES.has(type)) return \"lead\";\n if (type.startsWith(\"offsite_conversion.fb_pixel_custom\")) return type;\n const prefix = ALIAS_PREFIXES.find((p) => type.startsWith(p));\n return prefix ? type.slice(prefix.length) : type;\n}\n\nfunction isNoise(type: string): boolean {\n return ENGAGEMENT_TYPES.has(type) || type.startsWith(ENGAGEMENT_PREFIX) || COMBINED_TYPE.test(type);\n}\n\nfunction isActionArray(value: unknown): value is ActionEntry[] {\n return (\n Array.isArray(value) &&\n value.every((entry) => typeof entry === \"object\" && entry !== null && typeof entry.action_type === \"string\")\n );\n}\n\n/** The cross-channel `omni_` entry, else the plain name, else the largest alias: never a sum, the aliases overlap. */\nfunction pickOf(canonical: string, family: ActionEntry[]): ActionEntry {\n return (\n family.find((entry) => entry.action_type === `omni_${canonical}`) ??\n family.find((entry) => entry.action_type === canonical) ??\n family.reduce((best, entry) => (Number(entry.value) > Number(best.value) ? entry : best))\n );\n}\n\nfunction representative(canonical: string, family: ActionEntry[]): ActionEntry {\n return { ...pickOf(canonical, family), action_type: canonical };\n}\n\n/** The `--action-breakdowns` dimensions an entry is sliced by (`action_device: \"iphone\"`), beyond its type. */\nfunction sliceOf(entry: ActionEntry): Array<[string, unknown]> {\n return Object.entries(entry).filter(([key]) => key.startsWith(\"action_\") && key !== \"action_type\");\n}\n\n/** One conversion's entries under each of its names, within one breakdown slice. */\nfunction familiesOf(entries: ActionEntry[]): ActionEntry[][] {\n const families = new Map<string, ActionEntry[]>();\n for (const entry of entries) {\n const key = JSON.stringify([canonicalType(entry.action_type), sliceOf(entry)]);\n families.set(key, [...(families.get(key) ?? []), entry]);\n }\n return [...families.values()];\n}\n\n/** Each printed plain name and the raw names compaction printed under it (`purchase` ← `omni_purchase`). */\ntype Folds = Map<string, Set<string>>;\n\n/**\n * Aliases collapse within one breakdown slice: an iPhone and a desktop count of one conversion are two entries.\n * Every raw name printed under its plain name is recorded in `folded`, but one `kept` as its own entry.\n */\nfunction collapse(entries: ActionEntry[], folded: Folds, kept: (raw: string) => boolean = () => false): ActionEntry[] {\n return familiesOf(entries).map((family) => {\n const canonical = canonicalType(family[0]?.action_type ?? \"\");\n for (const { action_type: raw } of family) {\n if (raw !== canonical && !kept(raw)) folded.set(canonical, (folded.get(canonical) ?? new Set()).add(raw));\n }\n return representative(canonical, family);\n });\n}\n\n/** `--action-types`: a plain name (its aliases collapsed), an exact raw name, or a custom event's own name. */\nfunction keepNamed(entries: ActionEntry[], wanted: string[], folded: Folds): ActionEntry[] {\n const raw = entries.filter(\n (entry) =>\n (wanted.includes(entry.action_type) && canonicalType(entry.action_type) !== entry.action_type) ||\n wanted.some((name) => entry.action_type.endsWith(`.${name}`)),\n );\n const named = collapse(\n entries.filter((entry) => wanted.includes(canonicalType(entry.action_type))),\n folded,\n (type) => raw.some((entry) => entry.action_type === type),\n );\n return [...named, ...raw.filter((entry) => !named.some((kept) => kept.action_type === entry.action_type))];\n}\n\n/** An attribution window's figure on an entry: `7d_click`, `1d_view`. */\nconst WINDOW_KEY = /^(\\d+)d_(click|view)$/;\n\n/**\n * Arrays whose figures do not add up across windows: a cost (`cost_per_action_type`),\n * a return (`purchase_roas`), a rate (`website_ctr`) or an average\n * (`video_avg_time_watched_actions`). Every other action array is a count or a value.\n */\nconst UNADDITIVE_FIELD = /^cost_per_|_roas$|_ctr$|_avg_/;\n\n/** The entry's widest click window plus its widest view window — disjoint, so they add up — among `windows` if named. */\nfunction windowSum(entry: ActionEntry, windows?: readonly string[]): number {\n const widest = new Map<string, { days: number; figure: number }>();\n for (const [key, figure] of Object.entries(entry)) {\n const window = WINDOW_KEY.exec(key);\n if (!window || (windows && !windows.includes(key)) || !Number.isFinite(Number(figure))) continue;\n const days = Number(window[1]);\n const seen = widest.get(window[2] ?? \"\");\n if (!seen || days > seen.days) widest.set(window[2] ?? \"\", { days, figure: Number(figure) });\n }\n return [...widest.values()].reduce((sum, { figure }) => sum + figure, 0);\n}\n\n/**\n * The entry's `value`, or when Meta sent none (BAKER-1549, where a script\n * crashed on `KeyError: 'value'`) its click and view windows summed, else 0.\n * A cost, return, rate or average does not add up, so one without a value\n * says null. Every compact entry has one.\n */\nfunction withValue(field: string, entry: ActionEntry): ActionEntry {\n if (entry.value !== undefined) return entry;\n if (UNADDITIVE_FIELD.test(field)) return { ...entry, value: null };\n return { ...entry, value: String(round2(windowSum(entry))) };\n}\n\n/** The keys on an entry beside its type, its total and its breakdown slices: its attribution figures (`7d_click`, `1d_ev`, `dda`). */\nfunction attributionKeys(entry: ActionEntry): string[] {\n return Object.keys(entry).filter((key) => key !== \"action_type\" && key !== \"value\" && !key.startsWith(\"action_\"));\n}\n\n/**\n * Whether a read's figures can be told in its `windows`: click and view\n * windows, which add up as `windowSum` adds them, or one other selector alone\n * (`1d_ev`, `dda`). `default` is Meta's own total, and a mix of models does not\n * add up, so those keep Meta's figures.\n */\nfunction readsInWindows(windows: readonly string[]): boolean {\n if (windows.includes(\"default\")) return false;\n return windows.length === 1 || windows.every((window) => WINDOW_KEY.test(window));\n}\n\n/** A count in `windows`: their click and view figures summed, or the one other selector's figure. */\nfunction countIn(entry: ActionEntry, windows: readonly string[]): number {\n if (windows.every((window) => WINDOW_KEY.test(window))) return windowSum(entry, windows);\n const figure = Number(entry[windows[0] ?? \"\"]);\n return Number.isFinite(figure) ? figure : 0;\n}\n\n/**\n * An entry read in `windows` other than Meta's default: Meta's `value` stays\n * its default-window total (click plus view) whatever was asked, and it leaves\n * out a window that counted nothing (BAKER-2422). So every requested window is\n * set, 0 where Meta split the entry and sent none of them, and `value` is their\n * figure: their sum for a count, the one window's figure for a cost or rate\n * (null across several). An entry Meta did not split at all (`value` alone)\n * may or may not have counted in them, so its figures are null: unknown, not 0.\n */\nfunction inWindows(field: string, entry: ActionEntry, windows: readonly string[]): ActionEntry {\n if (attributionKeys(entry).length === 0) {\n return { ...entry, ...Object.fromEntries(windows.map((window) => [window, null])), value: null };\n }\n const unadditive = UNADDITIVE_FIELD.test(field);\n const figures = Object.fromEntries(windows.map((window) => [window, entry[window] ?? (unadditive ? null : \"0\")]));\n const only = windows.length === 1 ? figures[windows[0] ?? \"\"] : null;\n const value = unadditive ? (only ?? null) : String(round2(countIn(entry, windows)));\n return { ...entry, ...figures, value };\n}\n\n/** An array whose figures depend on the windows: every mixed array, a return (`purchase_roas`), or any array Meta split. */\nfunction isWindowed(field: string, entries: ActionEntry[]): boolean {\n return (\n MIXED_ACTION_FIELDS.has(field) || /_roas$/.test(field) || entries.some((entry) => attributionKeys(entry).length > 0)\n );\n}\n\n/**\n * A row with every action entry's `value` filled, so compaction and its\n * disagreement hints read the same figures; read in `windows` when the read\n * named windows other than Meta's default.\n */\nfunction withValues(row: InsightsRow, windows: readonly string[] | undefined): InsightsRow {\n return Object.fromEntries(\n Object.entries(row).map(([field, value]) => {\n if (!isActionArray(value)) return [field, value];\n if (!windows || !isWindowed(field, value)) return [field, value.map((entry) => withValue(field, entry))];\n return [field, value.map((entry) => inWindows(field, entry, windows))];\n }),\n );\n}\n\nfunction compactArray(\n field: string,\n entries: ActionEntry[],\n wanted: string[] | undefined,\n out: { dropped: Set<string>; folded: Folds },\n) {\n const { dropped, folded } = out;\n if (!MIXED_ACTION_FIELDS.has(field)) return collapse(entries, folded);\n if (wanted) return keepNamed(entries, wanted, folded);\n const kept = entries.filter((entry) => {\n if (!isNoise(entry.action_type)) return true;\n dropped.add(entry.action_type);\n return false;\n });\n return collapse(kept, folded);\n}\n\n/**\n * A conversion whose names count it differently (`lead` 48, `offsite_conversion.fb_pixel_lead` 30):\n * the compact view prints one of them, so it says which and what the others counted (BAKER-2377).\n * Only the count arrays of conversions the compact view prints, its first such row as the example.\n */\nfunction disagreeingCounters(rows: InsightsRow[], wanted: string[] | undefined): string[] {\n const found = new Map<string, { example: string; rows: number }>();\n for (const row of rows) {\n for (const { label, example } of rowDisagreements(row, wanted)) {\n const seen = found.get(label);\n found.set(label, { example: seen?.example ?? example, rows: (seen?.rows ?? 0) + 1 });\n }\n }\n return [...found.entries()].map(\n ([label, { example, rows: count }]) =>\n `Meta's counters for ${label} disagree on ${count} ${count === 1 ? \"row\" : \"rows\"} (${example}); --full returns every counter.`,\n );\n}\n\n/** One row's printed conversions whose counters disagree, each with every counter's value and the one printed. */\nfunction rowDisagreements(row: InsightsRow, wanted: string[] | undefined): Array<{ label: string; example: string }> {\n return Object.entries(row).flatMap(([field, value]) => {\n if (!COUNT_FIELDS.has(field) || !isActionArray(value)) return [];\n return familiesOf(value).flatMap((family) => {\n const canonical = canonicalType(family[0]?.action_type ?? \"\");\n const printed = wanted ? wanted.includes(canonical) : !isNoise(canonical);\n const known = family.filter((entry) => entry.value !== null);\n if (!printed || new Set(known.map((entry) => Number(entry.value))).size < 2) return [];\n const label = columnOf(field, { ...family[0], action_type: canonical });\n const pick = pickOf(canonical, family);\n const counts = family.map((entry) => `${entry.action_type} ${String(entry.value)}`).join(\", \");\n return [{ label, example: `${counts}; ${label} shows ${String(pick.value)}, from ${pick.action_type}` }];\n });\n });\n}\n\n/**\n * The folds for a hint, every one (\"omni_purchase, offsite_conversion.fb_pixel_purchase → purchase; omni_lead → lead\"):\n * a lookup by a raw name finds nothing in the compact rows, so the hint has to say where each went (BAKER-3247).\n * Null when nothing was folded. Each caller names its own way to keep a raw name.\n */\nfunction foldedList(folded: Folds): string | null {\n if (folded.size === 0) return null;\n return [...folded.entries()].map(([canonical, raws]) => `${[...raws].join(\", \")} → ${canonical}`).join(\"; \");\n}\n\n/** Each printed count column whose entry satisfies `test`, and on how many rows. */\nfunction columnsWhere(rows: InsightsRow[], test: (entry: ActionEntry) => boolean): string[] {\n const found = new Map<string, number>();\n for (const row of rows) {\n for (const [field, value] of Object.entries(row)) {\n if (!COUNT_FIELDS.has(field) || !isActionArray(value)) continue;\n for (const entry of value.filter(test))\n found.set(columnOf(field, entry), (found.get(columnOf(field, entry)) ?? 0) + 1);\n }\n }\n return [...found.entries()].map(([column, count]) => `${column} (${count} ${count === 1 ? \"row\" : \"rows\"})`);\n}\n\n/**\n * The hints for the printed count entries a read in `windows` could not give\n * a figure in them: those Meta counted only in other windows, which read 0,\n * and those Meta did not split by window at all, which read null.\n */\nfunction windowHints(rows: InsightsRow[], windows: readonly string[]): string[] {\n const asked = windows.join(\",\");\n const outside = columnsWhere(\n rows,\n (entry) =>\n entry.value !== null &&\n Number(entry.value) === 0 &&\n attributionKeys(entry).some((key) => !windows.includes(key) && Number(entry[key]) > 0),\n );\n const unsplit = columnsWhere(rows, (entry) => entry.value === null);\n return [\n ...(outside.length === 0\n ? []\n : [\n `Meta counted ${outside.join(\", \")} only outside ${asked}, so each reads 0 on those rows: a real 0 in ${asked}, not a missing figure (Meta counted it in another window and none in ${asked}).`,\n ]),\n ...(unsplit.length === 0\n ? []\n : [\n `Meta sent ${unsplit.join(\", \")} as one total with no ${asked} figure, so each reads null on those rows: its count in ${asked} is not known, not 0; --full keeps Meta's own value, its 7d_click,1d_view total.`,\n ]),\n ];\n}\n\n/**\n * Every row with its action arrays compacted, the engagement or combined types\n * that were dropped, the raw names folded into a plain one, the conversions\n * whose counters disagreed, and, for a read in `windows` other than Meta's\n * default, the printed conversions it could not count in them.\n */\nexport function compactInsightsRows(\n rows: InsightsRow[],\n options: { actionTypes?: string[]; windows?: readonly string[] },\n): {\n rows: InsightsRow[];\n dropped: string[];\n folded: string | null;\n disagreements: string[];\n windowHints: string[];\n} {\n const dropped = new Set<string>();\n const folded: Folds = new Map();\n const windows = options.windows && readsInWindows(options.windows) ? options.windows : undefined;\n const valued = rows.map((row) => withValues(row, windows));\n const compacted = valued.map((row) =>\n Object.fromEntries(\n Object.entries(row).map(([field, value]) => [\n field,\n isActionArray(value) ? compactArray(field, value, options.actionTypes, { dropped, folded }) : value,\n ]),\n ),\n );\n return {\n rows: windows ? compacted.map((row) => inAskedWindowsOnly(row, windows)) : compacted,\n dropped: [...dropped],\n folded: foldedList(folded),\n disagreements: disagreeingCounters(valued, options.actionTypes),\n windowHints: windows ? windowHints(compacted, windows) : [],\n };\n}\n\n/** A row whose action entries keep only the asked `windows`' keys: the other windows were read only to tell a 0 from an unsplit total. */\nfunction inAskedWindowsOnly(row: InsightsRow, windows: readonly string[]): InsightsRow {\n return Object.fromEntries(\n Object.entries(row).map(([field, value]) => {\n if (!isActionArray(value)) return [field, value];\n return [\n field,\n value.map((entry) =>\n Object.fromEntries(\n Object.entries(entry).filter(([key]) => !attributionKeys(entry).includes(key) || windows.includes(key)),\n ),\n ),\n ];\n }),\n );\n}\n\n/** Arrays that count actions; their entries can be priced from the row's spend. */\nconst COUNT_FIELDS = new Set([\"actions\", \"unique_actions\", \"conversions\"]);\n\nconst CUSTOM_EVENT_PREFIX = \"offsite_conversion.fb_pixel_custom\";\n\n/** `actions.lead`, or `actions.lead[iphone]` for an `--action-breakdowns` slice. */\nfunction columnOf(field: string, entry: ActionEntry): string {\n const slice = sliceOf(entry).map(([, value]) => String(value));\n return slice.length === 0 ? `${field}.${entry.action_type}` : `${field}.${entry.action_type}[${slice.join(\",\")}]`;\n}\n\nfunction round2(value: number): number {\n return Math.round(value * 100) / 100;\n}\n\n/** Spend over count, for an unsliced count entry that is priced: spend is per row, never per breakdown slice. */\nfunction pricedEntry(field: string, entry: ActionEntry, priceAll: boolean): boolean {\n if (!COUNT_FIELDS.has(field) || sliceOf(entry).length > 0) return false;\n return priceAll || entry.action_type.startsWith(CUSTOM_EVENT_PREFIX);\n}\n\n/**\n * Rows for `--output md|csv`: each action array becomes one `<field>.<action_type>`\n * column holding its total, in place of the array as JSON in one cell. The\n * click/view split stays in `--output json|jsonl`. Meta adds each row's period\n * (`date_start`, `date_stop`) outside the requested fields; it leads the table.\n * A custom event (a CRM stage), or every type `--action-types` named\n * (`priceAll`), gets a `cost_per.<field>.<action_type>` column: the row's spend\n * over that count, in the requested attribution windows.\n */\nexport function insightsTable(\n rows: InsightsRow[],\n fields: string[],\n options: { priceAll?: boolean } = {},\n): { rows: InsightsRow[]; columns: string[] } {\n const priceAll = options.priceAll ?? false;\n const period = [\"date_start\", \"date_stop\"].filter(\n (field) => !fields.includes(field) && rows.some((row) => row[field] !== undefined),\n );\n const columns = [...period, ...fields].flatMap((field) => {\n const counts = new Set<string>();\n const costs = new Set<string>();\n for (const row of rows) {\n const value = row[field];\n if (!isActionArray(value)) continue;\n for (const entry of value) {\n counts.add(columnOf(field, entry));\n if (pricedEntry(field, entry, priceAll) && row.spend !== undefined)\n costs.add(`cost_per.${columnOf(field, entry)}`);\n }\n }\n return counts.size === 0 ? [field] : [...counts, ...costs];\n });\n const flat = rows.map((row) => {\n const out: InsightsRow = {};\n const spend = Number(row.spend);\n for (const [field, value] of Object.entries(row)) {\n if (!isActionArray(value)) {\n out[field] = value;\n continue;\n }\n for (const entry of value) {\n const column = columnOf(field, entry);\n out[column] = entry.value;\n const count = Number(entry.value);\n if (pricedEntry(field, entry, priceAll) && Number.isFinite(spend) && count > 0) {\n out[`cost_per.${column}`] = round2(spend / count);\n }\n }\n }\n return out;\n });\n return { rows: flat, columns };\n}\n\n/** The columns `--intent funnel` adds to every row. */\nconst FUNNEL_COLUMNS = [\"result_type\", \"results\", \"cvr\", \"cost_per_result\"];\n\n/** The conversions a funnel ends in, deepest first: the first one an ad reports is its result. */\nconst RESULT_PRIORITY = [\n \"purchase\",\n \"complete_registration\",\n \"lead\",\n \"submit_application\",\n \"subscribe\",\n \"start_trial\",\n \"schedule\",\n \"contact\",\n \"initiate_checkout\",\n \"add_payment_info\",\n \"add_to_cart\",\n];\n\n/** The count of `type`, null when one of its entries has no known count (a read in windows Meta did not split it by). */\nfunction countOf(actions: ActionEntry[], type: string): number | null {\n const entries = actions.filter((entry) => entry.action_type === type);\n if (entries.some((entry) => entry.value === null)) return null;\n return entries.reduce((sum, entry) => sum + Number(entry.value), 0);\n}\n\nfunction resultTypeOf(actions: ActionEntry[], wanted: string[] | undefined): string | null {\n const present = new Set(actions.map((entry) => entry.action_type));\n const named = (wanted ?? []).find((name) => [...present].some((type) => type === name || type.endsWith(`.${name}`)));\n if (named) return [...present].find((type) => type === named || type.endsWith(`.${named}`)) ?? null;\n const standard = RESULT_PRIORITY.find((type) => present.has(type));\n if (standard) return standard;\n const custom = actions\n .filter((entry) => entry.action_type.startsWith(CUSTOM_EVENT_PREFIX))\n .sort((a, b) => Number(b.value) - Number(a.value));\n return custom[0]?.action_type ?? null;\n}\n\n/**\n * `--intent funnel` rows with the figures the intent exists for: the ad's\n * result (the first `--action-types` name it reports, else its deepest standard\n * conversion, else its largest custom event), `cvr` as the percent of link\n * clicks that became one, and `cost_per_result` as spend over results. Reads\n * compacted rows, where each conversion sits under its plain name.\n */\nexport function withFunnelResults(rows: InsightsRow[], options: { actionTypes?: string[] }): InsightsRow[] {\n return rows.map((row) => {\n const actions = isActionArray(row.actions) ? row.actions : [];\n const resultType = resultTypeOf(actions, options.actionTypes);\n const results = resultType === null ? null : countOf(actions, resultType);\n const linkClicks =\n row.inline_link_clicks !== undefined ? Number(row.inline_link_clicks) : countOf(actions, \"link_click\");\n const spend = Number(row.spend);\n return {\n ...row,\n result_type: resultType,\n results,\n cvr: results !== null && linkClicks !== null && linkClicks > 0 ? round2((results / linkClicks) * 100) : null,\n cost_per_result: results !== null && results > 0 && Number.isFinite(spend) ? round2(spend / results) : null,\n };\n });\n}\n\n/**\n * `--intent leads` rows with `cost_per_lead`: spend over the row's `lead`\n * count, null when it has none. md prices it as `cost_per.actions.lead`; json\n * and the channel engine read the compacted rows, which held no cost at all.\n */\nfunction withLeadCost(rows: InsightsRow[]): InsightsRow[] {\n return rows.map((row) => {\n const leads = countOf(isActionArray(row.actions) ? row.actions : [], \"lead\");\n const spend = Number(row.spend);\n return {\n ...row,\n cost_per_lead: leads !== null && leads > 0 && Number.isFinite(spend) ? round2(spend / leads) : null,\n };\n });\n}\n\n/** Compacted rows with the figures their intents add: the funnel's result, CVR and cost per result; the leads' cost per lead. */\nexport function withIntentFigures(\n rows: InsightsRow[],\n intents: readonly string[],\n options: { actionTypes?: string[] },\n): InsightsRow[] {\n const funnel = intents.includes(\"funnel\") ? withFunnelResults(rows, options) : rows;\n return intents.includes(\"leads\") ? withLeadCost(funnel) : funnel;\n}\n\n/**\n * The columns a read's intents add to every row. A read narrowed to its\n * conversions (`actionTypes`) prices each as `cost_per.actions.<type>`; one\n * that keeps every action (`leads,funnel`) prices none, so it prints\n * `cost_per_lead` itself.\n */\nexport function intentColumns(intents: readonly string[], actionTypes: string[] | undefined): string[] {\n const funnel = intents.includes(\"funnel\") ? FUNNEL_COLUMNS : [];\n return intents.includes(\"leads\") && actionTypes === undefined ? [...funnel, \"cost_per_lead\"] : funnel;\n}\n\n/**\n * Rows a read prints at `--level ad|adset` unless `--limit` names another\n * number: an account runs to hundreds of ads, and one ad-level read printed\n * 269 KB that the agent cut with `head -c` (BAKER-1222). Account and campaign\n * reads stay whole.\n */\nconst SHOWN_ROWS_BY_DEFAULT = 25;\n\n/** How many rows a read prints: `--limit`, else the default for its level; null prints every row read. */\nexport function shownRows(level: string, limit: number | undefined): number | null {\n if (limit !== undefined) return limit > 0 ? limit : null;\n return level === \"ad\" || level === \"adset\" ? SHOWN_ROWS_BY_DEFAULT : null;\n}\n\n/** The first `shown` rows of an ordered read, and what was left out (\"Showing 25 of 312 rows (…)\"), null when nothing was. */\nexport function firstRows(\n rows: InsightsRow[],\n shown: number | null,\n order: string,\n): { rows: InsightsRow[]; leftOut: string | null } {\n if (shown === null || rows.length <= shown) return { rows, leftOut: null };\n return { rows: rows.slice(0, shown), leftOut: `Showing ${shown} of ${rows.length} rows (${order})` };\n}\n\n/** A read by day or month (`--time-increment 1|monthly|<n>`), not one row for the whole period. */\nexport function isTimeSeries(timeIncrement: string | undefined): boolean {\n return timeIncrement !== undefined && timeIncrement !== \"all_days\";\n}\n\n/**\n * Rows in the order they are read: a time series by date, earliest first (by\n * spend within a day), so a daily read is a series and not a ranking of days\n * (BAKER-1660); any other read by spend.\n */\nexport function inReadingOrder(rows: InsightsRow[], timeIncrement: string | undefined): InsightsRow[] {\n const bySpend = bySpendDescending(rows);\n if (!isTimeSeries(timeIncrement)) return bySpend;\n return bySpend.sort((a, b) => String(a.date_start ?? \"\").localeCompare(String(b.date_start ?? \"\")));\n}\n\n/** Rows by spend, most first: a read is scanned for where the money went. */\nfunction bySpendDescending(rows: InsightsRow[]): InsightsRow[] {\n return [...rows].sort((a, b) => {\n const sa = Number(a.spend ?? 0);\n const sb = Number(b.spend ?? 0);\n if (Number.isNaN(sa) || Number.isNaN(sb)) return 0;\n return sb - sa;\n });\n}\n","/**\n * Meta insights `--compare`: the same read over other windows, joined to each\n * printed row with the change of every figure. A week against the week\n * before, or a 3-day read against its 7- and 30-day windows, was one call per\n * window and the arithmetic done by hand (BAKER-928, BAKER-613). The CLI and\n * the engine's conversations read it the same way.\n */\nimport { z } from \"zod\";\nimport type { InsightsLevel } from \"./insightsIntents\";\nimport { DATE_PRESETS_TAKEN, metaDatePreset } from \"./insightsPeriod\";\n\ntype Row = Record<string, unknown>;\n\n/** A window to compare with: the period just before, a Meta preset, or a date range. */\nexport type CompareWindow =\n | { label: \"previous_period\" }\n | { label: string; datePreset: string }\n | { label: string; since: string; until: string };\n\nconst ISO_DAY = z.iso.date();\nconst DAY_MS = 86_400_000;\n\nfunction isDay(value: string | undefined): value is string {\n return value !== undefined && ISO_DAY.safeParse(value).success;\n}\n\n/** `previous_period,last_30d,2026-08-01..2026-08-27`; a string naming what is wrong for any other spelling. */\nexport function parseCompare(raw: string): CompareWindow[] | string {\n const windows: CompareWindow[] = [];\n for (const token of raw.split(\",\").map((part) => part.trim())) {\n const [since, until, extra] = token.split(\"..\");\n const preset = metaDatePreset(token);\n if (token === \"previous_period\") windows.push({ label: token });\n else if (isDay(since) && isDay(until) && extra === undefined && since <= until)\n windows.push({ label: token, since, until });\n else if (preset) windows.push({ label: token, datePreset: preset });\n else\n return `--compare takes previous_period, YYYY-MM-DD..YYYY-MM-DD or ${DATE_PRESETS_TAKEN}, comma-separated; got \"${token}\"`;\n }\n return windows;\n}\n\nfunction shiftDay(day: string, days: number): string {\n return new Date(Date.parse(`${day}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10);\n}\n\n/** As many days as `since..until`, ending the day before it starts. */\nexport function previousPeriod(since: string, until: string): { since: string; until: string } {\n const days = Math.round((Date.parse(until) - Date.parse(since)) / DAY_MS) + 1;\n return { since: shiftDay(since, -days), until: shiftDay(since, -1) };\n}\n\n/**\n * The period a window is read over. The period before a preset is counted from\n * the dates Meta answered it with, which are the account's own days; null when\n * nothing delivered in the read, so there are no dates to count back from.\n */\nexport function windowPeriod(\n window: CompareWindow,\n read: { since?: string; until?: string },\n current: readonly Row[],\n): { datePreset: string } | { since: string; until: string } | null {\n if (\"datePreset\" in window) return { datePreset: window.datePreset };\n if (\"since\" in window) return { since: window.since, until: window.until };\n const since = read.since ?? current[0]?.date_start;\n const until = read.until ?? current[0]?.date_stop;\n return typeof since === \"string\" && typeof until === \"string\" ? previousPeriod(since, until) : null;\n}\n\n/** Said when a window could not be read, and how to read it. */\nexport function unreadWindowHint(label: string): string {\n return `${label} was not read: nothing delivered in this window, so the days before it are unknown; read it by days (since and until) to compare.`;\n}\n\n/** The level's own id, asked for whenever windows are compared: rows are joined by it, never by name. */\nexport function withJoinId(fields: string[], level: InsightsLevel): string[] {\n if (level === \"account\") return fields;\n const id = `${level}_id`;\n return fields.includes(id) ? fields : [id, ...fields];\n}\n\nconst PERIOD_FIELDS = new Set([\"date_start\", \"date_stop\"]);\n\n/** Counts Meta leaves out of a row when they are zero (`actions.complete_registration`). */\nconst COUNT_PREFIXES = [\"actions.\", \"unique_actions.\", \"conversions.\"];\n\nfunction isCount(field: string): boolean {\n return COUNT_PREFIXES.some((prefix) => field.startsWith(prefix));\n}\n\n/** What names a row rather than measuring it: ids, names, its period, and the breakdown values. */\nfunction isLabel(field: string, breakdowns: readonly string[]): boolean {\n return PERIOD_FIELDS.has(field) || field.endsWith(\"_id\") || field.endsWith(\"_name\") || breakdowns.includes(field);\n}\n\n/** One row's place in every window: its ids and breakdown values, never its name, which can change between them. */\nfunction keyOf(row: Row, breakdowns: readonly string[]): string {\n return JSON.stringify(\n Object.keys(row)\n .filter((field) => field.endsWith(\"_id\") || breakdowns.includes(field))\n .sort()\n .map((field) => [field, row[field]]),\n );\n}\n\nfunction numberOf(value: unknown): number | null {\n if (typeof value !== \"number\" && typeof value !== \"string\") return null;\n if (typeof value === \"string\" && value.trim() === \"\") return null;\n const number = Number(value);\n return Number.isFinite(number) ? number : null;\n}\n\n/** Percent change from `before` to `now`, one decimal; null when there was nothing before to change from. */\nfunction changePct(now: unknown, before: unknown): number | null {\n const a = numberOf(now);\n const b = numberOf(before);\n if (a === null || b === null || b === 0) return null;\n return Math.round(((a - b) / Math.abs(b)) * 1000) / 10;\n}\n\n/** The figures of either row: a conversion that stopped, or started, is still compared. */\nfunction figuresOf(row: Row, other: Row, breakdowns: readonly string[]): string[] {\n const fields = new Set([...Object.keys(row), ...Object.keys(other)]);\n return [...fields].filter(\n (field) => !isLabel(field, breakdowns) && (numberOf(row[field]) !== null || numberOf(other[field]) !== null),\n );\n}\n\n/** The figures of `other` beside `row`'s, with the change of each; null when the row did not deliver in that window. */\nfunction comparedTo(row: Row, other: Row | undefined, breakdowns: readonly string[]): Row | null {\n if (other === undefined) return null;\n const figures = figuresOf(row, other, breakdowns);\n const before = Object.fromEntries(figures.map((field) => [field, other[field] ?? null]));\n const change = Object.fromEntries(figures.map((field) => [field, changePct(row[field], other[field])]));\n const period = Object.fromEntries([...PERIOD_FIELDS].filter((f) => f in other).map((f) => [f, other[f]]));\n return { ...period, ...before, change_pct: change };\n}\n\n/** A count the row lacks but a window holds is a zero Meta left out, said as one. */\nfunction withZeroCounts(row: Row, others: ReadonlyArray<Row | undefined>): Row {\n const missing = others.flatMap((other) =>\n Object.keys(other ?? {}).filter((field) => isCount(field) && !(field in row)),\n );\n return missing.length === 0 ? row : { ...row, ...Object.fromEntries(missing.map((field) => [field, 0])) };\n}\n\n/**\n * Each printed row with `compare.<window>`: that window's figures for the same\n * entity and the percent change of each, and a hint counting the entities that\n * delivered in a window but not in the one read. `read` is every row the read\n * returned, the printed ones among them: one a row limit left out still\n * delivered. A window whose rows are null was not read.\n */\nexport function withComparisons(\n rows: Row[],\n windows: Array<{ label: string; rows: Row[] | null }>,\n breakdowns: readonly string[],\n read: readonly Row[] = rows,\n): { rows: Row[]; hints: string[] } {\n const indexed = windows.map(({ label, rows: other }) => ({\n label,\n byKey: other === null ? null : new Map(other.map((row) => [keyOf(row, breakdowns), row])),\n }));\n const compared = rows.map((row) => {\n const others = indexed.map(({ byKey }) => byKey?.get(keyOf(row, breakdowns)));\n const filled = withZeroCounts(row, others);\n return {\n ...filled,\n compare: Object.fromEntries(indexed.map(({ label }, at) => [label, comparedTo(filled, others[at], breakdowns)])),\n };\n });\n const delivered = new Set(read.map((row) => keyOf(row, breakdowns)));\n const hints = indexed.flatMap(({ label, byKey }) => {\n if (byKey === null) return [unreadWindowHint(label)];\n const gone = [...byKey.keys()].filter((key) => !delivered.has(key)).length;\n return gone === 0 ? [] : [`${gone} more delivered in ${label} and not in this window; they are not listed.`];\n });\n if (compared.some((row) => Object.values(row.compare).includes(null))) {\n hints.push(\"compare.<window> is null where that row did not deliver in the window.\");\n }\n return { rows: compared, hints };\n}\n\n/** One window's entry as `compare.<window>.<figure>` cells, its changes as `compare.<window>.change_pct.<figure>`. */\nfunction flatEntry(label: string, entry: Row | null): Row {\n if (entry === null) return {};\n const { change_pct: change, ...figures } = entry;\n return Object.fromEntries([\n ...Object.entries(figures).map(([field, value]) => [`compare.${label}.${field}`, value]),\n ...Object.entries((change ?? {}) as Row).map(([field, pct]) => [`compare.${label}.change_pct.${field}`, pct]),\n ]);\n}\n\n/** `compare.<window>.<figure>` columns for a table, after the row's own and the zero counts the join added. */\nexport function flatComparisons(rows: Row[], columns: string[]): { rows: Row[]; columns: string[] } {\n const flat = rows.map(({ compare, ...row }) => ({\n ...row,\n ...Object.assign(\n {},\n ...Object.entries((compare ?? {}) as Record<string, Row | null>).map(([label, entry]) => flatEntry(label, entry)),\n ),\n }));\n const keys = new Set(flat.flatMap((row) => Object.keys(row).filter((key) => !columns.includes(key))));\n const counts = [...keys].filter(isCount);\n const compared = [...keys].filter((key) => key.startsWith(\"compare.\"));\n return { rows: flat, columns: [...columns, ...counts, ...compared] };\n}\n","/**\n * The period of a Meta insights read, checked before Meta is asked. Meta\n * answers a preset it does not have with a message that names neither the flag\n * nor what it does take (`lifetime` came back as \"not a valid date_preset\",\n * leaving out `maximum`), so the natural spelling is read as Meta's and\n * anything else is refused here, naming the presets (BAKER-3849).\n */\n\n/** Meta's `date_preset` values, from the Insights API reference. */\nexport const META_DATE_PRESETS = [\n \"today\",\n \"yesterday\",\n \"this_month\",\n \"last_month\",\n \"this_quarter\",\n \"maximum\",\n \"data_maximum\",\n \"last_3d\",\n \"last_7d\",\n \"last_14d\",\n \"last_28d\",\n \"last_30d\",\n \"last_90d\",\n \"last_week_mon_sun\",\n \"last_week_sun_sat\",\n \"last_quarter\",\n \"last_year\",\n \"this_week_mon_today\",\n \"this_week_sun_today\",\n \"this_year\",\n] as const;\nexport type MetaDatePreset = (typeof META_DATE_PRESETS)[number];\n\nfunction isPreset(value: string): value is MetaDatePreset {\n return (META_DATE_PRESETS as readonly string[]).includes(value);\n}\n\n/** Meta's preset for `raw` (`lifetime` is `maximum`), or null when Meta has no such preset. */\nexport function metaDatePreset(raw: string): MetaDatePreset | null {\n const value = raw.trim().toLowerCase();\n if (isPreset(value)) return value;\n return value === \"lifetime\" ? \"maximum\" : null;\n}\n\n/** What a date preset may be, said when one is refused. */\nexport const DATE_PRESETS_TAKEN = `one of Meta's presets: ${META_DATE_PRESETS.join(\", \")} (maximum for lifetime)`;\n","/**\n * Insights field bundles. Picked for AI agent ergonomics: small, focused field\n * lists that answer one specific question without forcing the AI to enumerate\n * Meta's 500+ insights fields.\n *\n * Two-axis design:\n * --intent (field bundle, default: baseline) — what data to ask for\n * --level (object granularity, default: account) — at what granularity\n *\n * Intents are independent of level — pass `--intent ranking --level ad` to flag\n * creatives, or `--intent revenue --level campaign` for ROAS by campaign. They\n * combine: `--intent ranking,funnel` reads both bundles in one request, one row\n * per object, so nobody joins two reads by ad_id (BAKER-1549).\n *\n * Identity fields (campaign_name etc.) are appended automatically based on\n * level so the AI can read rows without joining.\n */\n\nexport const INSIGHTS_LEVELS = [\"account\", \"campaign\", \"adset\", \"ad\"] as const;\nexport type InsightsLevel = (typeof INSIGHTS_LEVELS)[number];\n\nexport const INSIGHTS_INTENT_NAMES = [\n \"baseline\",\n \"leads\",\n \"revenue\",\n \"funnel\",\n \"ranking\",\n \"video\",\n \"identity\",\n] as const;\nexport type InsightsIntent = (typeof INSIGHTS_INTENT_NAMES)[number];\n\n/** The attribution windows a read asks for unless told otherwise: the only ones still working as of Jan 2026 (1d_view + 28d_click also valid but rarely used). */\nexport const DEFAULT_ATTRIBUTION_WINDOWS = [\"7d_click\", \"1d_view\"];\n\n/** The filter a read applies unless told otherwise: rows that didn't deliver are left out. Almost always what we want. */\nexport const DEFAULT_FILTERING = [{ field: \"impressions\", operator: \"GREATER_THAN\", value: 0 }];\n\n/** The period a read covers when it names none. */\nexport const DEFAULT_DATE_PRESET = \"last_7d\";\n\ninterface IntentDefinition {\n name: InsightsIntent;\n description: string;\n fields: string[];\n /** Action breakdowns to slice the actions[] array — empty if not needed. */\n actionBreakdowns?: string[];\n /** The conversions the intent counts, unless `--action-types` names others. */\n actionTypes?: string[];\n}\n\nconst INSIGHTS_INTENTS: Record<InsightsIntent, IntentDefinition> = {\n baseline: {\n name: \"baseline\",\n description: \"Spend, impressions, clicks, CTR, CPC, CPM. The default question: 'how is delivery?'\",\n fields: [\"impressions\", \"reach\", \"frequency\", \"spend\", \"clicks\", \"ctr\", \"cpc\", \"cpm\"],\n },\n leads: {\n name: \"leads\",\n description: \"Spend, leads and cost per lead (the `lead` count). 'How many leads, at what cost?'\",\n fields: [\"impressions\", \"clicks\", \"spend\", \"actions\"],\n actionTypes: [\"lead\"],\n },\n revenue: {\n name: \"revenue\",\n description: \"Spend, conversions, action_values, purchase_roas. 'How much money are we making?'\",\n fields: [\"spend\", \"actions\", \"action_values\", \"conversions\", \"conversion_values\", \"purchase_roas\"],\n actionBreakdowns: [\"action_type\"],\n },\n funnel: {\n name: \"funnel\",\n description: \"Impression → click → landing page → action. 'Where do users drop off?'\",\n fields: [\"impressions\", \"clicks\", \"inline_link_clicks\", \"outbound_clicks\", \"actions\", \"spend\"],\n actionBreakdowns: [\"action_type\"],\n },\n ranking: {\n name: \"ranking\",\n description: \"Quality, engagement, conversion-rate rankings. 'Which creatives need a refresh?'\",\n fields: [\"impressions\", \"spend\", \"ctr\", \"quality_ranking\", \"engagement_rate_ranking\", \"conversion_rate_ranking\"],\n },\n video: {\n name: \"video\",\n description: \"Watch funnel, thruplay cost. 'How are video creatives holding attention?'\",\n fields: [\n \"impressions\",\n \"spend\",\n \"video_play_actions\",\n \"video_p25_watched_actions\",\n \"video_p50_watched_actions\",\n \"video_p75_watched_actions\",\n \"video_p100_watched_actions\",\n \"video_thruplay_watched_actions\",\n \"cost_per_thruplay\",\n ],\n },\n identity: {\n name: \"identity\",\n description: \"Just the names + spend — for cheap roll-up summaries.\",\n fields: [\"spend\", \"impressions\"],\n },\n};\n\nconst IDENTITY_FIELDS_BY_LEVEL: Record<InsightsLevel, string[]> = {\n account: [\"account_id\", \"account_name\", \"account_currency\"],\n campaign: [\"campaign_id\", \"campaign_name\", \"objective\"],\n adset: [\"adset_id\", \"adset_name\", \"campaign_id\", \"campaign_name\"],\n ad: [\"ad_id\", \"ad_name\", \"adset_id\", \"adset_name\", \"campaign_id\", \"campaign_name\"],\n};\n\n/** The intents a read names (`ranking,funnel`), each once; baseline when it names none, or the names no intent has. */\nexport function parseIntents(names: readonly string[]): InsightsIntent[] | { unknown: string[] } {\n const unknown = names.filter((name) => getIntent(name) === undefined);\n if (unknown.length > 0) return { unknown };\n return names.length === 0 ? [\"baseline\"] : [...new Set(names as InsightsIntent[])];\n}\n\nfunction asIntents(intents: string | readonly string[] | undefined): IntentDefinition[] {\n const names = intents === undefined ? [\"baseline\"] : typeof intents === \"string\" ? [intents] : intents;\n return names.flatMap((name) => getIntent(name) ?? []);\n}\n\n/** Compose final field list: every intent's metrics + level-specific identity fields, deduplicated. */\nexport function composeFields(intents: InsightsIntent | readonly InsightsIntent[], level: InsightsLevel): string[] {\n const intentFields = asIntents(intents).flatMap((intent) => intent.fields);\n const identity = IDENTITY_FIELDS_BY_LEVEL[level];\n const seen = new Set<string>();\n const out: string[] = [];\n for (const f of [...identity, ...intentFields]) {\n if (!seen.has(f)) {\n seen.add(f);\n out.push(f);\n }\n }\n return out;\n}\n\n/** The arrays `--action-types` filters by count: one of them has to be asked for, or the filter has nothing to keep. */\nconst COUNTED_ACTION_FIELDS = [\"actions\", \"unique_actions\", \"conversions\"];\n\n/**\n * The fields to ask Meta for: naming `--action-types` asks for `actions` when\n * the intent or `--fields` holds no counted action array. The default intent\n * has none, and a filter over a field nobody requested returned rows with no\n * action at all and no word why (BAKER-3479).\n */\nexport function withActionFields(fields: string[], actionTypes: string[] | undefined): string[] {\n if (!actionTypes?.length || fields.some((field) => COUNTED_ACTION_FIELDS.includes(field))) return fields;\n return [...fields, \"actions\"];\n}\n\n/**\n * The fields to ask Meta for: `spend` too, which ranks the rows whatever fields\n * are printed. A `--fields ad_id,ctr` read came back without it, every row tied\n * at 0, and the 25 printed as \"the most spend\" were Meta's first 25.\n */\nexport function withSpendField(fields: string[]): string[] {\n return fields.includes(\"spend\") ? fields : [...fields, \"spend\"];\n}\n\n/**\n * The conversions a read keeps: the ones `--action-types` names, else its\n * intents' own (`leads` → lead) — unless another intent reads every action\n * (`leads,funnel` keeps the funnel's landing-page views).\n */\nexport function intentActionTypes(\n intents: string | readonly string[] | undefined,\n named: string[] | undefined,\n): string[] | undefined {\n if (named) return named;\n const read = asIntents(intents);\n if (read.some((intent) => intent.actionTypes === undefined && intent.fields.includes(\"actions\"))) return undefined;\n const own = read.flatMap((intent) => intent.actionTypes ?? []);\n return own.length === 0 ? undefined : [...new Set(own)];\n}\n\n/** The action breakdowns a read's intents slice actions by (revenue and funnel: action_type), none when none does. */\nexport function intentActionBreakdowns(intents: string | readonly string[] | undefined): string[] | undefined {\n const own = asIntents(intents).flatMap((intent) => intent.actionBreakdowns ?? []);\n return own.length === 0 ? undefined : [...new Set(own)];\n}\n\nfunction getIntent(name: string): IntentDefinition | undefined {\n return INSIGHTS_INTENTS[name as InsightsIntent];\n}\n\nexport function listIntents(): IntentDefinition[] {\n return Object.values(INSIGHTS_INTENTS);\n}\n","import {\n compactInsightsRows,\n firstRows,\n inReadingOrder,\n insightsTable,\n intentColumns,\n isTimeSeries,\n shownRows,\n withIntentFigures,\n} from \"@baker/api/ads-meta/insightsActions\";\nimport {\n type CompareWindow,\n flatComparisons,\n parseCompare,\n windowPeriod,\n withComparisons,\n withJoinId,\n} from \"@baker/api/ads-meta/insightsCompare\";\nimport {\n composeFields,\n DEFAULT_ATTRIBUTION_WINDOWS,\n DEFAULT_DATE_PRESET,\n DEFAULT_FILTERING,\n type InsightsIntent,\n type InsightsLevel,\n intentActionBreakdowns,\n intentActionTypes,\n listIntents,\n parseIntents,\n withActionFields,\n withSpendField,\n} from \"@baker/api/ads-meta/insightsIntents\";\nimport { DATE_PRESETS_TAKEN, metaDatePreset } from \"@baker/api/ads-meta/insightsPeriod\";\nimport { defineCommand } from \"citty\";\nimport { z } from \"zod\";\nimport { NO_CACHE_ARG } from \"../../../cache-flag.ts\";\nimport { apiGet, apiPost } from \"../../../client.ts\";\nimport { withWindowSpellings } from \"../../../date-window.ts\";\nimport { withEffect } from \"../../../schemas.ts\";\nimport { writeAdsJson, writeAdsOutput, writeJsonEnvelope } from \"../output.ts\";\nimport {\n campaignsAnswered,\n metaBreakdownSyncedHint,\n type SyncedLevel,\n type SyncedRead,\n syncedFirstHint,\n} from \"../synced-first.ts\";\nimport { placementDeliveryHints } from \"./placement-delivery.ts\";\nimport { csvOrJson, getDateRange, handleMetaError, todayIso } from \"./shared.ts\";\n\n/** Rows asked of Meta at least, whatever is printed: the ones printed are the top of the whole read, not Meta's first page. */\nconst ROWS_READ = 1000;\n\nconst POLL_FIRST_MS = 5_000;\nconst POLL_LONGEST_MS = 30_000;\nconst POLL_MAX_MS = 10 * 60_000;\n\n/**\n * The wait before status poll `attempt` (0-based): 5s, growing by half each\n * poll, at most 30s. Every poll is a read from the ad account's hourly Meta\n * budget, and a long report gains nothing from being asked every 5 seconds.\n */\nexport function asyncPollDelayMs(attempt: number): number {\n return Math.min(Math.round(POLL_FIRST_MS * 1.5 ** attempt), POLL_LONGEST_MS);\n}\n\nexport interface InsightsBody {\n object: string;\n level: InsightsLevel;\n fields: string[];\n datePreset?: string;\n since?: string;\n until?: string;\n timeIncrement?: string;\n breakdowns?: string[];\n actionBreakdowns?: string[];\n filtering?: Array<{ field: string; operator: string; value: string | number | string[] }>;\n attributionWindows?: string[];\n useAccountAttributionSetting?: boolean;\n useUnifiedAttributionSetting?: boolean;\n limit?: number;\n skipCache?: boolean;\n}\n\nfunction commaSplit(input: string | undefined): string[] | undefined {\n if (!input) return undefined;\n return input\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\n/** The shape Meta's insights route accepts for `filtering`. */\nconst filteringSchema = z.array(\n z.object({\n field: z.string(),\n operator: z.string(),\n value: z.union([z.string(), z.number(), z.array(z.string())]),\n }),\n);\n\nfunction parseFiltering(raw: string | undefined): InsightsBody[\"filtering\"] {\n if (!raw) return undefined;\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n handleMetaError(new Error(\"Invalid --filtering JSON\"));\n }\n const parsed = filteringSchema.safeParse(json);\n if (!parsed.success) {\n writeAdsJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message:\n '--filtering must be a JSON array of {field,operator,value}, e.g. \\'[{\"field\":\"ad.name\",\"operator\":\"CONTAIN\",\"value\":\"SPRING\"}]\\'',\n },\n });\n process.exit(1);\n }\n return parsed.data;\n}\n\n/** `--intent`, one or several comma-separated (`ranking,funnel`); baseline when absent. */\nfunction intentsOf(args: Record<string, unknown>): InsightsIntent[] {\n const intents = parseIntents(commaSplit(args.intent as string | undefined) ?? []);\n if (!(\"unknown\" in intents)) return intents;\n writeAdsJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `Unknown --intent: ${intents.unknown.join(\", \")}. Use --list-intents to see options.`,\n },\n });\n process.exit(1);\n}\n\n/** The conversions the read keeps: `--action-types`, else the intents' own. */\nfunction actionTypesOf(args: Record<string, unknown>): string[] | undefined {\n return intentActionTypes(intentsOf(args), commaSplit(args[\"action-types\"] as string | undefined));\n}\n\n/** `--limit`: rows to print, 0 for every row; absent leaves it to the level's default. */\nfunction pickLimit(raw: unknown): number | undefined {\n if (raw === undefined) return undefined;\n const limit = Number(raw);\n if (!Number.isInteger(limit) || limit < 0) {\n handleMetaError(new Error(\"--limit must be a whole number of rows, or 0 for every row\"));\n }\n return limit;\n}\n\nfunction pickLevel(args: Record<string, unknown>): InsightsLevel {\n const raw = args.level as string | undefined;\n if (!raw) return \"account\";\n if (raw !== \"account\" && raw !== \"campaign\" && raw !== \"adset\" && raw !== \"ad\") {\n handleMetaError(new Error(\"--level must be one of: account|campaign|adset|ad\"));\n }\n return raw;\n}\n\n/**\n * Auto-async heuristic. Heavy queries that would time out as sync go async\n * automatically — the user shouldn't have to think about it.\n *\n * - level=ad with breakdowns\n * - >2 breakdowns at any level\n * - explicit time range > 90 days\n * - level=ad over an account-level object with a wide window\n */\nfunction shouldAutoAsync(body: InsightsBody): boolean {\n const breakdownCount = (body.breakdowns ?? []).length;\n if (body.level === \"ad\" && breakdownCount > 0 && body.object.startsWith(\"act_\")) {\n return true;\n }\n if (breakdownCount > 2) {\n return true;\n }\n if (body.since && body.until) {\n const days = (Date.parse(body.until) - Date.parse(body.since)) / 86_400_000;\n if (days > 90) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether to take the async path — three states, not two.\n *\n * citty resolves `--no-async` to `async: false` rather than filling a separate\n * `no-async` arg, so reading `args[\"no-async\"]` (as this did) always saw\n * undefined and the documented refusal never applied: a heavy query went async\n * no matter what the caller asked for.\n */\nexport function wantsAsync(asyncFlag: unknown, body: InsightsBody): boolean {\n if (asyncFlag === true) return true;\n if (asyncFlag === false) return false;\n return shouldAutoAsync(body);\n}\n\n/** A value Meta does not take, refused before Meta is asked, naming the ones it does. */\nfunction refuseValue(flag: string, got: string, taken: string): never {\n const message = `${flag} takes ${taken}; got \"${got}\"`;\n writeAdsJson({\n ok: false,\n error: { code: \"VALIDATION_ERROR\", message, fix: { action: \"reject\", explanation: message }, retryable: false },\n });\n process.exit(1);\n}\n\nconst MAX_INCREMENT_DAYS = 90;\nconst TIME_INCREMENTS_TAKEN = `1 (a row per day), 2 to ${MAX_INCREMENT_DAYS} (a row per that many days), monthly or all_days`;\n\n/** `--time-increment` as Meta spells it (`daily` is 1), refused when Meta does not take it. */\nfunction pickTimeIncrement(raw: unknown): string | undefined {\n if (raw === undefined) return undefined;\n const value = String(raw).trim().toLowerCase();\n if (value === \"monthly\" || value === \"all_days\") return value;\n const spelled = value === \"day\" || value === \"daily\" ? \"1\" : value;\n const days = /^\\d+$/.test(spelled) ? Number(spelled) : 0;\n if (days >= 1 && days <= MAX_INCREMENT_DAYS) return String(days);\n return refuseValue(\"--time-increment\", String(raw), TIME_INCREMENTS_TAKEN);\n}\n\nfunction applyDateRange(body: InsightsBody, args: Record<string, unknown>): void {\n const range = getDateRange(args);\n if (range.datePreset) {\n body.datePreset =\n metaDatePreset(range.datePreset) ?? refuseValue(\"--date-preset\", range.datePreset, DATE_PRESETS_TAKEN);\n }\n if (range.since) body.since = range.since;\n if (range.until) body.until = range.until;\n if (!body.datePreset && !(body.since && body.until)) {\n body.datePreset = DEFAULT_DATE_PRESET;\n }\n}\n\n/** Every `effective_status` Meta reports for a campaign, ad set or ad. */\nconst EVERY_EFFECTIVE_STATUS = [\n \"ACTIVE\",\n \"PAUSED\",\n \"DELETED\",\n \"ARCHIVED\",\n \"PENDING_REVIEW\",\n \"DISAPPROVED\",\n \"PREAPPROVED\",\n \"PENDING_BILLING_INFO\",\n \"CAMPAIGN_PAUSED\",\n \"ADSET_PAUSED\",\n \"IN_PROCESS\",\n \"WITH_ISSUES\",\n];\n\n/**\n * A filter on a campaign's, ad set's or ad's own field (`ad.name`, `campaign.id`)\n * makes Meta leave archived and deleted ones out of the read, so their spend\n * disappears from a history; each such entity gets every status unless the\n * caller filtered its status already.\n */\nfunction withEveryStatus(filtering: NonNullable<InsightsBody[\"filtering\"]>): InsightsBody[\"filtering\"] {\n const unstated = [\"campaign\", \"adset\", \"ad\"].filter(\n (entity) =>\n filtering.some(({ field }) => field.startsWith(`${entity}.`)) &&\n !filtering.some(({ field }) => field === `${entity}.effective_status`),\n );\n return [\n ...filtering,\n ...unstated.map((entity) => ({\n field: `${entity}.effective_status`,\n operator: \"IN\",\n value: EVERY_EFFECTIVE_STATUS,\n })),\n ];\n}\n\nfunction buildFiltering(args: Record<string, unknown>): InsightsBody[\"filtering\"] {\n const explicit = parseFiltering(args.filtering as string | undefined);\n if (explicit) return withEveryStatus(explicit);\n if (args[\"include-undelivered\"]) return undefined;\n return DEFAULT_FILTERING;\n}\n\n/**\n * The windows Meta is asked for. A compact read naming click or view windows asks for Meta's default ones too:\n * Meta leaves out a window that counted nothing and sends no split at all when only that window was asked, so\n * without them a conversion counted 0 in the asked window could not be told from one Meta never splits\n * (BAKER-2422). The compact view prints only the asked windows.\n */\nfunction buildAttributionWindows(args: Record<string, unknown>): string[] | undefined {\n const explicit = commaSplit(args[\"attribution-windows\"] as string | undefined);\n if (!explicit) return DEFAULT_ATTRIBUTION_WINDOWS;\n const named = namedWindows(args);\n if (args.full || !named || !named.every((window) => CLICK_OR_VIEW_WINDOW.test(window))) return explicit;\n return [...new Set([...explicit, ...DEFAULT_ATTRIBUTION_WINDOWS])];\n}\n\nconst CLICK_OR_VIEW_WINDOW = /^\\d+d_(click|view)$/;\n\n/**\n * The windows a read names in place of Meta's default (`--attribution-windows 7d_click`), whose figures each\n * compact `value` then holds; undefined for the default, or when an attribution setting decides instead.\n */\nfunction namedWindows(args: Record<string, unknown>): string[] | undefined {\n if (args[\"use-account-attribution\"] || args[\"use-unified-attribution\"]) return undefined;\n const explicit = commaSplit(args[\"attribution-windows\"] as string | undefined);\n if (!explicit) return undefined;\n const isDefault =\n (explicit.length === 1 && explicit[0] === \"default\") ||\n (explicit.length === DEFAULT_ATTRIBUTION_WINDOWS.length &&\n DEFAULT_ATTRIBUTION_WINDOWS.every((window) => explicit.includes(window)));\n return isDefault ? undefined : explicit;\n}\n\nfunction buildBody(args: Record<string, unknown>): InsightsBody {\n const intents = intentsOf(args);\n const level = pickLevel(args);\n const explicitFields = commaSplit(args.fields as string | undefined);\n const fields = withSpendField(withActionFields(explicitFields ?? composeFields(intents, level), actionTypesOf(args)));\n const breakdowns = commaSplit(args.breakdowns as string | undefined);\n const actionBreakdowns =\n commaSplit(args[\"action-breakdowns\"] as string | undefined) ?? intentActionBreakdowns(intents);\n\n const body: InsightsBody = {\n object: args.object as string,\n level,\n fields,\n timeIncrement: pickTimeIncrement(args[\"time-increment\"]),\n breakdowns,\n actionBreakdowns,\n filtering: buildFiltering(args),\n attributionWindows: buildAttributionWindows(args),\n useAccountAttributionSetting: Boolean(args[\"use-account-attribution\"]),\n useUnifiedAttributionSetting: Boolean(args[\"use-unified-attribution\"]),\n limit: Math.max(ROWS_READ, pickLimit(args.limit) ?? 0),\n skipCache: Boolean(args[\"no-cache\"]),\n };\n applyDateRange(body, args);\n if (args.compare) body.fields = withJoinId(body.fields, level);\n return body;\n}\n\nasync function pollAsync(reportRunId: string): Promise<void> {\n const start = Date.now();\n for (let attempt = 0; Date.now() - start < POLL_MAX_MS; attempt++) {\n // The status route is a GET reading `report-run-id` from the query string.\n // Posting to it matched no route at all, so every heavy query died on a\n // bare 404 the moment it went async.\n const status = await apiGet<{ async_status?: string; async_percent_completion?: number }>(\n \"/api/ads/meta/insights/async/status\",\n { \"report-run-id\": reportRunId },\n );\n if (status.async_status === \"Job Completed\") return;\n if (status.async_status === \"Job Failed\" || status.async_status === \"Job Skipped\") {\n handleMetaError(new Error(`Async insights job ${status.async_status}`));\n }\n process.stderr.write(\n `Async insights ${status.async_status ?? \"queued\"} (${Math.round(status.async_percent_completion ?? 0)}%)…\\n`,\n );\n await new Promise((resolve) => setTimeout(resolve, asyncPollDelayMs(attempt)));\n }\n handleMetaError(new Error(\"Async insights polling timed out after 10 minutes\"));\n}\n\nasync function runAsync(body: InsightsBody): Promise<Array<Record<string, unknown>>> {\n const submit = await apiPost<{ reportRunId: string }>(\"/api/ads/meta/insights/async\", body);\n process.stderr.write(`Async insights job: ${submit.reportRunId}\\n`);\n await pollAsync(submit.reportRunId);\n return apiPost<Array<Record<string, unknown>>>(\"/api/ads/meta/insights/async/result\", {\n reportRunId: submit.reportRunId,\n fields: body.fields,\n limit: body.limit,\n });\n}\n\nconst META_GRAIN: Record<string, SyncedRead[\"grain\"]> = { \"1\": \"day\", \"7\": \"week\", monthly: \"month\" };\n\n/** The days Meta answered the read with: a calendar preset (last_month, maximum…) is its account's own dates. */\nfunction answeredDays(rows: ReadonlyArray<Record<string, unknown>>): { start: string; end: string } | undefined {\n const starts = rows.map((row) => row.date_start).filter((day): day is string => typeof day === \"string\");\n const ends = rows.map((row) => row.date_stop).filter((day): day is string => typeof day === \"string\");\n if (starts.length === 0 || ends.length === 0) return undefined;\n return { start: starts.reduce((a, b) => (a < b ? a : b)), end: ends.reduce((a, b) => (a > b ? a : b)) };\n}\n\n/**\n * The insights window as the synced copy spells it; null for a read of today alone, or one whose days are unknown:\n * a calendar preset (last_month, maximum…) split into buckets, whose rows name only the days that delivered.\n */\nfunction syncedWindow(\n body: InsightsBody,\n rows: ReadonlyArray<Record<string, unknown>>,\n): NonNullable<SyncedRead[\"window\"]> | null {\n if (body.datePreset === \"today\") return null;\n if (body.datePreset === \"yesterday\") return { days: 1 };\n const days = /^last_(\\d+)d$/.exec(body.datePreset ?? \"\")?.[1];\n if (days !== undefined) return { days: Number(days) };\n const window =\n body.since && body.until\n ? { start: body.since, end: body.until }\n : isTimeSeries(body.timeIncrement)\n ? undefined\n : answeredDays(rows);\n return window === undefined || window.start >= todayIso() ? null : window;\n}\n\n/**\n * The first day of the window in the account's own dates, so seven-day buckets are named as synced weeks only when\n * both start on a Monday: Meta anchors every bucket to it, so any bucket's first day falls on its weekday.\n */\nfunction windowStart(window: NonNullable<SyncedRead[\"window\"]>, rows: ReadonlyArray<Record<string, unknown>>) {\n if (\"start\" in window) return window.start;\n return answeredDays(rows)?.start;\n}\n\n/**\n * The `baker ads performance` read that answers the same insights read; null when the synced copy cannot.\n * `previousPeriod` is true only for a `--compare previous_period`, the one baseline the synced `--compare` reads.\n */\nfunction syncedHintOf(\n body: InsightsBody,\n rows: ReadonlyArray<Record<string, unknown>>,\n previousPeriod: boolean,\n): string | null {\n const window = syncedWindow(body, rows);\n if (window === null) return null;\n const breakdowns = body.breakdowns ?? [];\n if (breakdowns.length > 0) return metaBreakdownSyncedHint(breakdowns, window);\n const level: SyncedLevel = body.level === \"adset\" ? \"ad_group\" : body.level;\n const grain = body.timeIncrement === undefined ? undefined : META_GRAIN[body.timeIncrement];\n if (grain === \"week\") {\n const start = windowStart(window, rows);\n if (start === undefined || new Date(`${start}T00:00:00Z`).getUTCDay() !== 1) return null;\n }\n return syncedFirstHint(\"meta\", level, { window, grain, compare: previousPeriod, campaigns: campaignsAnswered(rows) });\n}\n\n/** `--fields` without spend: it is still read, to rank the rows, and left out of what prints. */\nfunction spendUnasked(args: Record<string, unknown>): boolean {\n const explicit = commaSplit(args.fields as string | undefined);\n return explicit !== undefined && !explicit.includes(\"spend\");\n}\n\n/** The read in its order (by spend, a series by date, or Meta's own with --no-sort), cut to the rows `--limit` prints. */\nfunction rowsToPrint(rows: Array<Record<string, unknown>>, body: InsightsBody, args: Record<string, unknown>) {\n const shown = shownRows(body.level, pickLimit(args.limit));\n if (args[\"no-sort\"]) return firstRows(rows, shown, \"as Meta sent them\");\n const order = isTimeSeries(body.timeIncrement) ? \"the earliest dates first\" : \"the most spend first\";\n return firstRows(inReadingOrder(rows, body.timeIncrement), shown, order);\n}\n\n/** The compact rows, or Meta's own with --full, and the hint naming what the compact view dropped. */\nfunction shapeRows(\n rows: Array<Record<string, unknown>>,\n args: Record<string, unknown>,\n): { rows: Array<Record<string, unknown>>; hints: string[] } {\n if (args.full) return { rows, hints: [] };\n const actionTypes = actionTypesOf(args);\n const {\n rows: compacted,\n dropped,\n folded,\n disagreements,\n windowHints,\n } = compactInsightsRows(rows, {\n actionTypes,\n windows: namedWindows(args),\n });\n const compact = withIntentFigures(compacted, intentsOf(args), { actionTypes });\n const foldHints =\n folded === null\n ? []\n : [\n `Meta's other names for one conversion print under its plain name (${folded}); read it by that name, or --action-types <raw name> keeps Meta's own name in actions, conversions and their values and costs.`,\n ];\n if (dropped.length === 0) return { rows: compact, hints: [...foldHints, ...disagreements, ...windowHints] };\n const named = dropped.slice(0, 4).join(\", \");\n const more = dropped.length > 4 ? ` and ${dropped.length - 4} more` : \"\";\n return {\n rows: compact,\n hints: [\n `Engagement and combined action types were left out (${named}${more}); --action-types <type> keeps one, --full returns every raw action.`,\n ...foldHints,\n ...disagreements,\n ...windowHints,\n ],\n };\n}\n\n/** One read, sync or async as `--async` and the heuristic decide. */\nfunction readRows(body: InsightsBody, asyncFlag: unknown): Promise<Array<Record<string, unknown>>> {\n return wantsAsync(asyncFlag, body)\n ? runAsync(body)\n : apiPost<Array<Record<string, unknown>>>(\"/api/ads/meta/insights\", body);\n}\n\n/** `--compare`, refused for a series: a row per day has no one row to set beside it in another window. */\nfunction pickCompare(raw: unknown, body: InsightsBody): CompareWindow[] | undefined {\n if (raw === undefined || raw === \"\") return undefined;\n const windows = isTimeSeries(body.timeIncrement)\n ? \"--compare sets one window beside another; drop --time-increment, or read the series without it\"\n : parseCompare(String(raw));\n if (typeof windows !== \"string\") return windows;\n writeAdsJson({ ok: false, error: { code: \"VALIDATION_ERROR\", message: windows } });\n process.exit(1);\n}\n\n/**\n * The same read over every `--compare` window, shaped as the printed rows are,\n * with the hints its shaping gave, each naming its window. Rows are null for a\n * window that could not be read.\n */\nfunction readWindows(\n windows: CompareWindow[],\n body: InsightsBody,\n current: Array<Record<string, unknown>>,\n args: Record<string, unknown>,\n): Promise<Array<{ label: string; rows: Array<Record<string, unknown>> | null; hints: string[] }>> {\n const { datePreset: _preset, since: _since, until: _until, ...rest } = body;\n return Promise.all(\n windows.map(async (window) => {\n const period = windowPeriod(window, body, current);\n if (period === null) return { label: window.label, rows: null, hints: [] };\n const shaped = printedRows(await readRows({ ...rest, ...period }, args.async), args);\n return {\n label: window.label,\n rows: flatTable(shaped.rows, body, args).rows,\n hints: shaped.hints.map((hint) => `${window.label}: ${hint}`),\n };\n }),\n );\n}\n\n/** The rows as printed: spend left out where `--fields` did not ask for it, then compacted. */\nfunction printedRows(rows: Array<Record<string, unknown>>, args: Record<string, unknown>) {\n return shapeRows(spendUnasked(args) ? rows.map(({ spend: _spend, ...row }) => row) : rows, args);\n}\n\n/** The fields printed, in order: spend only when asked for, and the columns the intents add. */\nfunction printedFields(body: InsightsBody, args: Record<string, unknown>): string[] {\n const fields = spendUnasked(args) ? body.fields.filter((field) => field !== \"spend\") : body.fields;\n return args.full ? fields : [...fields, ...intentColumns(intentsOf(args), actionTypesOf(args))];\n}\n\n/** Printed rows with one column per action type, as `--output md|csv` shows them. */\nfunction flatTable(rows: Array<Record<string, unknown>>, body: InsightsBody, args: Record<string, unknown>) {\n return insightsTable(rows, printedFields(body, args), { priceAll: actionTypesOf(args) !== undefined });\n}\n\n/**\n * The JSON envelope with its hints ahead of the rows, and the synced read on stderr too, first: a long read cut\n * with `head` or projected to `.data` still shows which read answers it without the rate limit (BAKER-3382).\n */\nfunction writeInsightsJson(data: unknown, lead: string[], hints: string[]): void {\n for (const hint of lead) process.stderr.write(`${hint}\\n`);\n writeJsonEnvelope({ ok: true, hints: [...lead, ...hints], data });\n}\n\n/** The printed rows with every `--compare` window beside them: nested in json, one column per figure otherwise. */\nasync function printCompared(input: {\n windows: CompareWindow[];\n body: InsightsBody;\n args: Record<string, unknown>;\n fmt: string;\n rows: Array<Record<string, unknown>>;\n printed: { rows: Array<Record<string, unknown>>; hints: string[] };\n}): Promise<void> {\n const { body, args } = input;\n const windows = await readWindows(input.windows, body, input.rows, args);\n const table = flatTable(input.printed.rows, body, args);\n const compared = withComparisons(table.rows, windows, body.breakdowns ?? [], input.rows);\n const previousPeriod = input.windows.length === 1 && input.windows[0]?.label === \"previous_period\";\n const synced = syncedHintOf(body, input.rows, previousPeriod);\n const ownHints = new Set(input.printed.hints);\n const windowHints = windows.flatMap((window) =>\n window.hints.filter((hint) => !ownHints.has(hint.slice(window.label.length + 2))),\n );\n const lead = synced === null ? [] : [synced];\n const hints = [...input.printed.hints, ...windowHints, ...compared.hints];\n if (input.fmt === \"json\") {\n writeInsightsJson(compared.rows, lead, [...placementDeliveryHints(input.rows), ...hints]);\n return;\n }\n const flat = flatComparisons(compared.rows, table.columns);\n writeAdsOutput(flat.rows, input.fmt, flat.columns, [...lead, ...hints]);\n}\n\nexport const insightsCommand = withEffect(\n {\n effect: \"read_live\",\n routes: [\n \"POST /api/ads/meta/insights\",\n \"POST /api/ads/meta/insights/async\",\n \"GET /api/ads/meta/insights/async/status\",\n \"POST /api/ads/meta/insights/async/result\",\n ],\n },\n defineCommand({\n meta: {\n name: \"insights\",\n description: `Performance reporting — the main Meta tool for AI agents.\n\nSmart defaults so the AI doesn't have to remember every flag:\n --level account (set --level campaign|adset|ad to drill in)\n --intent baseline (or leads|revenue|funnel|ranking|video|identity)\n --date-preset last_7d (override with --since/--until)\n --attribution-windows 7d_click,1d_view (the only ones still working post Jan 2026)\n filter: impressions > 0 (skip undelivered rows; --include-undelivered to keep)\n sort: spend descending (a --time-increment read: by date, earliest first)\n --limit 25 at --level ad|adset (the top of the whole read; a hint says how many more, --limit 0 prints all)\n auto-async when query is heavy (level=ad + breakdowns, big date ranges, etc.)\n\nIdentity fields (campaign_name, ad_name etc.) are appended automatically based on --level so rows\nare self-describing.\n\nExamples — common AI questions:\n # \"How is GreenLeaf doing this week?\"\n baker ads meta insights --object act_123\n\n # \"How many leads, and at what cost?\" — spend, actions.lead and cost_per.actions.lead per row\n baker ads meta insights --object act_123 --intent leads --date-preset last_14d --output md\n\n # \"Which campaigns are profitable?\"\n baker ads meta insights --object act_123 --level campaign --intent revenue --date-preset last_28d\n\n # \"Which creatives need a refresh?\"\n baker ads meta insights --object act_123 --level ad --intent ranking --date-preset last_14d\n\n # \"Registrations and cost per registration, this week vs last?\" — one call; each row gets compare.<window>\n baker ads meta insights --object act_123 --level campaign --since 2026-09-21 --until 2026-09-27 --compare previous_period --action-types complete_registration\n\n # \"Is this ad fatiguing?\" — 3 days against 7 and 30, frequency/CTR/CPM with their % change\n baker ads meta insights --object <adId> --level ad --fields ad_id,frequency,ctr,cpm --date-preset last_3d --compare last_7d,last_30d --output md\n\n # \"Where do users drop off the funnel?\"\n baker ads meta insights --object act_123 --intent funnel\n\n # \"Which ads to keep?\" — intents combine: rankings, delivery and funnel in one row per ad, one call\n baker ads meta insights --object act_123 --level ad --intent ranking,baseline,funnel --output md\n\n # \"Should we shift budget to Instagram?\"\n baker ads meta insights --object act_123 --level adset --breakdowns publisher_platform,platform_position\n\n # \"How many sign-ups and leads per month?\" — one call, one row per month\n baker ads meta insights --object act_123 --intent revenue --action-types complete_registration,lead --time-increment monthly --since 2026-01-01 --until 2026-03-31\n\n # \"Cost per lead per campaign?\" / \"Cost per <custom conversion> per ad?\" (its id from custom-conversions)\n baker ads meta insights --object act_123 --level ad --action-types 1119307438661117 --output md\n\n # \"Daily spend of the ads whose name holds a token?\" — Meta sums only those ads, archived ones included\n baker ads meta insights --object act_123 --time-increment 1 --since 2026-09-28 --until 2026-10-04 --filtering '[{\"field\":\"ad.name\",\"operator\":\"CONTAIN\",\"value\":\"RUBEN\"}]'\n\n # \"Brazil only, by day?\" — one breakdown value, filtered by Meta\n baker ads meta insights --object act_123 --breakdowns country --time-increment 1 --filtering '[{\"field\":\"country\",\"operator\":\"IN\",\"value\":[\"BR\"]}]'\n\n # Custom field set (escape hatch)\n baker ads meta insights --object act_123 --fields impressions,spend,actions\n\nAction arrays (actions, cost_per_action_type, conversions, …) are compact: Meta's aliases of one conversion\n(omni_, offsite_conversion.fb_pixel_, onsite_web_ …) collapse to one entry under its plain name\n(complete_registration, lead, purchase), and engagement counts (likes, saves, video views) are left out. Every\nentry has a value: when Meta sent none, a count's window figures summed, else 0; a cost, ROAS or rate says null.\n--attribution-windows other than the default (7d_click for click-only) makes value those windows alone, every named\nwindow set (0 where Meta counted none, null where it sent one total it did not split): Meta's own value, kept by\n--full, is its 7d_click,1d_view total whatever was asked.\n--action-types keeps only the named types; --full returns Meta's raw arrays. --output md|csv gives each\naction type its own column (actions.lead, cost_per_action_type.lead); a custom event, or every type --action-types\nnames, also gets its cost (cost_per.conversions.<type> = spend / count). --intent funnel adds result_type, results,\ncvr (% of link clicks) and cost_per_result to each row; --action-types <type> picks which action is the result.\n--compare <windows> reads the same thing over each window (previous_period, a preset, or YYYY-MM-DD..YYYY-MM-DD) and\nsets it beside each row as compare.<window>: that window's figures and change_pct, the % change from it to the read.\n\nAsync is automatic for heavy queries; pass --async to force it, or --no-async to refuse fallback.`,\n },\n args: withWindowSpellings({\n object: {\n type: \"string\",\n description: \"Object ID — act_<id> for account, or a campaign/adset/ad ID\",\n },\n level: { type: \"string\", description: \"account|campaign|adset|ad (default: account)\" },\n intent: {\n type: \"string\",\n description:\n \"baseline|leads|revenue|funnel|ranking|video|identity (default: baseline); several comma-separated read together, one row per object (ranking,funnel)\",\n },\n fields: { type: \"string\", description: \"Comma-separated field list (overrides --intent bundle)\" },\n \"list-intents\": { type: \"boolean\", description: \"Print available intents and exit\" },\n \"date-preset\": {\n type: \"string\",\n description:\n \"Meta date preset: today, yesterday, last_3d|7d|14d|28d|30d|90d, this_month, last_month, this_year, maximum (lifetime), …; any other is refused with the list\",\n },\n since: { type: \"string\", description: \"Custom start date YYYY-MM-DD\" },\n until: { type: \"string\", description: \"Custom end date YYYY-MM-DD\" },\n \"time-increment\": {\n type: \"string\",\n description: \"1 or daily (a row per day) | 2-90 (a row per that many days) | monthly | all_days\",\n },\n breakdowns: { type: \"string\", description: \"Comma-separated breakdowns (e.g. publisher_platform,age)\" },\n \"action-types\": {\n type: \"string\",\n description:\n \"Keep only these action types in actions/cost_per_action_type/conversions — plain names (complete_registration,lead,purchase), a raw Meta name, a custom event's name, or a custom conversion's id. Works with any intent: it asks for actions when the intent has none.\",\n },\n full: { type: \"boolean\", description: \"Return Meta's raw action arrays: every alias and engagement type\" },\n \"action-breakdowns\": {\n type: \"string\",\n description: \"Slice the actions[] array (default: action_type for revenue/funnel)\",\n },\n filtering: {\n type: \"string\",\n description:\n 'Meta filters the rows before they are sent — JSON array of {field,operator,value}, replacing the default impressions>0 filter. One name token at any level: \\'[{\"field\":\"ad.name\",\"operator\":\"CONTAIN\",\"value\":\"SPRING\"}]\\' (case-insensitive; also campaign.name, adset.name, ad.id IN [...]); archived and deleted entities are kept unless you filter their effective_status. One breakdown value: \\'[{\"field\":\"country\",\"operator\":\"IN\",\"value\":[\"BR\"]}]\\' with --breakdowns country (publisher_platform, platform_position, age, gender too).',\n },\n \"include-undelivered\": { type: \"boolean\", description: \"Keep rows where impressions=0 (off by default)\" },\n \"attribution-windows\": {\n type: \"string\",\n description:\n \"Override default 7d_click,1d_view (only 1d_view, 1d_click, 7d_click, 28d_click work post Jan 2026). Start here for click-only: --attribution-windows 7d_click — each compact value then counts the named windows alone, each window key set (0 where Meta counted none, null where it did not split its total).\",\n },\n \"use-account-attribution\": { type: \"boolean\", description: \"Use account-saved attribution setting\" },\n \"use-unified-attribution\": { type: \"boolean\", description: \"Use ad-set unified attribution setting\" },\n limit: {\n type: \"string\",\n description:\n \"Rows to print (default 25 at --level ad|adset, every row otherwise; 0 prints every row). The rows printed are the top of the whole read, in its order.\",\n },\n // Declaring `no-async` too would be a trap: citty resolves it to `async: false`\n // and never fills an arg of that name, so the declaration reads as supported\n // while nothing consumes it.\n async: { type: \"boolean\", description: \"Force the async submit-and-poll path (--no-async refuses it)\" },\n \"no-sort\": {\n type: \"boolean\",\n description: \"Keep Meta's own row order (default: by spend, or by date with --time-increment)\",\n },\n compare: {\n type: \"string\",\n description:\n \"Set each row beside the same read over other windows, with every figure's change in % (compare.<window>.change_pct): previous_period (as many days just before), a Meta preset (last_30d) or YYYY-MM-DD..YYYY-MM-DD, comma-separated. Rows are flat, one key per action type. Not with --time-increment.\",\n },\n \"no-cache\": NO_CACHE_ARG,\n output: { type: \"string\", description: \"Output format: json|csv|jsonl|md\", default: \"json\" },\n }),\n run: async ({ args }) => {\n if (args[\"list-intents\"]) {\n writeAdsJson({ ok: true, data: listIntents() });\n return;\n }\n\n if (!args.object) {\n writeAdsJson({\n ok: false,\n error: { code: \"VALIDATION_ERROR\", message: \"Missing required argument: --object\" },\n });\n process.exit(1);\n }\n\n const body = buildBody(args);\n const fmt = csvOrJson(args);\n const compare = pickCompare(args.compare, body);\n\n try {\n const rows = await readRows(body, args.async);\n const cut = rowsToPrint(rows, body, args);\n const shaped = printedRows(cut.rows, args);\n const sorted = shaped.rows;\n if (cut.leftOut !== null) shaped.hints.push(`${cut.leftOut}; --limit <n> prints more, --limit 0 every row.`);\n if (compare !== undefined) {\n await printCompared({ windows: compare, body, args, fmt, rows, printed: shaped });\n return;\n }\n\n const synced = syncedHintOf(body, rows, false);\n const lead = synced === null ? [] : [synced];\n if (fmt !== \"json\") {\n const table =\n args.full || fmt === \"jsonl\"\n ? { rows: sorted, columns: printedFields(body, args) }\n : flatTable(sorted, body, args);\n writeAdsOutput(table.rows, fmt, table.columns, [...lead, ...shaped.hints]);\n return;\n }\n writeInsightsJson(sorted, lead, [...placementDeliveryHints(rows), ...shaped.hints]);\n } catch (err) {\n handleMetaError(err);\n }\n },\n }),\n);\n","import { placementFormatNote, previewFormatForPosition } from \"@baker/api/ads-meta\";\n\n/**\n * Reads a placement breakdown the way the question \"why does my video show as a\n * still image?\" actually needs to be answered: with this account's own numbers.\n *\n * The failure this replaces is an agent recalling a list of \"image-only\n * placements\" (most of it wrong) and inventing a mechanism Meta does not\n * document. Impressions against video plays, per placement, is the cheap\n * empirical check — it costs one query the agent already ran, and it is\n * account evidence rather than a rule. So the hints below name a suspect and\n * hand over the command that confirms it; they never conclude.\n */\n\n/**\n * Below this, a placement's play rate is arithmetic on too few impressions to\n * carry a claim. Set against a 90%-ish reference rate, seeing no plays in 20\n * impressions is not something chance produces — so this is low enough to reach\n * the long tail where format problems actually live, and the placements it\n * excludes are the ones nobody could have concluded anything from anyway.\n */\nconst MIN_IMPRESSIONS = 20;\n\n/**\n * How far below the ad's own play rate counts as \"this placement is not playing\".\n *\n * Judged against the ad, not against zero. The account this was built from is\n * the reason: it plays at 93% overall, and the one placement carrying a\n * documented format constraint played at 3.85% — 24x worse, and still above any\n * absolute \"under 2%\" bar. An absolute rule cannot see that at any impression\n * threshold; a relative one calibrates itself per creative and per account.\n */\nconst SILENT_FRACTION_OF_REFERENCE = 0.1;\n\n/** Proof the creative plays at all somewhere, so a flagged placement means something. */\nconst PLAYING_REFERENCE_RATE = 0.5;\n\ninterface PlacementDelivery {\n platform: string;\n position: string;\n impressions: number;\n plays: number;\n playRate: number;\n share: number;\n}\n\nfunction toNumber(value: unknown): number {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n}\n\n/** Meta returns action metrics as `[{ action_type, value }]`; the total is what matters here. */\nfunction sumActionValues(value: unknown): number {\n if (!Array.isArray(value)) return 0;\n return value.reduce<number>((total, entry) => {\n const item = entry as { value?: unknown };\n return total + toNumber(item?.value);\n }, 0);\n}\n\nfunction aggregate(rows: Array<Record<string, unknown>>): PlacementDelivery[] {\n const byPlacement = new Map<string, PlacementDelivery>();\n let totalImpressions = 0;\n\n for (const row of rows) {\n const position = row.platform_position;\n if (typeof position !== \"string\" || position.length === 0) continue;\n const platform = typeof row.publisher_platform === \"string\" ? row.publisher_platform : \"\";\n const impressions = toNumber(row.impressions);\n totalImpressions += impressions;\n const key = `${platform}/${position}`;\n const current = byPlacement.get(key) ?? { platform, position, impressions: 0, plays: 0, playRate: 0, share: 0 };\n current.impressions += impressions;\n current.plays += sumActionValues(row.video_play_actions);\n byPlacement.set(key, current);\n }\n\n return [...byPlacement.values()].map((placement) => ({\n ...placement,\n playRate: placement.impressions > 0 ? placement.plays / placement.impressions : 0,\n share: totalImpressions > 0 ? placement.impressions / totalImpressions : 0,\n }));\n}\n\nfunction previewCommand(placement: PlacementDelivery): string {\n const format = previewFormatForPosition(placement.position, placement.platform);\n return format\n ? `\\`baker ads meta preview --creative-id <id> --placement ${placement.position} --platform ${placement.platform}\\``\n : `no preview format is known for ${placement.position}, so Meta's renderer cannot confirm it — say the placement is unverified rather than filling the gap`;\n}\n\n/**\n * The play rate only means something when every row describes the same\n * creative. Aggregating placements across ads puts an image ad's impressions in\n * the same bucket as a video's plays, which reads as \"this placement doesn't\n * render video\" when it only means \"an image ad ran there\" — the exact wrong\n * conclusion this module exists to prevent. So a query that does not pin one ad\n * (`--level ad --object <adId>`) gets no hint rather than a confounded one.\n */\nfunction isSingleAdQuery(rows: Array<Record<string, unknown>>): boolean {\n const adIds = new Set<string>();\n for (const row of rows) {\n if (typeof row.ad_id !== \"string\" || row.ad_id.length === 0) return false;\n adIds.add(row.ad_id);\n }\n return adIds.size === 1;\n}\n\n/**\n * Placements this account delivered into without the video ever playing.\n *\n * Silent unless the query carried video metrics AND the creative demonstrably\n * plays somewhere else: without a playing reference, a zero everywhere means\n * \"not a video query\", not \"the placement is broken\".\n */\nexport function placementDeliveryHints(rows: Array<Record<string, unknown>>): string[] {\n const carriesVideoMetrics = rows.some((row) => Array.isArray(row.video_play_actions));\n if (!carriesVideoMetrics || !isSingleAdQuery(rows)) return [];\n\n const placements = aggregate(rows);\n const judgeable = placements.filter((p) => p.impressions >= MIN_IMPRESSIONS);\n const impressions = judgeable.reduce((total, p) => total + p.impressions, 0);\n const reference = impressions > 0 ? judgeable.reduce((total, p) => total + p.plays, 0) / impressions : 0;\n if (reference < PLAYING_REFERENCE_RATE) return [];\n\n const silent = judgeable\n .filter((p) => p.playRate < reference * SILENT_FRACTION_OF_REFERENCE)\n .sort((a, b) => b.impressions - a.impressions);\n\n // Never go quiet on a video placement query. Silence is what the agent fills\n // in with a remembered rule, and \"every placement plays\" is the answer to\n // \"why does it show as a still image\" far more often than a placement is.\n if (silent.length === 0) {\n const worst = [...judgeable].sort((a, b) => a.playRate - b.playRate)[0];\n return [\n `Checked every placement above ${MIN_IMPRESSIONS} impressions against this ad's own play rate (${(reference * 100).toFixed(0)}%): no placement is failing to play the video${worst ? `, the lowest being ${worst.platform}/${worst.position} at ${(worst.playRate * 100).toFixed(0)}%` : \"\"}. So placements do not explain a \"it shows as a still image\" report — rule out autoplay off or data saver in the viewer's own app, which renders every video as its cover frame account-wide.`,\n ];\n }\n\n const hints = silent.map((placement) => {\n const note = placementFormatNote(placement.position);\n const documented = note ? ` Meta documents this placement: ${note.note}` : \"\";\n return `${placement.platform}/${placement.position} delivered ${placement.impressions.toLocaleString(\"en-US\")} impressions (${(placement.share * 100).toFixed(1)}% of the total) and ${placement.plays.toLocaleString(\"en-US\")} video plays — it may not be rendering the video. This is account evidence, not a rule: confirm what Meta renders there with ${previewCommand(placement)} before you say anything about it.${documented}`;\n });\n\n const combinedShare = silent.reduce((total, placement) => total + placement.share, 0) * 100;\n hints.push(\n `Those placements are ${combinedShare.toFixed(1)}% of delivery in this query. State that share before proposing to remove them — and note that removing placements from a live ad set is a targeting change, which Meta counts as a significant edit that re-enters the learning phase.`,\n );\n return hints;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,mBAAmB,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGD,IAAM,oBAAoB;AAG1B,IAAM,gBAAgB;AAGtB,IAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAM,eAAe,oBAAI,IAAI,CAAC,kCAAkC,iBAAiB,CAAC;AAGlF,SAAS,cAAc,MAAsB;AAC3C,MAAI,aAAa,IAAI,IAAI,EAAG,QAAO;AACnC,MAAI,KAAK,WAAW,oCAAoC,EAAG,QAAO;AAClE,QAAM,SAAS,eAAe,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC;AAC5D,SAAO,SAAS,KAAK,MAAM,OAAO,MAAM,IAAI;AAC9C;AAEA,SAAS,QAAQ,MAAuB;AACtC,SAAO,iBAAiB,IAAI,IAAI,KAAK,KAAK,WAAW,iBAAiB,KAAK,cAAc,KAAK,IAAI;AACpG;AAEA,SAAS,cAAc,OAAwC;AAC7D,SACE,MAAM,QAAQ,KAAK,KACnB,MAAM,MAAM,CAAC,UAAU,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,MAAM,gBAAgB,QAAQ;AAE/G;AAGA,SAAS,OAAO,WAAmB,QAAoC;AACrE,SACE,OAAO,KA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cAAM,OAAO,MAAM,SAAS,MAAM,KAAK,KAAK;AAC5C,cAAM,MAAM,YAAY,MAAM,MAAM,IAAI;AACxC,cAAM,SAAS,YAAY,IAAI,MAAM,IAAI;AACzC,cAAM,SAAS,OAAO;AACtB,YAAI,IAAI,YAAY,KAAM,QAAO,MAAM,KAAK,GAAG,IAAI,OAAO,iDAAiD;AAC3G,YAAI,YAAY,QAAW;AACzB,gBAAM,cAAc,EAAE,SAAS,SAAS,MAAM,MAAM,KAAK,MAAM,SAAS,OAAO,CAAC;AAChF;AAAA,QACF;AAEA,cAAM,SAAS,aAAa,MAAM,MAAM,KAAK;AAC7C,cAAM,OAAO,WAAW,OAAO,CAAC,IAAI,CAAC,MAAM;AAC3C,YAAI,QAAQ,QAAQ;AAClB,gBAAM,QACJ,KAAK,QAAQ,QAAQ,UACjB,EAAE,MAAM,QAAQ,SAAS,cAAc,MAAM,IAAI,EAAE,IACnD,UAAU,QAAQ,MAAM,IAAI;AAClC,yBAAe,MAAM,MAAM,KAAK,MAAM,SAAS,CAAC,GAAG,MAAM,GAAG,OAAO,KAAK,CAAC;AACzE;AAAA,QACF;AACA,0BAAkB,QAAQ,MAAM,CAAC,GAAG,uBAAuB,IAAI,GAAG,GAAG,OAAO,KAAK,CAAC;AAAA,MACpF,SAAS,KAAK;AACZ,wBAAgB,GAAG;AAAA,MACrB;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["z","z","previousPeriod","windowHints"]}
@@ -6,13 +6,13 @@ import {
6
6
  mergePayload,
7
7
  requireTarget,
8
8
  stageOp
9
- } from "./chunk-6XXKYTD5.js";
9
+ } from "./chunk-BRHYK4HQ.js";
10
10
  import "./chunk-3R62EYYX.js";
11
11
  import "./chunk-GDFJOCDO.js";
12
12
  import {
13
13
  csvOrJson,
14
14
  handleMetaError
15
- } from "./chunk-2W6ILA5Z.js";
15
+ } from "./chunk-LDL5VBBD.js";
16
16
  import "./chunk-S7J2JP3U.js";
17
17
  import "./chunk-UKENQSZ2.js";
18
18
  import "./chunk-D5FY4FAK.js";
@@ -265,4 +265,4 @@ export {
265
265
  instantExperiencesCreateCommand,
266
266
  instantExperiencesUpdateCommand
267
267
  };
268
- //# sourceMappingURL=instant-experiences-KCAH5ONN.js.map
268
+ //# sourceMappingURL=instant-experiences-YXH2AHFI.js.map
@@ -8,7 +8,7 @@ import {
8
8
  requireTarget,
9
9
  stageOp,
10
10
  upper
11
- } from "./chunk-6XXKYTD5.js";
11
+ } from "./chunk-BRHYK4HQ.js";
12
12
  import {
13
13
  isMetaLeadAdsRefusal
14
14
  } from "./chunk-3R62EYYX.js";
@@ -16,7 +16,7 @@ import "./chunk-GDFJOCDO.js";
16
16
  import {
17
17
  csvOrJson,
18
18
  handleMetaError
19
- } from "./chunk-2W6ILA5Z.js";
19
+ } from "./chunk-LDL5VBBD.js";
20
20
  import {
21
21
  withWindowSpellings
22
22
  } from "./chunk-74QGFUZL.js";
@@ -572,4 +572,4 @@ export {
572
572
  leadPageHints,
573
573
  leadsCommand
574
574
  };
575
- //# sourceMappingURL=leads-HU4GA6T4.js.map
575
+ //# sourceMappingURL=leads-IGOXMIEW.js.map
@@ -8,11 +8,11 @@ var metaMediaCommand = defineCommand({
8
8
  description: "Stage Baker library media uploads to Meta so creatives can reference them (upload), or take an image out of the account's image library (delete --image-hash). Upload publishes an ad-image hash or video id a creative binds via --image-ref/--video-ref."
9
9
  },
10
10
  subCommands: {
11
- upload: () => import("./write-commands-PD3BEWWZ.js").then((m) => m.mediaUploadCommand),
12
- delete: () => import("./asset-writes-HXFRHFWF.js").then((m) => m.mediaDeleteCommand)
11
+ upload: () => import("./write-commands-REUTFNJ3.js").then((m) => m.mediaUploadCommand),
12
+ delete: () => import("./asset-writes-ZOVD5O5X.js").then((m) => m.mediaDeleteCommand)
13
13
  }
14
14
  });
15
15
  export {
16
16
  metaMediaCommand
17
17
  };
18
- //# sourceMappingURL=media-NHO7QT2A.js.map
18
+ //# sourceMappingURL=media-QOGVG6CU.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-GS3SIVUK.js";
4
4
  import {
5
5
  normalizeMetaAccountId
6
- } from "./chunk-2W6ILA5Z.js";
6
+ } from "./chunk-LDL5VBBD.js";
7
7
  import "./chunk-QALAJNBG.js";
8
8
  import "./chunk-7W5KGO5H.js";
9
9
  import {
@@ -106,47 +106,47 @@ Full guide: __tooling__/docs/tools/baker/ads-meta.md`
106
106
  normalize: normalizeMetaAccountId
107
107
  }),
108
108
  subCommands: {
109
- accounts: () => import("./accounts-JILEWVP6.js").then((m) => m.accountsCommand),
110
- account: () => import("./account-6EJ22A7X.js").then((m) => m.accountCommand),
111
- businesses: () => import("./businesses-3N6CTZ2Q.js").then((m) => m.businessesCommand),
112
- pages: () => import("./pages-Q4W64A3N.js").then((m) => m.pagesCommand),
113
- "lead-forms": () => import("./leads-HU4GA6T4.js").then((m) => m.leadFormsCommand),
114
- "instant-experiences": () => import("./instant-experiences-KCAH5ONN.js").then((m) => m.instantExperiencesCommand),
115
- leads: () => import("./leads-HU4GA6T4.js").then((m) => m.leadsCommand),
116
- campaigns: () => import("./campaigns-FN56B6B7.js").then((m) => m.campaignsCommand),
117
- adsets: () => import("./adsets-JF3CBKOU.js").then((m) => m.adsetsCommand),
118
- ads: () => import("./ads-7NUK2UOG.js").then((m) => m.adsListCommand),
119
- creatives: () => import("./creatives-3AQ3EEUL.js").then((m) => m.creativesCommand),
120
- audiences: () => import("./audiences-G3PRPIY4.js").then((m) => m.audiencesCommand),
121
- "custom-conversions": () => import("./custom-conversions-XNYZOJYY.js").then((m) => m.customConversionsCommand),
122
- pixels: () => import("./pixels-HOOILVHZ.js").then((m) => m.pixelsCommand),
123
- activities: () => import("./activities-JHKNRR3M.js").then((m) => m.activitiesCommand),
124
- insights: () => import("./insights-VD4QINO7.js").then((m) => m.insightsCommand),
125
- preview: () => import("./preview-3TA3ILQ5.js").then((m) => m.previewCommand),
126
- videos: () => import("./videos-RS3G65UV.js").then((m) => m.videosCommand),
127
- targeting: () => import("./targeting-BNJVE7XS.js").then((m) => m.targetingCommand),
128
- "instagram-accounts": () => import("./account-assets-ZY4UYCHQ.js").then((m) => m.instagramAccountsCommand),
129
- apps: () => import("./account-assets-ZY4UYCHQ.js").then((m) => m.appsCommand),
130
- "dsa-recommendations": () => import("./account-assets-ZY4UYCHQ.js").then((m) => m.dsaRecommendationsCommand),
131
- images: () => import("./account-assets-ZY4UYCHQ.js").then((m) => m.imagesCommand),
132
- labels: () => import("./account-assets-ZY4UYCHQ.js").then((m) => m.labelsCommand),
133
- studies: () => import("./studies-5YCUBVK5.js").then((m) => m.studiesCommand),
134
- catalogs: () => import("./catalogs-N2I2GNHS.js").then((m) => m.catalogsCommand),
135
- "page-photos": () => import("./page-photos-6PRIPJJE.js").then((m) => m.pagePhotosCommand),
136
- "page-posts": () => import("./account-level-Z4Z5PUA6.js").then((m) => m.pagePostsCommand),
137
- "instagram-media": () => import("./account-level-Z4Z5PUA6.js").then((m) => m.instagramMediaCommand),
138
- comments: () => import("./account-level-Z4Z5PUA6.js").then((m) => m.commentsCommand),
139
- "account-settings": () => import("./account-level-Z4Z5PUA6.js").then((m) => m.accountSettingsCommand),
140
- "account-details": () => import("./account-level-Z4Z5PUA6.js").then((m) => m.accountDetailsCommand),
141
- "block-lists": () => import("./account-level-Z4Z5PUA6.js").then((m) => m.blockListsCommand),
142
- "reach-frequency": () => import("./account-level-Z4Z5PUA6.js").then((m) => m.reachFrequencyCommand),
143
- "high-demand-periods": () => import("./account-assets-ZY4UYCHQ.js").then((m) => m.highDemandPeriodsCommand),
144
- rules: () => import("./rules-BNNJXDYI.js").then((m) => m.rulesCommand),
145
- media: () => import("./media-NHO7QT2A.js").then((m) => m.metaMediaCommand),
146
- draft: () => import("./draft-3P2XHRWX.js").then((m) => m.metaDraftCommand)
109
+ accounts: () => import("./accounts-2USPMXA2.js").then((m) => m.accountsCommand),
110
+ account: () => import("./account-AIW3XGWG.js").then((m) => m.accountCommand),
111
+ businesses: () => import("./businesses-5AEHP23G.js").then((m) => m.businessesCommand),
112
+ pages: () => import("./pages-O7NXGSBG.js").then((m) => m.pagesCommand),
113
+ "lead-forms": () => import("./leads-IGOXMIEW.js").then((m) => m.leadFormsCommand),
114
+ "instant-experiences": () => import("./instant-experiences-YXH2AHFI.js").then((m) => m.instantExperiencesCommand),
115
+ leads: () => import("./leads-IGOXMIEW.js").then((m) => m.leadsCommand),
116
+ campaigns: () => import("./campaigns-PP3MFPJR.js").then((m) => m.campaignsCommand),
117
+ adsets: () => import("./adsets-2HV6TJJP.js").then((m) => m.adsetsCommand),
118
+ ads: () => import("./ads-G3N76HWA.js").then((m) => m.adsListCommand),
119
+ creatives: () => import("./creatives-ZYY5OF5U.js").then((m) => m.creativesCommand),
120
+ audiences: () => import("./audiences-65JSGH4L.js").then((m) => m.audiencesCommand),
121
+ "custom-conversions": () => import("./custom-conversions-YQPOB2IR.js").then((m) => m.customConversionsCommand),
122
+ pixels: () => import("./pixels-I7S5N76B.js").then((m) => m.pixelsCommand),
123
+ activities: () => import("./activities-DYI25TF4.js").then((m) => m.activitiesCommand),
124
+ insights: () => import("./insights-PBJODKMY.js").then((m) => m.insightsCommand),
125
+ preview: () => import("./preview-5CK5INGO.js").then((m) => m.previewCommand),
126
+ videos: () => import("./videos-OF6PAPP2.js").then((m) => m.videosCommand),
127
+ targeting: () => import("./targeting-YWOOD6YL.js").then((m) => m.targetingCommand),
128
+ "instagram-accounts": () => import("./account-assets-FJFPB7KD.js").then((m) => m.instagramAccountsCommand),
129
+ apps: () => import("./account-assets-FJFPB7KD.js").then((m) => m.appsCommand),
130
+ "dsa-recommendations": () => import("./account-assets-FJFPB7KD.js").then((m) => m.dsaRecommendationsCommand),
131
+ images: () => import("./account-assets-FJFPB7KD.js").then((m) => m.imagesCommand),
132
+ labels: () => import("./account-assets-FJFPB7KD.js").then((m) => m.labelsCommand),
133
+ studies: () => import("./studies-TIF7PYEB.js").then((m) => m.studiesCommand),
134
+ catalogs: () => import("./catalogs-UYYPZRFW.js").then((m) => m.catalogsCommand),
135
+ "page-photos": () => import("./page-photos-P2XMKTVF.js").then((m) => m.pagePhotosCommand),
136
+ "page-posts": () => import("./account-level-CB6I4X5W.js").then((m) => m.pagePostsCommand),
137
+ "instagram-media": () => import("./account-level-CB6I4X5W.js").then((m) => m.instagramMediaCommand),
138
+ comments: () => import("./account-level-CB6I4X5W.js").then((m) => m.commentsCommand),
139
+ "account-settings": () => import("./account-level-CB6I4X5W.js").then((m) => m.accountSettingsCommand),
140
+ "account-details": () => import("./account-level-CB6I4X5W.js").then((m) => m.accountDetailsCommand),
141
+ "block-lists": () => import("./account-level-CB6I4X5W.js").then((m) => m.blockListsCommand),
142
+ "reach-frequency": () => import("./account-level-CB6I4X5W.js").then((m) => m.reachFrequencyCommand),
143
+ "high-demand-periods": () => import("./account-assets-FJFPB7KD.js").then((m) => m.highDemandPeriodsCommand),
144
+ rules: () => import("./rules-UEKJOZTV.js").then((m) => m.rulesCommand),
145
+ media: () => import("./media-QOGVG6CU.js").then((m) => m.metaMediaCommand),
146
+ draft: () => import("./draft-OHAOBGVP.js").then((m) => m.metaDraftCommand)
147
147
  }
148
148
  });
149
149
  export {
150
150
  metaCommand
151
151
  };
152
- //# sourceMappingURL=meta-SOPDFYYK.js.map
152
+ //# sourceMappingURL=meta-RJH5COPE.js.map
@@ -3,10 +3,10 @@ import {
3
3
  failWriteValidation,
4
4
  requireTarget,
5
5
  stageOp
6
- } from "./chunk-6XXKYTD5.js";
6
+ } from "./chunk-BRHYK4HQ.js";
7
7
  import "./chunk-3R62EYYX.js";
8
8
  import "./chunk-GDFJOCDO.js";
9
- import "./chunk-2W6ILA5Z.js";
9
+ import "./chunk-LDL5VBBD.js";
10
10
  import "./chunk-S7J2JP3U.js";
11
11
  import "./chunk-UKENQSZ2.js";
12
12
  import "./chunk-D5FY4FAK.js";
@@ -119,4 +119,4 @@ var pagePhotosCommand = defineCommand({
119
119
  export {
120
120
  pagePhotosCommand
121
121
  };
122
- //# sourceMappingURL=page-photos-6PRIPJJE.js.map
122
+ //# sourceMappingURL=page-photos-P2XMKTVF.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  csvOrJson,
3
3
  handleMetaError
4
- } from "./chunk-2W6ILA5Z.js";
4
+ } from "./chunk-LDL5VBBD.js";
5
5
  import "./chunk-QALAJNBG.js";
6
6
  import {
7
7
  NO_CACHE_ARG
@@ -64,4 +64,4 @@ export {
64
64
  pageSelectionHints,
65
65
  pagesCommand
66
66
  };
67
- //# sourceMappingURL=pages-Q4W64A3N.js.map
67
+ //# sourceMappingURL=pages-O7NXGSBG.js.map
@@ -1,10 +1,13 @@
1
1
  import {
2
+ LISTING_ACCOUNT_ARG,
3
+ accountsInScope,
2
4
  csvOrJson,
3
5
  daysAgoIso,
4
6
  handleMetaError,
5
- resolveAccountIdArg,
6
- todayIso
7
- } from "./chunk-2W6ILA5Z.js";
7
+ readEachAccount,
8
+ todayIso,
9
+ withAccountColumn
10
+ } from "./chunk-LDL5VBBD.js";
8
11
  import "./chunk-QALAJNBG.js";
9
12
  import {
10
13
  NO_CACHE_ARG
@@ -40,7 +43,7 @@ Examples:
40
43
  baker ads meta pixels --pixel-id 9876 --stats --days 30 --by total # each event's count, first and last seen`
41
44
  },
42
45
  args: {
43
- "account-id": { type: "string", description: "Meta ad account ID" },
46
+ "account-id": LISTING_ACCOUNT_ARG,
44
47
  "pixel-id": { type: "string", description: "Pixel ID for --stats" },
45
48
  stats: { type: "boolean", description: "Fetch firing stats for the pixel" },
46
49
  aggregation: {
@@ -188,11 +191,17 @@ function instant(time) {
188
191
  return bucketTime(time).toMillis();
189
192
  }
190
193
  async function runList(args) {
191
- const accountId = await resolveAccountIdArg(args);
192
- const params = { "account-id": accountId };
194
+ const accounts = await accountsInScope(args);
195
+ const params = {};
193
196
  if (args["no-cache"]) params["skip-cache"] = "true";
194
- const { pixels, restrictedFields } = await apiGet("/api/ads/meta/pixels", params);
195
- emit(args.full ? pixels : pixels.map(compactPixel), args, pixelWarnings(restrictedFields));
197
+ const restricted = /* @__PURE__ */ new Set();
198
+ const read = await readEachAccount(accounts, async (accountId) => {
199
+ const { pixels, restrictedFields } = await apiGet("/api/ads/meta/pixels", { ...params, "account-id": accountId });
200
+ for (const field of restrictedFields) restricted.add(field);
201
+ return pixels;
202
+ });
203
+ const rows = args.full ? read.rows : read.rows.map(compactPixel);
204
+ emit(withAccountColumn(rows, read.accountOf), args, pixelWarnings([...restricted]), read.hints);
196
205
  }
197
206
  function compactPixel(pixel) {
198
207
  return {
@@ -215,16 +224,21 @@ function pixelWarnings(restrictedFields) {
215
224
  }
216
225
  ];
217
226
  }
218
- function emit(data, args, warnings = []) {
227
+ function emit(data, args, warnings = [], hints = []) {
219
228
  const fmt = csvOrJson(args);
220
229
  if (fmt !== "json") {
221
- writeAdsOutput(data, fmt);
230
+ writeAdsOutput(data, fmt, void 0, hints);
222
231
  return;
223
232
  }
224
- writeAdsJson({ ok: true, data, ...warnings.length > 0 ? { warnings } : {} });
233
+ writeAdsJson({
234
+ ok: true,
235
+ data,
236
+ ...warnings.length > 0 ? { warnings } : {},
237
+ ...hints.length > 0 ? { hints } : {}
238
+ });
225
239
  }
226
240
  export {
227
241
  pixelWarnings,
228
242
  pixelsCommand
229
243
  };
230
- //# sourceMappingURL=pixels-HOOILVHZ.js.map
244
+ //# sourceMappingURL=pixels-I7S5N76B.js.map