@koda-sl/baker-cli 0.869.0-dev.0631d8a3c → 0.869.0-dev.620009099
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -3
- package/dist/{account-LHY6YM6L.js → account-5VOZ4R2X.js} +2 -2
- package/dist/{account-assets-L6BX4YUQ.js → account-assets-DOHOKM2L.js} +54 -46
- package/dist/account-assets-DOHOKM2L.js.map +1 -0
- package/dist/{account-level-OX34JQ7C.js → account-level-HLSTNJHR.js} +4 -4
- package/dist/{accounts-LNFU27BU.js → accounts-SNH3LJ2H.js} +2 -2
- package/dist/{activities-LC64DAAK.js → activities-QHDGHXMI.js} +21 -12
- package/dist/activities-QHDGHXMI.js.map +1 -0
- package/dist/{ads-VSU53JN3.js → ads-MYACXO5A.js} +3 -3
- package/dist/{ads-ZR5D7BZT.js → ads-ZDSRE7D6.js} +27 -19
- package/dist/ads-ZDSRE7D6.js.map +1 -0
- package/dist/{adsets-3NIYL2GQ.js → adsets-CZQMTJ2T.js} +48 -30
- package/dist/adsets-CZQMTJ2T.js.map +1 -0
- package/dist/{asset-writes-5ZKZDPQ4.js → asset-writes-TXYCARXJ.js} +4 -4
- package/dist/{audience-writes-NL6NRLLY.js → audience-writes-DJG7XTFA.js} +29 -15
- package/dist/audience-writes-DJG7XTFA.js.map +1 -0
- package/dist/{audiences-DL267GNQ.js → audiences-QHM26I5Y.js} +27 -15
- package/dist/audiences-QHM26I5Y.js.map +1 -0
- package/dist/{businesses-RQ6P4DOS.js → businesses-ALNQZFB4.js} +2 -2
- package/dist/{campaigns-RXDC5FSQ.js → campaigns-55VLNVCE.js} +29 -18
- package/dist/campaigns-55VLNVCE.js.map +1 -0
- package/dist/{catalogs-QAZ7ZZ5R.js → catalogs-B24HAEXZ.js} +3 -3
- package/dist/{chunk-OMJ7DVFJ.js → chunk-2WHALQOJ.js} +2 -2
- package/dist/{chunk-XFTN3ARP.js → chunk-BPIHAIWB.js} +13 -22
- package/dist/chunk-BPIHAIWB.js.map +1 -0
- package/dist/{chunk-EGM42UKF.js → chunk-EJ6B5OS5.js} +2 -2
- package/dist/{chunk-WKRVHRWY.js → chunk-VBIKO56A.js} +14 -3
- package/dist/chunk-VBIKO56A.js.map +1 -0
- package/dist/{chunk-UE5ZFTDL.js → chunk-VUJPKIJN.js} +2 -2
- package/dist/{chunk-DP76WGDV.js → chunk-YF57BX3S.js} +87 -8
- package/dist/chunk-YF57BX3S.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{copy-writes-QYN6PBU2.js → copy-writes-S4X5XUSK.js} +4 -4
- package/dist/{creatives-CPLH3KHQ.js → creatives-BCTG6PV4.js} +32 -19
- package/dist/creatives-BCTG6PV4.js.map +1 -0
- package/dist/{custom-conversions-CTJVAZKC.js → custom-conversions-56VXFOWV.js} +27 -15
- package/dist/custom-conversions-56VXFOWV.js.map +1 -0
- package/dist/{draft-UU3F2VMJ.js → draft-OMGA2NYG.js} +2 -2
- package/dist/{insights-QU5A4XBO.js → insights-3SQWIU4E.js} +2 -2
- package/dist/{instant-experiences-EJWYFWDT.js → instant-experiences-HSRGMQ5T.js} +3 -3
- package/dist/{leads-FEEWX7OO.js → leads-LWWPMZRY.js} +3 -3
- package/dist/{linkedin-RMZMQ2ZA.js → linkedin-EBOTX37R.js} +4 -8
- package/dist/{linkedin-RMZMQ2ZA.js.map → linkedin-EBOTX37R.js.map} +1 -1
- package/dist/{media-PUOLJUN3.js → media-UODVM47L.js} +3 -3
- package/dist/{meta-HOFABFAK.js → meta-4IOVQSFF.js} +40 -40
- package/dist/{page-photos-ZBMJLL5V.js → page-photos-BCEDWPGX.js} +3 -3
- package/dist/{pages-YZC44QR2.js → pages-TZBFJXNR.js} +2 -2
- package/dist/{pixels-EX6FHVHW.js → pixels-2BG3XMZP.js} +25 -12
- package/dist/pixels-2BG3XMZP.js.map +1 -0
- package/dist/preview-HD3QAR53.js +104 -0
- package/dist/preview-HD3QAR53.js.map +1 -0
- package/dist/{preview-XXQ5AHXP.js → preview-WHUVS5JJ.js} +43 -135
- package/dist/preview-WHUVS5JJ.js.map +1 -0
- package/dist/{rule-writes-6XP7G35U.js → rule-writes-Q5NLSBF5.js} +3 -3
- package/dist/{rules-BRULCGRV.js → rules-Z7MMVOZ2.js} +41 -24
- package/dist/rules-Z7MMVOZ2.js.map +1 -0
- package/dist/{shared-64RE42DL.js → shared-AXONQS3M.js} +16 -4
- package/dist/{studies-357M2C2K.js → studies-HUINRZHD.js} +33 -16
- package/dist/studies-HUINRZHD.js.map +1 -0
- package/dist/{study-writes-HXUQRPIK.js → study-writes-SI5QXY7F.js} +3 -3
- package/dist/{targeting-7T7XHBIX.js → targeting-3XK4OLPG.js} +3 -3
- package/dist/{videos-TJG5CA7N.js → videos-C5OCSAIF.js} +2 -2
- package/dist/{write-commands-4KI6T2NF.js → write-commands-T46SVSQ7.js} +7 -7
- package/package.json +1 -1
- package/dist/account-assets-L6BX4YUQ.js.map +0 -1
- package/dist/activities-LC64DAAK.js.map +0 -1
- package/dist/ads-ZR5D7BZT.js.map +0 -1
- package/dist/adsets-3NIYL2GQ.js.map +0 -1
- package/dist/audience-writes-NL6NRLLY.js.map +0 -1
- package/dist/audiences-DL267GNQ.js.map +0 -1
- package/dist/campaigns-RXDC5FSQ.js.map +0 -1
- package/dist/chunk-DP76WGDV.js.map +0 -1
- package/dist/chunk-WKRVHRWY.js.map +0 -1
- package/dist/chunk-XFTN3ARP.js.map +0 -1
- package/dist/creatives-CPLH3KHQ.js.map +0 -1
- package/dist/custom-conversions-CTJVAZKC.js.map +0 -1
- package/dist/pixels-EX6FHVHW.js.map +0 -1
- package/dist/preview-4DDR337D.js +0 -151
- package/dist/preview-4DDR337D.js.map +0 -1
- package/dist/preview-XXQ5AHXP.js.map +0 -1
- package/dist/rules-BRULCGRV.js.map +0 -1
- package/dist/studies-357M2C2K.js.map +0 -1
- /package/dist/{account-LHY6YM6L.js.map → account-5VOZ4R2X.js.map} +0 -0
- /package/dist/{account-level-OX34JQ7C.js.map → account-level-HLSTNJHR.js.map} +0 -0
- /package/dist/{accounts-LNFU27BU.js.map → accounts-SNH3LJ2H.js.map} +0 -0
- /package/dist/{ads-VSU53JN3.js.map → ads-MYACXO5A.js.map} +0 -0
- /package/dist/{asset-writes-5ZKZDPQ4.js.map → asset-writes-TXYCARXJ.js.map} +0 -0
- /package/dist/{businesses-RQ6P4DOS.js.map → businesses-ALNQZFB4.js.map} +0 -0
- /package/dist/{catalogs-QAZ7ZZ5R.js.map → catalogs-B24HAEXZ.js.map} +0 -0
- /package/dist/{chunk-OMJ7DVFJ.js.map → chunk-2WHALQOJ.js.map} +0 -0
- /package/dist/{chunk-EGM42UKF.js.map → chunk-EJ6B5OS5.js.map} +0 -0
- /package/dist/{chunk-UE5ZFTDL.js.map → chunk-VUJPKIJN.js.map} +0 -0
- /package/dist/{copy-writes-QYN6PBU2.js.map → copy-writes-S4X5XUSK.js.map} +0 -0
- /package/dist/{draft-UU3F2VMJ.js.map → draft-OMGA2NYG.js.map} +0 -0
- /package/dist/{insights-QU5A4XBO.js.map → insights-3SQWIU4E.js.map} +0 -0
- /package/dist/{instant-experiences-EJWYFWDT.js.map → instant-experiences-HSRGMQ5T.js.map} +0 -0
- /package/dist/{leads-FEEWX7OO.js.map → leads-LWWPMZRY.js.map} +0 -0
- /package/dist/{media-PUOLJUN3.js.map → media-UODVM47L.js.map} +0 -0
- /package/dist/{meta-HOFABFAK.js.map → meta-4IOVQSFF.js.map} +0 -0
- /package/dist/{page-photos-ZBMJLL5V.js.map → page-photos-BCEDWPGX.js.map} +0 -0
- /package/dist/{pages-YZC44QR2.js.map → pages-TZBFJXNR.js.map} +0 -0
- /package/dist/{rule-writes-6XP7G35U.js.map → rule-writes-Q5NLSBF5.js.map} +0 -0
- /package/dist/{shared-64RE42DL.js.map → shared-AXONQS3M.js.map} +0 -0
- /package/dist/{study-writes-HXUQRPIK.js.map → study-writes-SI5QXY7F.js.map} +0 -0
- /package/dist/{targeting-7T7XHBIX.js.map → targeting-3XK4OLPG.js.map} +0 -0
- /package/dist/{videos-TJG5CA7N.js.map → videos-C5OCSAIF.js.map} +0 -0
- /package/dist/{write-commands-4KI6T2NF.js.map → write-commands-T46SVSQ7.js.map} +0 -0
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
requireTarget,
|
|
9
9
|
stageOp,
|
|
10
10
|
upper
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-2WHALQOJ.js";
|
|
12
12
|
import {
|
|
13
13
|
retailerIdFilter
|
|
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-
|
|
19
|
+
} from "./chunk-YF57BX3S.js";
|
|
20
20
|
import "./chunk-XD7C5OE7.js";
|
|
21
21
|
import "./chunk-UKENQSZ2.js";
|
|
22
22
|
import "./chunk-D5FY4FAK.js";
|
|
@@ -783,4 +783,4 @@ export {
|
|
|
783
783
|
productFieldsFromArgs,
|
|
784
784
|
productSetFilterFromArgs
|
|
785
785
|
};
|
|
786
|
-
//# sourceMappingURL=catalogs-
|
|
786
|
+
//# sourceMappingURL=catalogs-B24HAEXZ.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
handleMetaError,
|
|
6
6
|
resolveAccountIdArg
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-YF57BX3S.js";
|
|
8
8
|
import {
|
|
9
9
|
adCopyHints,
|
|
10
10
|
booleanWordPositionalError,
|
|
@@ -227,4 +227,4 @@ export {
|
|
|
227
227
|
stageOps,
|
|
228
228
|
stageStatusChange
|
|
229
229
|
};
|
|
230
|
-
//# sourceMappingURL=chunk-
|
|
230
|
+
//# sourceMappingURL=chunk-2WHALQOJ.js.map
|
|
@@ -8,32 +8,23 @@ import { tmpdir } from "os";
|
|
|
8
8
|
import { join } from "path";
|
|
9
9
|
var AD_PREVIEW_DIR = join(tmpdir(), "baker-ad-previews");
|
|
10
10
|
var AD_PREVIEW_DIR_LABEL = "your system temp folder, under baker-ad-previews";
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
async function renderAdPreviews(inputs, target, draw = drawPreviewInChromium) {
|
|
12
|
+
mkdirSync(target.dir, { recursive: true });
|
|
13
|
+
const previews = [];
|
|
14
14
|
const taken = /* @__PURE__ */ new Map();
|
|
15
|
-
const
|
|
15
|
+
for (const input of inputs) {
|
|
16
16
|
const where = input.surface ? { placement: input.placement, surface: input.surface } : { placement: input.placement };
|
|
17
|
-
const base = [
|
|
17
|
+
const base = [target.name, input.placement, input.surface?.toLowerCase()].filter(Boolean).join("-");
|
|
18
18
|
const seen = (taken.get(base) ?? 0) + 1;
|
|
19
19
|
taken.set(base, seen);
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const index = next++;
|
|
27
|
-
const { where, html, file } = jobs[index];
|
|
28
|
-
try {
|
|
29
|
-
const { text } = await draw(html, file);
|
|
30
|
-
previews[index] = { ...where, shownText: shownLines(text), image: file };
|
|
31
|
-
} catch (err) {
|
|
32
|
-
previews[index] = { ...where, error: err instanceof Error ? err.message : String(err) };
|
|
33
|
-
}
|
|
20
|
+
const file = join(target.dir, `${seen > 1 ? `${base}-${seen}` : base}.png`);
|
|
21
|
+
try {
|
|
22
|
+
const { text } = await draw(input.html, file);
|
|
23
|
+
previews.push({ ...where, shownText: shownLines(text), image: file });
|
|
24
|
+
} catch (err) {
|
|
25
|
+
previews.push({ ...where, error: err instanceof Error ? err.message : String(err) });
|
|
34
26
|
}
|
|
35
|
-
}
|
|
36
|
-
await Promise.all(Array.from({ length: Math.min(DRAW_CONCURRENCY, jobs.length) }, worker));
|
|
27
|
+
}
|
|
37
28
|
return { previews, hints: previewHints(previews) };
|
|
38
29
|
}
|
|
39
30
|
function shownLines(text) {
|
|
@@ -91,4 +82,4 @@ export {
|
|
|
91
82
|
AD_PREVIEW_DIR_LABEL,
|
|
92
83
|
renderAdPreviews
|
|
93
84
|
};
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
85
|
+
//# sourceMappingURL=chunk-BPIHAIWB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/ads/ad-preview-images.ts"],"sourcesContent":["import { mkdirSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { launchBrowser } from \"../../engine/landing-library/browser.ts\";\n\n/**\n * Opens a platform's preview iframe and returns what it displays: the text\n * people read (`shownText`) and a picture for questions text cannot answer.\n *\n * The API's fields say what is stored, not what shows. A Session paused seven\n * live ads because a stored headline read like an internal code, with no way to\n * check whether the feed showed it. The rendered text settles that; the picture\n * covers what is not text — words drawn into the artwork, cropping, layout.\n */\n\nexport interface AdPreviewInput {\n placement: string;\n /** Where the platform shows it (LinkedIn FEED, …) when one placement renders on several surfaces. */\n surface?: string;\n html: string;\n}\n\ntype AdPreviewWhere = { placement: string; surface?: string };\nexport type AdPreviewResult =\n | (AdPreviewWhere & { shownText: string[]; image: string })\n | (AdPreviewWhere & { error: string });\n\n/** Render `html` (a platform iframe): save a PNG at `file`, return the text it displays. */\nexport type DrawPreview = (html: string, file: string) => Promise<{ text: string }>;\n\nexport const AD_PREVIEW_DIR = join(tmpdir(), \"baker-ad-previews\");\n\n/**\n * The same folder as a sentence, for an arg description.\n *\n * `AD_PREVIEW_DIR` itself must never reach one: it is `tmpdir()` RESOLVED, which is\n * `/tmp/baker-ad-previews` on Linux and `/var/folders/<random>/T/baker-ad-previews` on a Mac — so\n * `catalog:export` wrote whichever machine ran it into `cli-catalog/families/ads-meta.json`, and\n * `catalog.test.ts` then failed for everyone else. The catalog is committed, so a description in it\n * has to be the same on every machine.\n */\nexport const AD_PREVIEW_DIR_LABEL = \"your system temp folder, under baker-ad-previews\";\n\nexport async function renderAdPreviews(\n inputs: readonly AdPreviewInput[],\n target: { dir: string; name: string },\n draw: DrawPreview = drawPreviewInChromium,\n): Promise<{ previews: AdPreviewResult[]; hints: string[] }> {\n mkdirSync(target.dir, { recursive: true });\n const previews: AdPreviewResult[] = [];\n const taken = new Map<string, number>();\n for (const input of inputs) {\n const where: AdPreviewWhere = input.surface\n ? { placement: input.placement, surface: input.surface }\n : { placement: input.placement };\n // One file per rendering: a shared name would leave two results pointing at the last picture drawn.\n const base = [target.name, input.placement, input.surface?.toLowerCase()].filter(Boolean).join(\"-\");\n const seen = (taken.get(base) ?? 0) + 1;\n taken.set(base, seen);\n const file = join(target.dir, `${seen > 1 ? `${base}-${seen}` : base}.png`);\n try {\n const { text } = await draw(input.html, file);\n previews.push({ ...where, shownText: shownLines(text), image: file });\n } catch (err) {\n previews.push({ ...where, error: err instanceof Error ? err.message : String(err) });\n }\n }\n return { previews, hints: previewHints(previews) };\n}\n\nfunction shownLines(text: string): string[] {\n return text\n .split(\"\\n\")\n .map((line) => line.replace(/\\s+/g, \" \").trim())\n .filter(Boolean);\n}\n\nfunction previewHints(previews: readonly AdPreviewResult[]): string[] {\n const hints: string[] = [];\n if (previews.some((p) => \"image\" in p)) {\n hints.push(\n \"shownText is what people see on the ad, in order — rendered by the platform itself, so it settles which text is displayed (headline under the image, button, cut-off intro). The API fields only say what is stored. Words drawn into the artwork are not in shownText: Read the image for those, and for cropping or how the ad looks.\",\n );\n }\n if (previews.some((p) => \"error\" in p)) {\n hints.push(\n \"Some previews could not be drawn. Do not describe how those look — say they could not be checked, and carry on with the rest.\",\n );\n }\n return hints;\n}\n\n/**\n * The platforms' iframes have a fixed window (Meta's 335×450) and scroll the rest,\n * which cuts the headline and button off a picture. The frame is grown to its\n * content's height first, so the picture holds the whole ad.\n */\nexport async function drawPreviewInChromium(html: string, file: string): Promise<{ text: string }> {\n const browser = await launchBrowser();\n try {\n const context = await browser.newContext({ viewport: { width: 900, height: 1200 }, deviceScaleFactor: 2 });\n const page = await context.newPage();\n await page.setContent(`<!doctype html><body style=\"margin:0;background:#fff\">${html}</body>`, {\n waitUntil: \"load\",\n timeout: 30_000,\n });\n await page.waitForLoadState(\"networkidle\", { timeout: 15_000 }).catch(() => undefined);\n const iframe = await page.$(\"iframe\");\n if (!iframe) throw new Error(\"the platform returned no preview frame\");\n const frame = await iframe.contentFrame();\n if (frame) {\n const height = await frame.evaluate(() =>\n Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0),\n );\n if (height > 0) {\n await iframe.evaluate((node, h) => {\n node.removeAttribute(\"height\");\n (node as HTMLElement).style.height = `${h}px`;\n }, height);\n await frame.waitForLoadState(\"networkidle\", { timeout: 10_000 }).catch(() => undefined);\n }\n }\n await iframe.screenshot({ path: file });\n // innerText follows the layout: hidden elements drop out, line breaks stay.\n const text = frame ? await frame.evaluate(() => document.body?.innerText ?? \"\") : \"\";\n return { text };\n } finally {\n await browser.close();\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,cAAc;AACvB,SAAS,YAAY;AA4Bd,IAAM,iBAAiB,KAAK,OAAO,GAAG,mBAAmB;AAWzD,IAAM,uBAAuB;AAEpC,eAAsB,iBACpB,QACA,QACA,OAAoB,uBACuC;AAC3D,YAAU,OAAO,KAAK,EAAE,WAAW,KAAK,CAAC;AACzC,QAAM,WAA8B,CAAC;AACrC,QAAM,QAAQ,oBAAI,IAAoB;AACtC,aAAW,SAAS,QAAQ;AAC1B,UAAM,QAAwB,MAAM,UAChC,EAAE,WAAW,MAAM,WAAW,SAAS,MAAM,QAAQ,IACrD,EAAE,WAAW,MAAM,UAAU;AAEjC,UAAM,OAAO,CAAC,OAAO,MAAM,MAAM,WAAW,MAAM,SAAS,YAAY,CAAC,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG;AAClG,UAAM,QAAQ,MAAM,IAAI,IAAI,KAAK,KAAK;AACtC,UAAM,IAAI,MAAM,IAAI;A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,MAAM,MAAM,MAAS;AACrF,UAAM,SAAS,MAAM,KAAK,EAAE,QAAQ;AACpC,QAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,wCAAwC;AACrE,UAAM,QAAQ,MAAM,OAAO,aAAa;AACxC,QAAI,OAAO;AACT,YAAM,SAAS,MAAM,MAAM;AAAA,QAAS,MAClC,KAAK,IAAI,SAAS,gBAAgB,cAAc,SAAS,MAAM,gBAAgB,CAAC;AAAA,MAClF;AACA,UAAI,SAAS,GAAG;AACd,cAAM,OAAO,SAAS,CAAC,MAAM,MAAM;AACjC,eAAK,gBAAgB,QAAQ;AAC7B,UAAC,KAAqB,MAAM,SAAS,GAAG,CAAC;AAAA,QAC3C,GAAG,MAAM;AACT,cAAM,MAAM,iBAAiB,eAAe,EAAE,SAAS,IAAO,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MACxF;AAAA,IACF;AACA,UAAM,OAAO,WAAW,EAAE,MAAM,KAAK,CAAC;AAEtC,UAAM,OAAO,QAAQ,MAAM,MAAM,SAAS,MAAM,SAAS,MAAM,aAAa,EAAE,IAAI;AAClF,WAAO,EAAE,KAAK;AAAA,EAChB,UAAE;AACA,UAAM,QAAQ,MAAM;AAAA,EACtB;AACF;","names":[]}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
failWriteValidation,
|
|
3
3
|
parseDateFlag,
|
|
4
4
|
parseMoneyFlag
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-2WHALQOJ.js";
|
|
6
6
|
import {
|
|
7
7
|
repeatedValues
|
|
8
8
|
} from "./chunk-ERSX3MKH.js";
|
|
@@ -284,4 +284,4 @@ export {
|
|
|
284
284
|
clearFromFlags,
|
|
285
285
|
clearArg
|
|
286
286
|
};
|
|
287
|
-
//# sourceMappingURL=chunk-
|
|
287
|
+
//# sourceMappingURL=chunk-EJ6B5OS5.js.map
|
|
@@ -9,6 +9,9 @@ import {
|
|
|
9
9
|
optimizesTo,
|
|
10
10
|
texts
|
|
11
11
|
} from "./chunk-PRPSV4VB.js";
|
|
12
|
+
import {
|
|
13
|
+
withAccountColumn
|
|
14
|
+
} from "./chunk-YF57BX3S.js";
|
|
12
15
|
import {
|
|
13
16
|
asRecord,
|
|
14
17
|
shapeListRows
|
|
@@ -241,8 +244,8 @@ var PROJECTIONS = {
|
|
|
241
244
|
audiences: { row: compactAudience, columns: AUDIENCE_COLUMNS, whenPresent: AUDIENCE_WHEN_PRESENT },
|
|
242
245
|
creatives: { row: compactCreative, columns: CREATIVE_COLUMNS }
|
|
243
246
|
};
|
|
244
|
-
function shapeMetaListRows(kind, rows, args) {
|
|
245
|
-
const shaped = withheldSizeHint(kind, shapeListRows(rows, args, PROJECTIONS[kind]));
|
|
247
|
+
function shapeMetaListRows(kind, rows, args, accountOf) {
|
|
248
|
+
const shaped = withAccounts(withheldSizeHint(kind, shapeListRows(rows, args, PROJECTIONS[kind])), accountOf);
|
|
246
249
|
if (!(kind in COMPACT_SOURCES) || !shaped.hints?.some((hint) => hint.startsWith("--fields matched nothing"))) {
|
|
247
250
|
return shaped;
|
|
248
251
|
}
|
|
@@ -254,6 +257,14 @@ function shapeMetaListRows(kind, rows, args) {
|
|
|
254
257
|
]
|
|
255
258
|
};
|
|
256
259
|
}
|
|
260
|
+
function withAccounts(shaped, accountOf) {
|
|
261
|
+
if (!accountOf) return shaped;
|
|
262
|
+
return {
|
|
263
|
+
...shaped,
|
|
264
|
+
rows: withAccountColumn(shaped.rows, accountOf),
|
|
265
|
+
...shaped.fields ? { fields: ["account_id", ...shaped.fields.filter((field) => field !== "account_id")] } : {}
|
|
266
|
+
};
|
|
267
|
+
}
|
|
257
268
|
function withheldSizeHint(kind, shaped) {
|
|
258
269
|
if (kind !== "audiences" || !shaped.rows.some((row) => row.size === AUDIENCE_SIZE_NOT_REPORTED)) return shaped;
|
|
259
270
|
return { ...shaped, hints: [...shaped.hints ?? [], AUDIENCE_SIZE_NOTE] };
|
|
@@ -397,4 +408,4 @@ export {
|
|
|
397
408
|
META_LIST_SHAPE_ARGS,
|
|
398
409
|
registerMetaListSchema
|
|
399
410
|
};
|
|
400
|
-
//# sourceMappingURL=chunk-
|
|
411
|
+
//# sourceMappingURL=chunk-VBIKO56A.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/ads/meta/list-rows.ts"],"sourcesContent":["import {\n AUDIENCE_SIZE_NOT_REPORTED,\n AUDIENCE_SIZE_NOTE,\n adCreativeColumns,\n adSetBudgetColumns,\n audienceColumns,\n creativeLink,\n oneOrMany,\n optimizesTo,\n texts,\n} from \"@baker/api/ads-meta/listColumns\";\nimport type { CommandRoute } from \"@baker/api/cli-catalog/entry\";\nimport { registerSchema } from \"../../../schemas.ts\";\nimport { asRecord, type CompactProjection, type ShapedRows, shapeListRows } from \"../list-rows.ts\";\nimport { writeAdsOutput } from \"../output.ts\";\nimport { withAccountColumn } from \"./shared.ts\";\n\n/**\n * The compact row of each Meta listing. The backend asks Graph for every field a\n * write or an audit might need (targeting, tracking specs, three status fields),\n * and 100 campaigns or two days of activity passed through whole ran to 55–78 KB.\n * A compact row carries what an agent decides with; `--fields` reaches any other\n * path and `--full` returns the record Graph sent.\n *\n * `effective_status` is the one status kept: it is what Ads Manager shows, and\n * `status`/`configured_status` only restate the toggle it already folds in.\n *\n * Listings print a table by default: keyed JSON repeats every column name on\n * every row, and 100 campaigns stayed near 30 KB even compact. `--output json`\n * returns the same rows in the envelope.\n */\n\ntype MetaRow = Record<string, unknown>;\n\nexport type MetaListKind = \"campaigns\" | \"adsets\" | \"ads\" | \"activities\" | \"audiences\" | \"creatives\";\n\nfunction pick(row: MetaRow, keys: readonly string[]): MetaRow {\n const picked: MetaRow = {};\n for (const key of keys) {\n if (row[key] !== undefined) picked[key] = row[key];\n }\n return picked;\n}\n\n/**\n * An account's campaign list is the widest listing an agent reads (100+ rows), so\n * its row is the narrowest: what a campaign is called, whether it runs and what\n * it spends. Objective, bid strategy and Special Ad Category are one `--fields`\n * away; the creation day is enough to order by, and `--fields created_time` has\n * the timestamp.\n */\nconst CAMPAIGN_COLUMNS = [\"id\", \"name\", \"effective_status\", \"daily_budget\", \"lifetime_budget\", \"created_date\"] as const;\n\n/** Why delivery stops and what Meta suggests: columns only when a row has one. */\nconst DIAGNOSTIC_COLUMNS = [\"issues\", \"suggestions\"] as const;\n\n/**\n * A campaign budgeted on its ad sets has no budget of its own, so its row marks\n * `budget_level: adset` and carries the sum of its active ad sets' budgets\n * (`adSetBudgetColumns`).\n */\nconst ADSET_BUDGET_COLUMNS = [\"budget_level\", \"adset_daily_budget\", \"adset_lifetime_budget\"] as const;\nconst CAMPAIGN_WHEN_PRESENT = [...ADSET_BUDGET_COLUMNS, ...DIAGNOSTIC_COLUMNS] as const;\n\nfunction compactCampaign(row: MetaRow): MetaRow {\n const created = row.created_time;\n return {\n ...pick(row, [\"id\", \"name\", \"effective_status\", \"daily_budget\", \"lifetime_budget\"]),\n ...(typeof created === \"string\" ? { created_date: created.slice(0, 10) } : {}),\n ...adSetBudgetColumns(row),\n ...diagnostics(row),\n };\n}\n\nconst ADSET_KEYS = [\n \"id\",\n \"name\",\n \"campaign_id\",\n \"effective_status\",\n \"optimization_goal\",\n \"billing_event\",\n \"bid_strategy\",\n \"daily_budget\",\n \"lifetime_budget\",\n \"destination_type\",\n // A Dynamic Creative ad set refuses every new ad, which changes the plan before anything is staged.\n \"is_dynamic_creative\",\n] as const;\n\nconst ADSET_COLUMNS = [...ADSET_KEYS, \"learning_stage\", \"end_time\", \"created_time\"] as const;\nconst ADSET_WHEN_PRESENT = [\"optimizes_to\", ...DIAGNOSTIC_COLUMNS] as const;\n\nfunction compactAdSet(row: MetaRow): MetaRow {\n const learning = asRecord(row.learning_stage_info)?.status;\n const optimizes = optimizesTo(row.promoted_object);\n return {\n ...pick(row, ADSET_KEYS),\n ...(typeof learning === \"string\" ? { learning_stage: learning } : {}),\n ...pick(row, [\"end_time\", \"created_time\"]),\n ...(optimizes !== undefined ? { optimizes_to: optimizes } : {}),\n ...diagnostics(row),\n };\n}\n\nconst AD_COLUMNS = [\n \"id\",\n \"name\",\n \"adset_id\",\n \"campaign_id\",\n \"effective_status\",\n \"creative_id\",\n \"issues\",\n \"created_time\",\n] as const;\n\n/** Why an ad is WITH_ISSUES — the one reason to open `issues_info`, in its own words. */\nfunction adIssues(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((entry) => {\n const issue = asRecord(entry);\n const text = issue?.error_summary ?? issue?.error_message;\n return typeof text === \"string\" && text ? [text] : [];\n });\n}\n\n/** Meta's suggestions for a campaign or ad set (`recommendations`), by their titles. */\nfunction suggestions(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((entry) => {\n const recommendation = asRecord(entry);\n const text = recommendation?.title ?? recommendation?.message;\n return typeof text === \"string\" && text ? [text] : [];\n });\n}\n\n/** Why a campaign or ad set cannot deliver, and what Meta suggests — only when Meta says something. */\nfunction diagnostics(row: MetaRow): MetaRow {\n const issues = adIssues(row.issues_info);\n const suggested = suggestions(row.recommendations);\n return {\n ...(issues.length > 0 ? { issues } : {}),\n ...(suggested.length > 0 ? { suggestions: suggested } : {}),\n };\n}\n\n/** Where an ad sends people, the URL parameters it adds and the instant form it opens — read off its creative, which the listing expands. */\nconst AD_WHEN_PRESENT = [\"link\", \"lead_form_id\", \"url_tags\"] as const;\n\nfunction compactAd(row: MetaRow): MetaRow {\n const creative = asRecord(row.creative);\n const issues = adIssues(row.issues_info);\n return {\n ...pick(row, [\"id\", \"name\", \"adset_id\", \"campaign_id\", \"effective_status\"]),\n ...(creative?.id !== undefined ? { creative_id: creative.id } : {}),\n ...(issues.length > 0 ? { issues } : {}),\n ...pick(row, [\"created_time\"]),\n ...adCreativeColumns(creative),\n };\n}\n\nconst ACTIVITY_COLUMNS = [\n \"event_time\",\n \"event_type\",\n \"actor_name\",\n \"object_type\",\n \"object_name\",\n \"object_id\",\n \"change\",\n] as const;\n\nfunction isScalar(value: unknown): value is string | number | null {\n return value === null || typeof value === \"string\" || typeof value === \"number\";\n}\n\n/**\n * `extra_data` is a JSON string whose shape varies by event type and carries most\n * of an activity's bytes (image URLs, whole targeting specs). A status, name,\n * budget or goal change stores its before and after as two plain values — those\n * read as one line; any richer change stays behind `--fields extra_data`.\n */\nexport function activityChange(extraData: unknown): string | undefined {\n if (typeof extraData !== \"string\") return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(extraData);\n } catch {\n return undefined;\n }\n const data = asRecord(parsed);\n // An absent old_value is one this read did not observe, not an unset one — only `null` means \"none\".\n if (!data || !(\"new_value\" in data) || !(\"old_value\" in data)) return undefined;\n const { old_value: before, new_value: after } = data;\n if (!isScalar(before) || !isScalar(after)) return undefined;\n const show = (value: string | number | null) => (value === null ? \"(none)\" : String(value));\n return `${show(before)} → ${show(after)}`;\n}\n\nfunction compactActivity(row: MetaRow): MetaRow {\n const change = activityChange(row.extra_data);\n return {\n ...pick(row, [\"event_time\", \"event_type\", \"actor_name\", \"object_type\", \"object_name\", \"object_id\"]),\n ...(change !== undefined ? { change } : {}),\n };\n}\n\n/**\n * An account can hold hundreds of audiences (one held 414, ~424 KB printed), and a\n * lookup is usually for one of them and its lookalikes. The row says what the audience\n * is, how big (or that Meta did not say), and — only when it is so — that it is still\n * processing, why it cannot be used and which audience a lookalike was built from. Its\n * rule and data source are one `--fields` away.\n */\nconst AUDIENCE_COLUMNS = [\"id\", \"name\", \"subtype\", \"size_min\", \"size_max\", \"retention_days\", \"updated_date\"] as const;\nconst AUDIENCE_WHEN_PRESENT = [\"size\", \"status\", \"delivery\", \"seed_id\"] as const;\n\nfunction compactAudience(row: MetaRow): MetaRow {\n const updated = row.time_updated;\n const delivery = asRecord(row.delivery_status);\n const origin = asRecord(row.lookalike_spec)?.origin;\n const seed = Array.isArray(origin) ? asRecord(origin[0])?.id : undefined;\n return {\n ...pick(row, [\"id\", \"name\", \"subtype\"]),\n ...audienceColumns(row),\n ...pick(row, [\"retention_days\"]),\n ...(typeof updated === \"number\" ? { updated_date: new Date(updated * 1000).toISOString().slice(0, 10) } : {}),\n ...(delivery && delivery.code !== 200 && typeof delivery.description === \"string\"\n ? { delivery: delivery.description }\n : {}),\n ...(seed !== undefined ? { seed_id: seed } : {}),\n };\n}\n\n/**\n * A creative's copy, destination and assets live in one of three places — the\n * top-level fields Meta derives, `object_story_spec`, or a dynamic creative's\n * `asset_feed_spec`, a carousel's cards in `link_data.child_attachments` — next to specs that carry most of its bytes and none of its\n * meaning (`degrees_of_freedom_spec`, per-placement rules, signed image URLs). The\n * row reads each value from wherever the creative keeps it: one value as itself,\n * several (a dynamic creative's variants) as a list.\n */\nconst CREATIVE_COLUMNS = [\n \"id\",\n \"name\",\n \"status\",\n \"object_type\",\n \"dynamic\",\n \"body\",\n \"title\",\n \"description\",\n \"link\",\n \"cta\",\n \"url_tags\",\n \"image_hash\",\n \"video_id\",\n \"page_id\",\n \"instagram_user_id\",\n \"effective_object_story_id\",\n] as const;\n\nfunction compactCreative(row: MetaRow): MetaRow {\n const story = asRecord(row.object_story_spec);\n const link = asRecord(story?.link_data);\n const video = asRecord(story?.video_data);\n const feed = asRecord(row.asset_feed_spec);\n // A carousel's cards: each one's headline, description, destination and media.\n const cards = link?.child_attachments;\n const derived: MetaRow = {\n dynamic: feed ? (typeof feed.optimization_type === \"string\" ? feed.optimization_type : \"ASSET_FEED\") : undefined,\n body: oneOrMany(row.body, link?.message, video?.message, texts(feed?.bodies, \"text\")),\n title: oneOrMany(row.title, link?.name, video?.title, texts(feed?.titles, \"text\"), texts(cards, \"name\")),\n description: oneOrMany(\n link?.description,\n video?.link_description,\n texts(feed?.descriptions, \"text\"),\n texts(cards, \"description\"),\n ),\n link: creativeLink(row),\n cta: oneOrMany(row.call_to_action_type, feed?.call_to_action_types),\n url_tags: row.url_tags,\n image_hash: oneOrMany(\n row.image_hash,\n link?.image_hash,\n video?.image_hash,\n texts(feed?.images, \"hash\"),\n texts(cards, \"image_hash\"),\n ),\n video_id: oneOrMany(row.video_id, video?.video_id, texts(feed?.videos, \"video_id\"), texts(cards, \"video_id\")),\n page_id: story?.page_id,\n instagram_user_id: row.instagram_user_id ?? story?.instagram_user_id,\n effective_object_story_id: row.effective_object_story_id,\n };\n const compact: MetaRow = pick(row, [\"id\", \"name\", \"status\", \"object_type\"]);\n for (const [key, value] of Object.entries(derived)) if (value !== undefined) compact[key] = value;\n return compact;\n}\n\n/**\n * The unit a listing's budgets are in, said once rather than as a column (a\n * 100-campaign table stays small). Meta lists money in the account currency's\n * smallest unit and Baker passes it through unchanged (published reports read\n * it that way), while every money flag takes whole currency. An agent that once\n * took a listed \"8000\" for the flag's unit staged 10,000 EUR a day instead of 100.\n */\nexport function budgetUnitHints(rows: ReadonlyArray<Record<string, unknown>>): string[] {\n const listed = rows\n .flatMap((row) => [row.daily_budget, row.lifetime_budget, row.adset_daily_budget, row.adset_lifetime_budget])\n .map(Number)\n .find((amount) => Number.isFinite(amount) && amount > 0);\n if (listed === undefined) return [];\n const whole = listed / 100;\n return [\n `Budgets here are in the account currency's smallest unit, as Meta sends them: daily_budget ${listed} is ${whole} in EUR or USD (currencies without cents, such as JPY, are not divided). Money flags take whole currency: --daily-budget ${whole}, never ${listed}.`,\n ];\n}\n\n/** Past this many rows a listing is an account read whole, not an answer to a question. */\nconst LARGE_LISTING_ROWS = 100;\n\n/**\n * A large account lists ad sets and ads by the thousand — one listed 1,000 ad\n * sets, 1.4 MB as Meta sent them. Even compact, that table is more than an agent\n * reads to decide, so a long listing says how to ask for the part it needs.\n */\nexport function largeListingHints(kind: \"adsets\" | \"ads\", rowCount: number): string[] {\n if (rowCount < LARGE_LISTING_ROWS) return [];\n const parent = kind === \"ads\" ? \"--campaign-id <id> or --adset-id <id>\" : \"--campaign-id <id>\";\n return [\n `${rowCount} ${NOUNS[kind]} listed. On a large account, ask for the part you need: ${parent} (from baker ads meta campaigns), --effective-status ACTIVE or PAUSED, --name-contains <text>, or --ids <id>,<id>.`,\n ];\n}\n\nconst PROJECTIONS: Record<MetaListKind, CompactProjection<MetaRow>> = {\n campaigns: { row: compactCampaign, columns: CAMPAIGN_COLUMNS, whenPresent: CAMPAIGN_WHEN_PRESENT },\n adsets: { row: compactAdSet, columns: ADSET_COLUMNS, whenPresent: ADSET_WHEN_PRESENT },\n ads: { row: compactAd, columns: AD_COLUMNS, whenPresent: AD_WHEN_PRESENT },\n activities: { row: compactActivity, columns: ACTIVITY_COLUMNS },\n audiences: { row: compactAudience, columns: AUDIENCE_COLUMNS, whenPresent: AUDIENCE_WHEN_PRESENT },\n creatives: { row: compactCreative, columns: CREATIVE_COLUMNS },\n};\n\nexport function shapeMetaListRows(\n kind: MetaListKind,\n rows: MetaRow[],\n args: Record<string, unknown>,\n accountOf?: readonly string[],\n): ShapedRows {\n const shaped = withAccounts(withheldSizeHint(kind, shapeListRows(rows, args, PROJECTIONS[kind])), accountOf);\n if (!(kind in COMPACT_SOURCES) || !shaped.hints?.some((hint) => hint.startsWith(\"--fields matched nothing\"))) {\n return shaped;\n }\n // Meta was asked for the named fields only, so the rows cannot show the ones a typo missed.\n return {\n ...shaped,\n hints: [\n ...shaped.hints,\n `Only the fields --fields names are read from Meta, so these rows list no others: --full --limit 1 shows every field ${NOUNS[kind]} carry.`,\n ],\n };\n}\n\n/** Rows read from several accounts lead with the account each one is in. */\nfunction withAccounts(shaped: ShapedRows, accountOf: readonly string[] | undefined): ShapedRows {\n if (!accountOf) return shaped;\n return {\n ...shaped,\n rows: withAccountColumn(shaped.rows, accountOf),\n ...(shaped.fields ? { fields: [\"account_id\", ...shaped.fields.filter((field) => field !== \"account_id\")] } : {}),\n };\n}\n\n/** A withheld size reads as Meta's placeholder once, not as a number on every row. */\nfunction withheldSizeHint(kind: MetaListKind, shaped: ShapedRows): ShapedRows {\n if (kind !== \"audiences\" || !shaped.rows.some((row) => row.size === AUDIENCE_SIZE_NOT_REPORTED)) return shaped;\n return { ...shaped, hints: [...(shaped.hints ?? []), AUDIENCE_SIZE_NOTE] };\n}\n\ntype ListedKind = \"campaigns\" | \"adsets\" | \"ads\" | \"audiences\";\n\n/** The fields Meta is asked for to build each compact row (and the hints read beside it). */\nconst COMPACT_SOURCES: Record<ListedKind, readonly string[]> = {\n campaigns: [\n \"id\",\n \"name\",\n \"effective_status\",\n \"daily_budget\",\n \"lifetime_budget\",\n \"created_time\",\n \"issues_info\",\n \"recommendations\",\n \"advantage_state_info\",\n \"adsets\",\n ],\n adsets: [\n ...ADSET_KEYS,\n \"learning_stage_info\",\n \"end_time\",\n \"created_time\",\n \"promoted_object\",\n \"issues_info\",\n \"recommendations\",\n ],\n ads: [\"id\", \"name\", \"adset_id\", \"campaign_id\", \"effective_status\", \"creative\", \"issues_info\", \"created_time\"],\n audiences: [\n \"id\",\n \"name\",\n \"subtype\",\n \"approximate_count_lower_bound\",\n \"approximate_count_upper_bound\",\n \"retention_days\",\n \"time_updated\",\n \"delivery_status\",\n \"operation_status\",\n \"lookalike_spec\",\n ],\n};\n\n/** The fields a listing's own hints read, asked for beside any `--fields`. */\nconst HINT_SOURCES: Partial<Record<ListedKind, readonly string[]>> = {\n campaigns: [\"advantage_state_info\"],\n};\n\n/** A compact column `--fields` may name, and the field Meta keeps it in. */\nconst DERIVED_FROM: Record<string, string> = {\n created_date: \"created_time\",\n updated_date: \"time_updated\",\n learning_stage: \"learning_stage_info\",\n issues: \"issues_info\",\n suggestions: \"recommendations\",\n creative_id: \"creative\",\n link: \"creative\",\n lead_form_id: \"creative\",\n url_tags: \"creative\",\n optimizes_to: \"promoted_object\",\n adset_daily_budget: \"adsets\",\n adset_lifetime_budget: \"adsets\",\n budget_level: \"adsets\",\n size_min: \"approximate_count_lower_bound\",\n size_max: \"approximate_count_upper_bound\",\n delivery: \"delivery_status\",\n seed_id: \"lookalike_spec\",\n};\n\n/** Columns only an audience row derives: campaigns, ad sets and ads keep their own `status`. */\nconst DERIVED_FROM_KIND: Partial<Record<ListedKind, Record<string, string>>> = {\n audiences: {\n size: \"approximate_count_lower_bound,approximate_count_upper_bound\",\n status: \"operation_status\",\n },\n};\n\n/**\n * What a listing asks the server to read from Meta: the source of the compact row,\n * or of each `--fields` path (its top-level key), and everything under `--full`.\n * The server read every field it knows of — an account's ads with their creatives\n * and specs ran to 1 MB and past 60 s — for a table that prints a handful.\n */\nexport function metaListFields(kind: ListedKind, args: Record<string, unknown>): string | undefined {\n const paths =\n typeof args.fields === \"string\"\n ? args.fields\n .split(\",\")\n .map((path) => path.trim())\n .filter(Boolean)\n : [];\n if (paths.length > 0) {\n const tops = paths.map((path) => {\n const top = path.split(\".\")[0] ?? path;\n return DERIVED_FROM_KIND[kind]?.[top] ?? DERIVED_FROM[top] ?? top;\n });\n return [...new Set([\"id\", ...tops, ...(HINT_SOURCES[kind] ?? [])])].join(\",\");\n }\n if (args.full) return undefined;\n return COMPACT_SOURCES[kind].join(\",\");\n}\n\n/** Read the named rows by id, matched by Meta — whatever their status, unless one is named. */\nexport const IDS_ARG = {\n type: \"string\",\n description:\n \"Comma-separated ids: only these rows, whatever their status (unless --effective-status names one). Start here when you have the ids: --ids 120250141735400031,120250141735400032\",\n} as const;\n\nconst NOUNS: Record<MetaListKind, string> = {\n campaigns: \"campaigns\",\n adsets: \"ad sets\",\n ads: \"ads\",\n activities: \"activities\",\n audiences: \"audiences\",\n creatives: \"creatives\",\n};\n\n/**\n * A table of no rows prints nothing at all, which reads as a failed call — so an empty\n * listing says so, and says why when a status filter may be hiding rows.\n */\nexport function writeMetaListRows(kind: MetaListKind, shaped: ShapedRows, format: string, hints: string[] = []): void {\n if (format === \"md\" && shaped.rows.length === 0) {\n process.stdout.write(`${hints.length > 0 ? hints.join(\"\\n\") : `No ${NOUNS[kind]} matched.`}\\n`);\n return;\n }\n writeAdsOutput(shaped.rows, format, shaped.fields, [...hints, ...(shaped.hints ?? [])]);\n}\n\n/** The projection flags every Meta listing shares, worded once for help and `baker schema`. */\nexport const META_LIST_SHAPE_ARGS = {\n fields: {\n type: \"string\",\n description: \"CSV of dotted paths to return instead of the compact row, e.g. id,name,targeting.geo_locations\",\n },\n full: { type: \"boolean\", description: \"Return every field Meta sent (targeting, tracking specs, raw extra_data)\" },\n output: {\n type: \"string\",\n description: \"md|json|csv|jsonl — md (default) prints a table; json returns the rows in the { ok, data } envelope\",\n default: \"md\",\n },\n} as const;\n\ninterface ListArgDef {\n type: string;\n description?: string;\n default?: unknown;\n}\n\n/**\n * `baker schema ads.meta.<list>`, read off the same arg defs the command parses,\n * so the introspection an agent checks before a call cannot promise a flag the\n * command refuses — `--full` on `adsets` was guessed three times in one Session.\n */\nexport function registerMetaListSchema(\n kind: MetaListKind,\n description: string,\n args: Record<string, ListArgDef>,\n alsoReads: readonly CommandRoute[] = [],\n): void {\n registerSchema({\n command: `ads.meta.${kind}`,\n // Read live from Meta, for the account named or the only one.\n routes: [`GET /api/ads/meta/${kind}`, \"GET /api/ads/meta/accounts\", ...alsoReads],\n effect: \"read_live\",\n description,\n args: Object.fromEntries(\n Object.entries(args).map(([name, def]) => [\n name,\n {\n type: def.type,\n description: def.description ?? \"\",\n required: false,\n ...(def.default !== undefined ? { default: def.default } : {}),\n },\n ]),\n ),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAS,KAAK,KAAc,MAAkC;AAC5D,QAAM,SAAkB,CAAC;AACzB,aAAW,OAAO,MAAM;AACtB,QAAI,IAAI,GAAG,MAAM,OAAW,QAAO,GAAG,IAAI,IAAI,GAAG;AAAA,EACnD;AACA,SAAO;AACT;AASA,IAAM,mBAAmB,CAAC,MAAM,QAAQ,oBAAoB,gBAAgB,mBAAmB,cAAc;AAG7G,IAAM,qBAAqB,CAAC,UAAU,aAAa;AAOnD,IAAM,uBAAuB,CAAC,gBAAgB,sBAAsB,uBAAuB;AAC3F,IAAM,wBAAwB,CAAC,GAAG,sBAAsB,GAAG,kBAAkB;AAE7E,SAAS,gBAAgB,KAAuB;AAC9C,QAAM,UAAU,IAAI;AACpB,SAAO;AAAA,IACL,GAAG,KAAK,KAAK,CAAC,MAA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MAAM,OAAO;AAAA,MACX,OAAO,QAAQ,IAAI,EAAE,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM;AAAA,QACxC;AAAA,QACA;AAAA,UACE,MAAM,IAAI;AAAA,UACV,aAAa,IAAI,eAAe;AAAA,UAChC,UAAU;AAAA,UACV,GAAI,IAAI,YAAY,SAAY,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;AAAA,QAC9D;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
requireTarget,
|
|
6
6
|
stageOp,
|
|
7
7
|
stageOps
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-2WHALQOJ.js";
|
|
9
9
|
import {
|
|
10
10
|
repeatedValues
|
|
11
11
|
} from "./chunk-ERSX3MKH.js";
|
|
@@ -216,4 +216,4 @@ export {
|
|
|
216
216
|
labelsAttachCommand,
|
|
217
217
|
labelsDetachCommand
|
|
218
218
|
};
|
|
219
|
-
//# sourceMappingURL=chunk-
|
|
219
|
+
//# sourceMappingURL=chunk-VUJPKIJN.js.map
|
|
@@ -126,12 +126,16 @@ async function connectedMetaAccounts(useCache) {
|
|
|
126
126
|
if (useCache && accounts.length > 0) cacheSet("meta-accounts", "list", accounts, CONNECTED_ACCOUNTS_TTL_MS);
|
|
127
127
|
return accounts;
|
|
128
128
|
}
|
|
129
|
-
|
|
129
|
+
var LISTING_ACCOUNT_ARG = {
|
|
130
|
+
type: "string",
|
|
131
|
+
description: "Meta ad account ID (act_123). Without it the listing reads every connected account, each row tagged with its account_id."
|
|
132
|
+
};
|
|
133
|
+
async function accountsInScope(args) {
|
|
130
134
|
const fromArgs = args["account-id"];
|
|
131
135
|
const explicit = fromArgs || getEnv().BAKER_META_AD_ACCOUNT_ID;
|
|
132
136
|
if (explicit) {
|
|
133
137
|
if (!ACCOUNT_ID_RE.test(explicit)) invalidAccountId(explicit);
|
|
134
|
-
return actId(explicit);
|
|
138
|
+
return [{ id: actId(explicit) }];
|
|
135
139
|
}
|
|
136
140
|
let accounts;
|
|
137
141
|
try {
|
|
@@ -143,13 +147,18 @@ async function resolveAccountIdArg(args) {
|
|
|
143
147
|
const id = account.externalId ?? account.id;
|
|
144
148
|
return id && ACCOUNT_ID_RE.test(id) ? [{ id: actId(id), name: account.name }] : [];
|
|
145
149
|
});
|
|
146
|
-
|
|
147
|
-
if (ids.length === 1 &&
|
|
148
|
-
process.stderr.write(`Using account "${
|
|
150
|
+
if (ids.length === 0) refuseMissingAccount(ids);
|
|
151
|
+
if (ids.length === 1 && ids[0]) {
|
|
152
|
+
process.stderr.write(`Using account "${ids[0].name ?? ids[0].id}" (${ids[0].id})
|
|
149
153
|
`);
|
|
150
|
-
return single.id;
|
|
151
154
|
}
|
|
152
|
-
|
|
155
|
+
return ids;
|
|
156
|
+
}
|
|
157
|
+
function listedAccounts(ids) {
|
|
158
|
+
return ids.map((account) => account.name ? `${account.id} (${account.name})` : account.id).join("; ");
|
|
159
|
+
}
|
|
160
|
+
function refuseMissingAccount(ids) {
|
|
161
|
+
const listed = listedAccounts(ids);
|
|
153
162
|
writeAdsJson({
|
|
154
163
|
ok: false,
|
|
155
164
|
error: {
|
|
@@ -164,6 +173,70 @@ async function resolveAccountIdArg(args) {
|
|
|
164
173
|
});
|
|
165
174
|
process.exit(1);
|
|
166
175
|
}
|
|
176
|
+
async function resolveAccountIdArg(args) {
|
|
177
|
+
const accounts = await accountsInScope(args);
|
|
178
|
+
const [single] = accounts;
|
|
179
|
+
if (accounts.length === 1 && single) return single.id;
|
|
180
|
+
refuseMissingAccount(accounts);
|
|
181
|
+
}
|
|
182
|
+
async function readEachAccount(accounts, read, options = {}) {
|
|
183
|
+
const [first] = accounts;
|
|
184
|
+
if ((accounts.length === 1 || options.byParent) && first) return { rows: await read(first.id), hints: [] };
|
|
185
|
+
let rows = [];
|
|
186
|
+
let accountOf = [];
|
|
187
|
+
const failed = [];
|
|
188
|
+
for (const account of accounts) {
|
|
189
|
+
try {
|
|
190
|
+
const listed = await read(account.id);
|
|
191
|
+
rows.push(...listed);
|
|
192
|
+
accountOf.push(...listed.map(() => account.id));
|
|
193
|
+
} catch (err) {
|
|
194
|
+
failed.push({ account, err });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (failed.length === accounts.length && failed[0]) throw failed[0].err;
|
|
198
|
+
const { time } = options;
|
|
199
|
+
if (time) {
|
|
200
|
+
const order = rows.map((_, i) => i).sort((a, b) => rowTime(rows[b], time) - rowTime(rows[a], time));
|
|
201
|
+
rows = order.flatMap((i) => rows[i] === void 0 ? [] : [rows[i]]);
|
|
202
|
+
accountOf = order.map((i) => accountOf[i] ?? "");
|
|
203
|
+
}
|
|
204
|
+
const total = rows.length;
|
|
205
|
+
const { limit } = options;
|
|
206
|
+
const cut = limit !== void 0 && total > limit;
|
|
207
|
+
if (cut) {
|
|
208
|
+
rows = rows.slice(0, limit);
|
|
209
|
+
accountOf = accountOf.slice(0, limit);
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
rows,
|
|
213
|
+
accountOf,
|
|
214
|
+
hints: [
|
|
215
|
+
`No --account-id, so all ${accounts.length} connected accounts were read: ${listedAccounts(accounts)}. account_id says which one each row is in; --account-id act_<id> reads one.`,
|
|
216
|
+
...cut ? [
|
|
217
|
+
`The accounts returned ${total} rows; the ${time ? "newest" : "first"} ${limit} are shown, as --limit caps the whole listing. --limit <n> shows more, or --account-id act_<id> reads one account.`
|
|
218
|
+
] : [],
|
|
219
|
+
...failed.map(
|
|
220
|
+
({ account, err }) => `${account.id}${account.name ? ` (${account.name})` : ""} could not be read, so none of its rows are here: ${err instanceof Error ? err.message : String(err)}`
|
|
221
|
+
)
|
|
222
|
+
]
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function rowTime(row, time) {
|
|
226
|
+
return row === void 0 ? 0 : time(row) || 0;
|
|
227
|
+
}
|
|
228
|
+
function loggedAt(value) {
|
|
229
|
+
if (typeof value === "number") return value < 1e12 ? value * 1e3 : value;
|
|
230
|
+
return Date.parse(String(value ?? "")) || 0;
|
|
231
|
+
}
|
|
232
|
+
function listingLimit(args, routeDefault) {
|
|
233
|
+
const asked = Number(args.limit);
|
|
234
|
+
return Number.isInteger(asked) && asked > 0 ? asked : routeDefault;
|
|
235
|
+
}
|
|
236
|
+
function withAccountColumn(rows, accountOf) {
|
|
237
|
+
if (!accountOf) return rows;
|
|
238
|
+
return rows.map((row, i) => Object.assign({ account_id: accountOf[i] }, row, { account_id: accountOf[i] }));
|
|
239
|
+
}
|
|
167
240
|
function getDateRange(args) {
|
|
168
241
|
const datePreset = args["date-preset"];
|
|
169
242
|
const since = args.since;
|
|
@@ -213,7 +286,13 @@ export {
|
|
|
213
286
|
metaForbiddenFix,
|
|
214
287
|
handleMetaError,
|
|
215
288
|
normalizeMetaAccountId,
|
|
289
|
+
LISTING_ACCOUNT_ARG,
|
|
290
|
+
accountsInScope,
|
|
216
291
|
resolveAccountIdArg,
|
|
292
|
+
readEachAccount,
|
|
293
|
+
loggedAt,
|
|
294
|
+
listingLimit,
|
|
295
|
+
withAccountColumn,
|
|
217
296
|
getDateRange,
|
|
218
297
|
todayIso,
|
|
219
298
|
daysAgoIso,
|
|
@@ -222,4 +301,4 @@ export {
|
|
|
222
301
|
resolveEffectiveStatus,
|
|
223
302
|
statusFilterHints
|
|
224
303
|
};
|
|
225
|
-
//# sourceMappingURL=chunk-
|
|
304
|
+
//# sourceMappingURL=chunk-YF57BX3S.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../api/src/ads-meta/permissionGates.ts","../src/commands/ads/meta/shared.ts"],"sourcesContent":["/**\n * The refusals Baker writes for Meta work that needs a permission the baseline\n * connection does not ask for — managing catalogs (`catalog_management`) and\n * posting to a Facebook Page (`pages_manage_posts`). Shared verbatim by the\n * backend that throws them and the CLI that explains them, for the same reason\n * as `leadAds.ts`: these name their own cause and remedy, so the CLI must not\n * append Meta's ambiguous \"maybe reconnect, maybe an unassigned asset\" advice.\n */\n\nexport type MetaPermissionGate = \"catalog\" | \"pagePosts\";\n\n/** Everything a person or the agent can see about one per-company Meta permission. */\nexport interface MetaPermissionState {\n /** A Baker admin switched it on for this company, so the consent screen asks for it. */\n enabled: boolean;\n /** The current Meta connection holds it. */\n granted: boolean;\n /** Switched on, but the connection predates it — reconnecting Meta is the fix. */\n reconnectNeeded: boolean;\n}\n\nexport type MetaPermissionStates = Record<\"leadAds\" | MetaPermissionGate, MetaPermissionState>;\n\nexport const META_PERMISSION_NOT_ENABLED_MESSAGE: Record<MetaPermissionGate, string> = {\n catalog:\n \"Catalog changes need the Catalog permission for Meta — ask a Baker admin to turn it on, then reconnect Meta. \" +\n \"Everything else on Meta keeps working: tell the user, and carry on with the rest of the job.\",\n pagePosts:\n \"Facebook Page posts need the Page posts permission for Meta — ask a Baker admin to turn it on, then reconnect \" +\n \"Meta. Everything else on Meta keeps working: tell the user, and carry on with the rest of the job.\",\n};\n\nexport const META_PERMISSION_RECONNECT_MESSAGE: Record<MetaPermissionGate, string> = {\n catalog:\n \"Catalog changes need the Catalog permission for Meta. It is turned on for this company, but this Meta \" +\n \"connection was made before, so it does not hold it — ask the user to reconnect Meta in the dashboard, then \" +\n \"try again. Everything else on Meta keeps working meanwhile.\",\n pagePosts:\n \"Facebook Page posts need the Page posts permission for Meta. It is turned on for this company, but this Meta \" +\n \"connection was made before, so it does not hold it — ask the user to reconnect Meta in the dashboard, then \" +\n \"try again. Everything else on Meta keeps working meanwhile.\",\n};\n\n/**\n * Work that needs a Meta permission Baker's connection does not ask for at all\n * (no switch turns it on): reading and moderating comments on ads\n * (`pages_read_user_content`, `pages_manage_engagement`) and listing an\n * Instagram account's posts (`instagram_basic`). Live on v26.0 (2026-10-15)\n * Meta refused both with code 10.\n */\nexport const META_UNREQUESTED_PERMISSION_MESSAGE = {\n comments:\n \"Reading and moderating comments on ads needs Meta permissions Baker's Meta connection does not ask for yet \" +\n \"(reading people's comments and managing them on the Page). Tell the user that comment moderation happens in \" +\n \"Meta Business Suite for now, and carry on with the rest of the job.\",\n instagramMedia:\n \"Listing an Instagram account's posts needs a Meta permission Baker's Meta connection does not ask for yet. \" +\n \"Ask the user for the post's link or id instead, or boost it from Meta Business Suite, and carry on.\",\n} as const;\n\nconst META_PAGE_ADS_PERMISSION_REMEDY =\n \"A Baker admin turns it on with the lead ads switch for this company; then the user reconnects Meta in the dashboard. \" +\n \"Tell the user, and carry on with the rest of the job.\";\n\n/**\n * Click-to-message ads and Instant Experiences need Meta's Page ads permission\n * (`pages_manage_ads`), which only the lead ads switch adds to the consent\n * screen. `work` names what was refused (\"Click-to-message ads\").\n */\nexport function metaPageAdsPermissionMessage(work: string): string {\n return `${work} need Meta's Page ads permission, and this Meta connection does not have it. ${META_PAGE_ADS_PERMISSION_REMEDY}`;\n}\n\n/**\n * Whether a `FORBIDDEN` message carries one of these refusals. `includes`, not\n * equality: a stage-time refusal may lead with what the op was trying to do.\n */\nexport function isMetaPermissionGateRefusal(message: string): boolean {\n return [\n ...Object.values(META_PERMISSION_NOT_ENABLED_MESSAGE),\n ...Object.values(META_PERMISSION_RECONNECT_MESSAGE),\n ...Object.values(META_UNREQUESTED_PERMISSION_MESSAGE),\n META_PAGE_ADS_PERMISSION_REMEDY,\n ].some((refusal) => message.includes(refusal));\n}\n","import { isMetaPermissionGateRefusal } from \"@baker/api/ads-meta/permissionGates\";\nimport { ApiError, apiGet } from \"../../../client.ts\";\nimport { getEnv } from \"../../../env.ts\";\nimport { handleConnectionError, isOrganizationReadRefusal, needsConnectionFix } from \"../../../error-handler.ts\";\nimport { cacheGet, cacheSet } from \"../cache.ts\";\nimport { writeAdsJson, writeJsonEnvelope } from \"../output.ts\";\nimport { termsRefusalFix } from \"../terms-output.ts\";\nimport type { AdsErrorEnvelope, QueryFix } from \"../types.ts\";\n\nconst DAY_MS = 86_400_000;\n\n/**\n * Meta answers a permission refusal (Graph codes 200/10/294) with a bare\n * \"Permissions error\" that covers two causes needing opposite remedies: a\n * consent grant the connection never got — nothing validates Meta's granted\n * scopes after connect, unlike HubSpot's `requireCapability` — or a role the\n * user lacks on one asset, since a Pixel/Dataset, Page or catalog lives in a\n * Business and is assigned separately from the ad account. Only the blast radius\n * separates them, so hand the agent that test rather than a verdict: guessing\n * \"reconnect\" wastes the user's time on an unassigned asset, and ruling it out\n * strands a connection that really is short a scope.\n */\nexport function metaForbiddenFix(message: string): QueryFix {\n // Baker's own refusal already names the switch or the reconnect; Meta's\n // two-cause advice under it would contradict it.\n if (isMetaPermissionGateRefusal(message)) {\n return { action: \"reject\", explanation: message };\n }\n if (message.includes(\"has not accepted Meta's Lead Generation Terms\")) {\n return {\n action: \"reject\",\n explanation: `${message}\\n\\nMeta confirmed the Page's terms status using its Page access. Give the Page owner the terms link in the error and ask them to accept it before trying the form or lead ad set again. Do not suggest reconnecting Meta for this refusal; continue with other work that does not require the form or ad set.`,\n };\n }\n return {\n action: \"reject\",\n explanation: [\n message,\n \"This is a permission refusal, not a dead connection, and Meta returns the same code for two causes with opposite remedies. Tell them apart by how much else works before you answer.\",\n \"If other reads on this account are ALSO refused (campaigns, ad sets, insights), the connection is short a permission it was never granted. Only the user can widen it, by reconnecting Meta from the dashboard.\",\n \"If those reads work and only this object is refused, the asset (pixel/dataset, Page, or catalog) belongs to a Business the connected user holds no role in. Ad-account access does not carry asset access and reconnecting cannot grant it — the client assigns that asset to the connected user or partner in Meta Business settings, under the asset's own section (Data sources → Datasets for a pixel).\",\n \"Either way do not retry the same call, and do not abort the wider job. Continue with what you can read, and state in your answer that this specific check could not run and why — never present the task as verified when this step was skipped.\",\n ].join(\"\\n\\n\"),\n };\n}\n\nexport function handleMetaError(err: unknown): never {\n if (err instanceof ApiError) {\n if (needsConnectionFix(err.code, err.message)) {\n handleConnectionError(\"meta_ads\", err.message);\n }\n const terms = termsRefusalFix(err.code, err.message);\n if (terms) {\n writeJsonEnvelope({\n ok: false,\n error: { code: terms.code, message: err.message, fix: terms.fix, retryable: false },\n });\n process.exit(1);\n }\n const envelope: AdsErrorEnvelope = {\n ok: false,\n error: {\n code: err.code,\n message: err.message,\n fix:\n err.code === \"FORBIDDEN\" && !isOrganizationReadRefusal(err.message)\n ? metaForbiddenFix(err.message)\n : { action: \"reject\", explanation: err.message },\n retryable:\n err.code === \"RATE_LIMITED\" ||\n err.code === \"UNAVAILABLE\" ||\n err.code === \"INTERNAL_ERROR\" ||\n err.code === \"BUDGET_EXCEEDED\",\n },\n };\n writeAdsJson(envelope);\n process.exit(1);\n }\n const message = err instanceof Error ? err.message : \"Unexpected error\";\n writeAdsJson({ ok: false, error: { code: \"NETWORK_ERROR\", message } });\n process.exit(1);\n}\n\nconst ACCOUNT_ID_RE = /^(act_)?[0-9]+$/;\nconst CONNECTED_ACCOUNTS_TTL_MS = 60 * 60 * 1000;\n\ninterface ConnectedMetaAccount {\n externalId?: string;\n id?: string;\n name?: string;\n}\n\nfunction invalidAccountId(id: string): never {\n writeAdsJson({\n ok: false,\n error: {\n code: \"INVALID_ACCOUNT_ID\",\n message: `Invalid account ID \"${id}\". Expected numeric ID, optionally prefixed with \"act_\".`,\n },\n });\n process.exit(1);\n}\n\n/** A Meta ad account id however it was written — `123`, `act_123`, padded — as `act_123`; null for anything else. */\nexport function normalizeMetaAccountId(raw: string): string | null {\n const trimmed = raw.trim();\n return ACCOUNT_ID_RE.test(trimmed) ? actId(trimmed) : null;\n}\n\nfunction actId(id: string): string {\n return id.startsWith(\"act_\") ? id : `act_${id}`;\n}\n\nasync function connectedMetaAccounts(useCache: boolean): Promise<ConnectedMetaAccount[]> {\n if (useCache) {\n const cached = cacheGet<ConnectedMetaAccount[]>(\"meta-accounts\", \"list\");\n if (cached) return cached.data;\n }\n const accounts = await apiGet<ConnectedMetaAccount[]>(\n \"/api/ads/meta/accounts\",\n useCache ? undefined : { \"skip-cache\": \"true\" },\n );\n // An empty list is never kept: the refusal asks the user to select an account, and the retry must see it.\n if (useCache && accounts.length > 0) cacheSet(\"meta-accounts\", \"list\", accounts, CONNECTED_ACCOUNTS_TTL_MS);\n return accounts;\n}\n\n/** `--account-id` on a listing, which reads every connected account when none is named (`readEachAccount`). */\nexport const LISTING_ACCOUNT_ARG = {\n type: \"string\",\n description:\n \"Meta ad account ID (act_123). Without it the listing reads every connected account, each row tagged with its account_id.\",\n} as const;\n\nexport interface NamedAccount {\n id: string;\n name?: string;\n}\n\n/**\n * The accounts a listing reads: `--account-id` or `BAKER_META_AD_ACCOUNT_ID` as\n * `act_<id>`, else every account the company connected (`readEachAccount`).\n */\nexport async function accountsInScope(args: Record<string, unknown>): Promise<NamedAccount[]> {\n const fromArgs = args[\"account-id\"] as string | undefined;\n const explicit = fromArgs || getEnv().BAKER_META_AD_ACCOUNT_ID;\n if (explicit) {\n if (!ACCOUNT_ID_RE.test(explicit)) invalidAccountId(explicit);\n return [{ id: actId(explicit) }];\n }\n let accounts: ConnectedMetaAccount[];\n try {\n accounts = await connectedMetaAccounts(!args[\"no-cache\"]);\n } catch (err) {\n handleMetaError(err);\n }\n const ids = accounts.flatMap((account) => {\n const id = account.externalId ?? account.id;\n return id && ACCOUNT_ID_RE.test(id) ? [{ id: actId(id), name: account.name }] : [];\n });\n if (ids.length === 0) refuseMissingAccount(ids);\n if (ids.length === 1 && ids[0]) {\n process.stderr.write(`Using account \"${ids[0].name ?? ids[0].id}\" (${ids[0].id})\\n`);\n }\n return ids;\n}\n\nfunction listedAccounts(ids: readonly NamedAccount[]): string {\n return ids.map((account) => (account.name ? `${account.id} (${account.name})` : account.id)).join(\"; \");\n}\n\nfunction refuseMissingAccount(ids: readonly NamedAccount[]): never {\n const listed = listedAccounts(ids);\n writeAdsJson({\n ok: false,\n error: {\n code: \"MISSING_ACCOUNT_ID\",\n message:\n ids.length === 0\n ? \"This company has no Meta ad account selected, so there is no account to default to.\"\n : `This company connected ${ids.length} Meta ad accounts, so pass --account-id to name one: ${listed}.`,\n fix: {\n action: \"reject\",\n explanation:\n ids.length === 0\n ? \"Ask the user to select a Meta ad account for this company in Baker's Meta connection, or pass --account-id act_<id> for one the login reaches (`baker ads meta accounts --available`).\"\n : `Re-run with --account-id set to one of: ${listed}. A question about the whole business covers all ${ids.length}.`,\n },\n retryable: false,\n },\n });\n process.exit(1);\n}\n\n/**\n * The Meta ad account a command works on: `--account-id`, then\n * `BAKER_META_AD_ACCOUNT_ID`, then the company's only connected account — the\n * default `baker ads meta accounts` promises. With several connected, nothing is\n * picked: the refusal lists them so the next call can name one. Listings read\n * every account instead (`readEachAccount`).\n */\nexport async function resolveAccountIdArg(args: Record<string, unknown>): Promise<string> {\n const accounts = await accountsInScope(args);\n const [single] = accounts;\n if (accounts.length === 1 && single) return single.id;\n refuseMissingAccount(accounts);\n}\n\nexport interface AccountsRead<Row> {\n rows: Row[];\n /** Each row's account, in row order — only when several accounts were read. */\n accountOf?: string[];\n hints: string[];\n}\n\nexport interface ReadEachAccountOptions<Row> {\n /** A read scoped by a parent id (`--campaign-id`, `--adset-id`): the parent decides the account. */\n byParent?: boolean;\n /** The most rows the whole listing prints (`--limit`, else the route's default), not each account's. */\n limit?: number;\n /** When each row happened, for a log merged newest first (one account's arrives in that order already). */\n time?: (row: Row) => number;\n}\n\n/**\n * A listing reads whichever account it names; with none named and several\n * connected, it reads each one in turn (the company's request budget refuses a\n * parallel burst) and says which account every row came from. A read guesses\n * nothing by covering them all, while a write still has to name its account.\n * An account Meta refuses is named in a hint while the others' rows still\n * arrive; only when every account fails does the listing fail. A read scoped\n * by a parent id lists that parent's children whichever connected account it\n * is sent with, so `byParent` sends it once (the backend paces it on the\n * parent's own account). `limit` caps the merged listing, as it caps one\n * account's.\n */\nexport async function readEachAccount<Row>(\n accounts: readonly NamedAccount[],\n read: (accountId: string) => Promise<Row[]>,\n options: ReadEachAccountOptions<Row> = {},\n): Promise<AccountsRead<Row>> {\n const [first] = accounts;\n if ((accounts.length === 1 || options.byParent) && first) return { rows: await read(first.id), hints: [] };\n let rows: Row[] = [];\n let accountOf: string[] = [];\n const failed: Array<{ account: NamedAccount; err: unknown }> = [];\n for (const account of accounts) {\n try {\n const listed = await read(account.id);\n rows.push(...listed);\n accountOf.push(...listed.map(() => account.id));\n } catch (err) {\n failed.push({ account, err });\n }\n }\n if (failed.length === accounts.length && failed[0]) throw failed[0].err;\n const { time } = options;\n if (time) {\n const order = rows.map((_, i) => i).sort((a, b) => rowTime(rows[b], time) - rowTime(rows[a], time));\n rows = order.flatMap((i) => (rows[i] === undefined ? [] : [rows[i]]));\n accountOf = order.map((i) => accountOf[i] ?? \"\");\n }\n const total = rows.length;\n const { limit } = options;\n const cut = limit !== undefined && total > limit;\n if (cut) {\n rows = rows.slice(0, limit);\n accountOf = accountOf.slice(0, limit);\n }\n return {\n rows,\n accountOf,\n hints: [\n `No --account-id, so all ${accounts.length} connected accounts were read: ${listedAccounts(accounts)}. account_id says which one each row is in; --account-id act_<id> reads one.`,\n ...(cut\n ? [\n `The accounts returned ${total} rows; the ${time ? \"newest\" : \"first\"} ${limit} are shown, as --limit caps the whole listing. --limit <n> shows more, or --account-id act_<id> reads one account.`,\n ]\n : []),\n ...failed.map(\n ({ account, err }) =>\n `${account.id}${account.name ? ` (${account.name})` : \"\"} could not be read, so none of its rows are here: ${err instanceof Error ? err.message : String(err)}`,\n ),\n ],\n };\n}\n\nfunction rowTime<Row>(row: Row | undefined, time: (row: Row) => number): number {\n return row === undefined ? 0 : time(row) || 0;\n}\n\n/** When a Meta log row happened (`event_time`, a rule run's `timestamp`), for merging accounts' logs. */\nexport function loggedAt(value: unknown): number {\n if (typeof value === \"number\") return value < 1e12 ? value * 1000 : value;\n return Date.parse(String(value ?? \"\")) || 0;\n}\n\n/** The `--limit` a listing asked for, else the route's own default, as the cap on the merged listing. */\nexport function listingLimit(args: Record<string, unknown>, routeDefault: number): number {\n const asked = Number(args.limit);\n return Number.isInteger(asked) && asked > 0 ? asked : routeDefault;\n}\n\n/** Puts each row's account first, when the rows came from several accounts. */\nexport function withAccountColumn<Row extends object>(\n rows: Row[],\n accountOf: readonly string[] | undefined,\n): Array<Row & { account_id?: string }> {\n if (!accountOf) return rows;\n // Ahead of the row's own fields, and over Graph's `account_id` (no `act_`) under --full.\n return rows.map((row, i) => Object.assign({ account_id: accountOf[i] }, row, { account_id: accountOf[i] }));\n}\n\nexport function getDateRange(args: Record<string, unknown>): { datePreset?: string; since?: string; until?: string } {\n const datePreset = args[\"date-preset\"] as string | undefined;\n const since = args.since as string | undefined;\n const until = args.until as string | undefined;\n if (since && until) return { since, until };\n return { datePreset: datePreset ?? \"last_7d\" };\n}\n\nexport function todayIso(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nexport function daysAgoIso(days: number): string {\n return new Date(Date.now() - days * DAY_MS).toISOString().slice(0, 10);\n}\n\nexport function csvOrJson(args: Record<string, unknown>): string {\n return (args.output as string | undefined) ?? \"json\";\n}\n\n/**\n * Matched by Meta itself, so finding one entity by name reads only the rows that\n * match instead of the whole account.\n */\nexport const NAME_CONTAINS_ARG = {\n type: \"string\",\n description:\n \"Only rows whose name contains this text, matched by Meta before anything is returned. Start here to find one entity by name: --name-contains octubre --all-statuses\",\n} as const;\n\n/**\n * Default to ACTIVE-only on listings — that's almost always what an AI agent or\n * a human glance wants. Pass `--effective-status ACTIVE,PAUSED` to override, or\n * `--all-statuses` to drop the filter entirely.\n */\nexport function resolveEffectiveStatus(args: Record<string, unknown>): string | undefined {\n if (args[\"all-statuses\"]) {\n return undefined;\n }\n const explicit = args[\"effective-status\"] as string | undefined;\n if (explicit) {\n return explicit;\n }\n // Rows named by id are wanted whatever they are doing; the ACTIVE default would hide a paused one.\n if (args.ids) {\n return undefined;\n }\n return \"ACTIVE\";\n}\n\n/**\n * An empty listing under a status filter reads exactly like \"nothing exists\":\n * a paused campaign's ad sets are CAMPAIGN_PAUSED, so the ACTIVE default hides\n * every one of them. Say which filter produced the empty list and how to widen it.\n */\nexport function statusFilterHints(\n rows: ReadonlyArray<unknown>,\n effectiveStatus: string | undefined,\n noun: string,\n): string[] {\n if (rows.length > 0 || effectiveStatus === undefined) return [];\n if (effectiveStatus === \"ACTIVE\") {\n return [\n `No ACTIVE ${noun}. The ACTIVE filter hides paused, archived and in-review ones (under a paused campaign or ad set that is all of them), so this does NOT mean none exist. Re-run with --all-statuses before concluding there are none.`,\n ];\n }\n return [\n `No ${noun} with effective_status ${effectiveStatus}. Re-run with --all-statuses to see every status before concluding there are none.`,\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuBO,IAAM,sCAA0E;AAAA,EACrF,SACE;AAAA,EAEF,WACE;AAEJ;AAEO,IAAM,oCAAwE;AAAA,EACnF,SACE;AAAA,EAGF,WACE;AAGJ;AASO,IAAM,sCAAsC;AAAA,EACjD,UACE;AAAA,EAGF,gBACE;AAEJ;AAEA,IAAM,kCACJ;AAgBK,SAAS,4BAA4B,SAA0B;AACpE,SAAO;AAAA,IACL,GAAG,OAAO,OAAO,mCAAmC;AAAA,IACpD,GAAG,OAAO,OAAO,iCAAiC;AAAA,IAClD,GAAG,OAAO,OAAO,mCAAmC;AAAA,IACpD;AAAA,EACF,EAAE,KAAK,CAAC,YAAY,QAAQ,SAAS,OAAO,CAAC;AAC/C;;;AC3EA,IAAM,SAAS;AAaR,SAAS,iBAAiB,SAA2B;AAG1D,MAAI,4BAA4B,OAAO,GAAG;AACxC,WAAO,EAAE,QAAQ,UAAU,aAAa,QAAQ;AAAA,EAClD;AACA,MAAI,QAAQ,SAAS,+CAA+C,GAAG;AACrE,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,aAAa,GAAG,OAAO;AAAA;AAAA;AAAA,IACzB;AAAA,EACF;AACA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,aAAa;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,KAAK,MAAM;AAAA,EACf;AACF;AAEO,SAAS,gBAAgB,KAAqB;AACnD,MAAI,eAAe,UAAU;AAC3B,QAAI,mBAAmB,IAAI,MAAM,IAAI,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SAAO;AACT;AAOO,SAAS,kBACd,MACA,iBACA,MACU;AACV,MAAI,KAAK,SAAS,KAAK,oBAAoB,OAAW,QAAO,CAAC;AAC9D,MAAI,oBAAoB,UAAU;AAChC,WAAO;AAAA,MACL,aAAa,IAAI;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AAAA,IACL,MAAM,IAAI,0BAA0B,eAAe;AAAA,EACrD;AACF;","names":[]}
|
package/dist/cli.js
CHANGED
|
@@ -625,7 +625,7 @@ Introspection: Run 'baker schema <command>' to inspect argument schemas.`
|
|
|
625
625
|
capabilities: () => import("./capabilities-FJAYWDY6.js").then((m) => m.capabilitiesCommand),
|
|
626
626
|
actions: () => import("./actions-PO35WQVS.js").then((m) => m.actionsCommand),
|
|
627
627
|
"scheduled-agents": () => import("./scheduled-agents-4UNG26CX.js").then((m) => m.scheduledAgentsCommand),
|
|
628
|
-
ads: () => import("./ads-
|
|
628
|
+
ads: () => import("./ads-MYACXO5A.js").then((m) => m.adsCommand),
|
|
629
629
|
brand: () => import("./brand-ARJMSWJA.js").then((m) => m.brandCommand),
|
|
630
630
|
analytics: () => import("./analytics-EM4NNEG5.js").then((m) => m.analyticsCommand),
|
|
631
631
|
experiment: () => import("./experiment-KOCG7PPI.js").then((m) => m.experimentCommand),
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
command
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-VUJPKIJN.js";
|
|
4
4
|
import {
|
|
5
5
|
bareAccountId,
|
|
6
6
|
failWriteValidation,
|
|
@@ -8,10 +8,10 @@ import {
|
|
|
8
8
|
requireTarget,
|
|
9
9
|
stageOp,
|
|
10
10
|
upper
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-2WHALQOJ.js";
|
|
12
12
|
import "./chunk-3R62EYYX.js";
|
|
13
13
|
import "./chunk-GDFJOCDO.js";
|
|
14
|
-
import "./chunk-
|
|
14
|
+
import "./chunk-YF57BX3S.js";
|
|
15
15
|
import "./chunk-XD7C5OE7.js";
|
|
16
16
|
import "./chunk-UKENQSZ2.js";
|
|
17
17
|
import "./chunk-D5FY4FAK.js";
|
|
@@ -171,4 +171,4 @@ export {
|
|
|
171
171
|
campaignsCopyCommand,
|
|
172
172
|
copyPayloadFromFlags
|
|
173
173
|
};
|
|
174
|
-
//# sourceMappingURL=copy-writes-
|
|
174
|
+
//# sourceMappingURL=copy-writes-S4X5XUSK.js.map
|
|
@@ -3,13 +3,16 @@ import {
|
|
|
3
3
|
registerMetaListSchema,
|
|
4
4
|
shapeMetaListRows,
|
|
5
5
|
writeMetaListRows
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-VBIKO56A.js";
|
|
7
7
|
import "./chunk-PRPSV4VB.js";
|
|
8
8
|
import {
|
|
9
|
+
LISTING_ACCOUNT_ARG,
|
|
10
|
+
accountsInScope,
|
|
9
11
|
csvOrJson,
|
|
10
12
|
handleMetaError,
|
|
11
|
-
|
|
12
|
-
|
|
13
|
+
listingLimit,
|
|
14
|
+
readEachAccount
|
|
15
|
+
} from "./chunk-YF57BX3S.js";
|
|
13
16
|
import "./chunk-QALAJNBG.js";
|
|
14
17
|
import {
|
|
15
18
|
NO_CACHE_ARG
|
|
@@ -27,7 +30,7 @@ import "./chunk-YQSBHWOI.js";
|
|
|
27
30
|
// src/commands/ads/meta/creatives.ts
|
|
28
31
|
import { defineCommand } from "citty";
|
|
29
32
|
var listArgs = {
|
|
30
|
-
"account-id":
|
|
33
|
+
"account-id": LISTING_ACCOUNT_ARG,
|
|
31
34
|
"creative-id": {
|
|
32
35
|
type: "string",
|
|
33
36
|
description: "One creative ID, or several comma-separated, read in one call: --creative-id 2394\u2026,2395\u2026"
|
|
@@ -42,7 +45,7 @@ var listArgs = {
|
|
|
42
45
|
};
|
|
43
46
|
registerMetaListSchema(
|
|
44
47
|
"creatives",
|
|
45
|
-
"List ad creatives, or read some by id, as a table by default: id, name, status, object_type, dynamic (the asset feed's optimization_type), body, title, description, link, cta, url_tags, image_hash, video_id, page_id, instagram_user_id, effective_object_story_id. Copy and assets are read from wherever the creative keeps them (top level, object_story_spec, its carousel cards or asset_feed_spec); a dynamic creative's variants and a carousel's cards come back as lists. Per-placement rules and enhancement toggles are --fields (asset_feed_spec.asset_customization_rules, degrees_of_freedom_spec) or --full. Start here: baker ads meta creatives --creative-id 2394\u2026,2395\u2026 --output json.",
|
|
48
|
+
"List ad creatives, or read some by id, as a table by default: id, name, status, object_type, dynamic (the asset feed's optimization_type), body, title, description, link, cta, url_tags, image_hash, video_id, page_id, instagram_user_id, effective_object_story_id. Copy and assets are read from wherever the creative keeps them (top level, object_story_spec, its carousel cards or asset_feed_spec); a dynamic creative's variants and a carousel's cards come back as lists. Per-placement rules and enhancement toggles are --fields (asset_feed_spec.asset_customization_rules, degrees_of_freedom_spec) or --full. Start here: baker ads meta creatives --creative-id 2394\u2026,2395\u2026 --output json. With no --account-id and several accounts connected, every account is read and each row leads with its account_id.",
|
|
46
49
|
listArgs
|
|
47
50
|
);
|
|
48
51
|
var CREATIVE_IDS_PER_REQUEST = 50;
|
|
@@ -64,19 +67,29 @@ var listCommand = defineCommand({
|
|
|
64
67
|
},
|
|
65
68
|
args: listArgs,
|
|
66
69
|
run: async ({ args }) => {
|
|
70
|
+
const ids = (args["creative-id"] ?? "").split(",").map((id) => id.trim()).filter(Boolean);
|
|
71
|
+
const accounts = ids.length > 0 ? [] : await accountsInScope(args);
|
|
67
72
|
try {
|
|
68
|
-
const ids = (args["creative-id"] ?? "").split(",").map((id) => id.trim()).filter(Boolean);
|
|
69
|
-
let data;
|
|
70
73
|
if (ids.length > 0) {
|
|
71
|
-
data = await readCreatives(ids, Boolean(args["no-cache"]));
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (args["name-contains"]) params["name-contains"] = args["name-contains"];
|
|
75
|
-
if (args.limit) params.limit = args.limit;
|
|
76
|
-
if (args["no-cache"]) params["skip-cache"] = "true";
|
|
77
|
-
data = await apiGet("/api/ads/meta/creatives", params);
|
|
74
|
+
const data = await readCreatives(ids, Boolean(args["no-cache"]));
|
|
75
|
+
writeMetaListRows("creatives", shapeMetaListRows("creatives", data, args), csvOrJson(args));
|
|
76
|
+
return;
|
|
78
77
|
}
|
|
79
|
-
|
|
78
|
+
const params = {};
|
|
79
|
+
if (args["name-contains"]) params["name-contains"] = args["name-contains"];
|
|
80
|
+
if (args.limit) params.limit = args.limit;
|
|
81
|
+
if (args["no-cache"]) params["skip-cache"] = "true";
|
|
82
|
+
const read = await readEachAccount(
|
|
83
|
+
accounts,
|
|
84
|
+
(accountId) => apiGet("/api/ads/meta/creatives", { ...params, "account-id": accountId }),
|
|
85
|
+
{ limit: listingLimit(args, 500) }
|
|
86
|
+
);
|
|
87
|
+
writeMetaListRows(
|
|
88
|
+
"creatives",
|
|
89
|
+
shapeMetaListRows("creatives", read.rows, args, read.accountOf),
|
|
90
|
+
csvOrJson(args),
|
|
91
|
+
read.hints
|
|
92
|
+
);
|
|
80
93
|
} catch (err) {
|
|
81
94
|
handleMetaError(err);
|
|
82
95
|
}
|
|
@@ -102,9 +115,9 @@ Examples:
|
|
|
102
115
|
},
|
|
103
116
|
subCommands: {
|
|
104
117
|
list: listCommand,
|
|
105
|
-
create: () => import("./write-commands-
|
|
106
|
-
update: () => import("./write-commands-
|
|
107
|
-
delete: () => import("./asset-writes-
|
|
118
|
+
create: () => import("./write-commands-T46SVSQ7.js").then((m) => m.adCreativesCreateCommand),
|
|
119
|
+
update: () => import("./write-commands-T46SVSQ7.js").then((m) => m.adCreativesUpdateCommand),
|
|
120
|
+
delete: () => import("./asset-writes-TXYCARXJ.js").then((m) => m.creativesDeleteCommand)
|
|
108
121
|
},
|
|
109
122
|
// `args` stays even though the parent has no `run`: citty scans rawArgs for the
|
|
110
123
|
// subcommand name using THIS command's arg defs, so without them `--account-id act_1`
|
|
@@ -116,4 +129,4 @@ Examples:
|
|
|
116
129
|
export {
|
|
117
130
|
creativesCommand
|
|
118
131
|
};
|
|
119
|
-
//# sourceMappingURL=creatives-
|
|
132
|
+
//# sourceMappingURL=creatives-BCTG6PV4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/ads/meta/creatives.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { NO_CACHE_ARG } from \"../../../cache-flag.ts\";\nimport { apiGet } from \"../../../client.ts\";\nimport { META_LIST_SHAPE_ARGS, registerMetaListSchema, shapeMetaListRows, writeMetaListRows } from \"./list-rows.ts\";\nimport {\n accountsInScope,\n csvOrJson,\n handleMetaError,\n LISTING_ACCOUNT_ARG,\n listingLimit,\n readEachAccount,\n} from \"./shared.ts\";\n\nconst listArgs = {\n \"account-id\": LISTING_ACCOUNT_ARG,\n \"creative-id\": {\n type: \"string\",\n description: \"One creative ID, or several comma-separated, read in one call: --creative-id 2394…,2395…\",\n },\n \"name-contains\": {\n type: \"string\",\n description:\n \"Only creatives whose name contains this text (any case), matched by Baker while it reads the account; --limit counts the matches. Start here to find a creative by name: --name-contains octubre\",\n },\n limit: { type: \"string\", description: \"Max rows (default 500)\" },\n \"no-cache\": NO_CACHE_ARG,\n ...META_LIST_SHAPE_ARGS,\n} as const;\n\nregisterMetaListSchema(\n \"creatives\",\n \"List ad creatives, or read some by id, as a table by default: id, name, status, object_type, dynamic (the asset feed's optimization_type), body, title, description, link, cta, url_tags, image_hash, video_id, page_id, instagram_user_id, effective_object_story_id. Copy and assets are read from wherever the creative keeps them (top level, object_story_spec, its carousel cards or asset_feed_spec); a dynamic creative's variants and a carousel's cards come back as lists. Per-placement rules and enhancement toggles are --fields (asset_feed_spec.asset_customization_rules, degrees_of_freedom_spec) or --full. Start here: baker ads meta creatives --creative-id 2394…,2395… --output json. With no --account-id and several accounts connected, every account is read and each row leads with its account_id.\",\n listArgs,\n);\n\nconst CREATIVE_IDS_PER_REQUEST = 50;\n\n/**\n * Up to 50 ids per request, which Baker reads from Meta in one Graph batch call. The requests run one after\n * another: the company's request budget (a burst of 4, then 2 a second) refuses a parallel burst.\n */\nasync function readCreatives(ids: string[], skipCache: boolean): Promise<Array<Record<string, unknown>>> {\n const rows: Array<Record<string, unknown>> = [];\n for (let start = 0; start < ids.length; start += CREATIVE_IDS_PER_REQUEST) {\n const read = await apiGet<Record<string, unknown> | Array<Record<string, unknown>>>(\"/api/ads/meta/creatives\", {\n \"creative-id\": ids.slice(start, start + CREATIVE_IDS_PER_REQUEST).join(\",\"),\n ...(skipCache ? { \"skip-cache\": \"true\" } : {}),\n });\n rows.push(...(Array.isArray(read) ? read : [read]));\n }\n return rows;\n}\n\nconst listCommand = defineCommand({\n meta: {\n name: \"list\",\n description:\n \"List ad creatives, or read some by ID. Runs by default when no subcommand is given. Example: baker ads meta creatives --creative-id 2394…,2395…\",\n },\n args: listArgs,\n run: async ({ args }) => {\n const ids = ((args[\"creative-id\"] as string | undefined) ?? \"\")\n .split(\",\")\n .map((id) => id.trim())\n .filter(Boolean);\n const accounts = ids.length > 0 ? [] : await accountsInScope(args);\n try {\n if (ids.length > 0) {\n const data = await readCreatives(ids, Boolean(args[\"no-cache\"]));\n writeMetaListRows(\"creatives\", shapeMetaListRows(\"creatives\", data, args), csvOrJson(args));\n return;\n }\n const params: Record<string, string> = {};\n if (args[\"name-contains\"]) params[\"name-contains\"] = args[\"name-contains\"] as string;\n if (args.limit) params.limit = args.limit as string;\n if (args[\"no-cache\"]) params[\"skip-cache\"] = \"true\";\n const read = await readEachAccount(\n accounts,\n (accountId) =>\n apiGet<Array<Record<string, unknown>>>(\"/api/ads/meta/creatives\", { ...params, \"account-id\": accountId }),\n { limit: listingLimit(args, 500) },\n );\n writeMetaListRows(\n \"creatives\",\n shapeMetaListRows(\"creatives\", read.rows, args, read.accountOf),\n csvOrJson(args),\n read.hints,\n );\n } catch (err) {\n handleMetaError(err);\n }\n },\n});\n\nexport const creativesCommand = defineCommand({\n meta: {\n name: \"creatives\",\n description: `List ad creatives, fetch one by ID, or stage writes (create/update). Write subcommands stage ops on this chat's draft.\n\nImportant: Meta creatives are effectively immutable once attached to an ad. Editing copy/image/CTA = create\na new creative + repoint the ad (baker ads meta ads update <adId> --creative <ref>).\n\nReads print a table by default: id, name, status, object_type, dynamic, body, title, description, link, cta,\nurl_tags, image_hash, video_id, page_id, instagram_user_id, effective_object_story_id — read from wherever the\ncreative keeps them; a dynamic creative's variants and a carousel's cards come back as lists. --fields (dotted paths) or --full for the rest.\n\nExamples:\n baker ads meta creatives --account-id act_123 --name-contains octubre — find creatives by name\n baker ads meta creatives --creative-id 23842...,23843... --output json # read several at once\n baker ads meta creatives --creative-id 23842... --fields id,asset_feed_spec.asset_customization_rules --output json\n baker ads meta creatives create --page 555 --message \"Save now\" --link https://x.com --image-hash abc… --cta SHOP_NOW`,\n },\n subCommands: {\n list: listCommand,\n create: () => import(\"./write-commands.ts\").then((m) => m.adCreativesCreateCommand),\n update: () => import(\"./write-commands.ts\").then((m) => m.adCreativesUpdateCommand),\n delete: () => import(\"./asset-writes.ts\").then((m) => m.creativesDeleteCommand),\n },\n // `args` stays even though the parent has no `run`: citty scans rawArgs for the\n // subcommand name using THIS command's arg defs, so without them `--account-id act_1`\n // would read `act_1` as a subcommand. `default` (not `run`) dispatches the bare\n // invocation — citty falls through to `run` after a subcommand, double-executing it.\n args: listArgs,\n default: \"list\",\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAa9B,IAAM,WAAW;AAAA,EACf,cAAc;AAAA,EACd,eAAe;AAAA,IACb,MAAM;AAAA,IACN,aAAa;AAAA,EACf;AAAA,EACA,iBAAiB;AAAA,IACf,MAAM;AAAA,IACN,aACE;AAAA,EACJ;AAAA,EACA,OAAO,EAAE,MAAM,UAAU,aAAa,yBAAyB;AAAA,EAC/D,YAAY;AAAA,EACZ,GAAG;AACL;AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,2BAA2B;AAMjC,eAAe,cAAc,KAAe,WAA6D;AACvG,Q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