@koda-sl/baker-cli 0.379.0-dev.0114084a3 → 0.379.0-dev.bfd923423

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 CHANGED
@@ -865,7 +865,7 @@ baker ads x targeting-constants --constant tv_shows --locale en-US
865
865
 
866
866
  ### Meta Ads (`baker ads meta`)
867
867
 
868
- Meta Marketing API (Facebook + Instagram). Connect via OAuth in the dashboard, pick which ad accounts to scope to, then call from the CLI. Account ID via `--account-id act_123` or `BAKER_META_AD_ACCOUNT_ID` env var.
868
+ Meta Marketing API (Facebook + Instagram). Connect via OAuth in the dashboard, pick which ad accounts to scope to, then call from the CLI. Account ID via `--account-id act_123` or `BAKER_META_AD_ACCOUNT_ID` env var; with a single connected account it is used automatically.
869
869
 
870
870
  The command surface is **curated for AI agents**, not 1:1 with the Marketing API. Smart defaults so an agent doesn't need to remember every flag.
871
871
 
@@ -969,7 +969,7 @@ baker ads meta draft remove meta_temp_cr # removing a create cascades to depen
969
969
  baker ads meta draft clear
970
970
  ```
971
971
 
972
- Status changes are `pause|resume|archive|delete` subcommands on `campaigns`/`adsets`/`ads`. `archive` keeps the entity readable in Ads Manager; `delete` removes it permanently (an archived entity can only be deleted). `duplicate` reconstructs a paused copy from the live snapshot (`--replace` also pauses the original once the copy publishes — write it attached, `--replace=false` or `--no-replace`, since the spaced form `--replace false` is rejected: a boolean flag written with a space is set to true and the word dropped). Carousel/dynamic creatives and complex targeting go via `--file` (creativeType `carousel`/`dynamic`; full Meta targeting spec). Advantage+ Creative enhancements: `--standard-enhancements on|off`, or per-feature toggles via a `--file` `enhancements.features` map.
972
+ Status changes are `pause|resume|archive` subcommands on `campaigns`/`adsets`/`ads`. `duplicate` reconstructs a paused copy from the live snapshot (`--replace` also pauses the original once the copy publishes — write it attached, `--replace=false` or `--no-replace`, since the spaced form `--replace false` is rejected: a boolean flag written with a space is set to true and the word dropped). Carousel/dynamic creatives and complex targeting go via `--file` (creativeType `carousel`/`dynamic`; full Meta targeting spec). Advantage+ Creative enhancements: `--standard-enhancements on|off`, or per-feature toggles via a `--file` `enhancements.features` map.
973
973
 
974
974
  #### Smart defaults (so agents don't enumerate the API)
975
975
 
@@ -4,7 +4,8 @@ import {
4
4
  writeAdsJson
5
5
  } from "./chunk-XHC4LMK4.js";
6
6
  import {
7
- ApiError
7
+ ApiError,
8
+ apiGet
8
9
  } from "./chunk-MF7YA62W.js";
9
10
  import {
10
11
  getEnv
@@ -46,30 +47,78 @@ function handleMetaError(err) {
46
47
  process.exit(1);
47
48
  }
48
49
  var ACCOUNT_ID_RE = /^(act_)?[0-9]+$/;
49
- function resolveAccountIdArg(args) {
50
+ function withActPrefix(id) {
51
+ return id.startsWith("act_") ? id : `act_${id}`;
52
+ }
53
+ function fetchConnectedAccounts() {
54
+ return apiGet("/api/ads/meta/accounts", { "skip-cache": "true" });
55
+ }
56
+ function connectedAccountId(account) {
57
+ const id = account.externalId ?? account.id ?? account.account_id;
58
+ return id && ACCOUNT_ID_RE.test(id) ? withActPrefix(id) : void 0;
59
+ }
60
+ async function resolveAccountIdArg(args) {
50
61
  const fromArgs = args["account-id"];
51
62
  const id = fromArgs || getEnv().BAKER_META_AD_ACCOUNT_ID;
52
- if (!id) {
63
+ if (id) {
64
+ if (!ACCOUNT_ID_RE.test(id)) {
65
+ writeAdsJson({
66
+ ok: false,
67
+ error: {
68
+ code: "INVALID_ACCOUNT_ID",
69
+ message: `Invalid account ID "${id}". Expected numeric ID, optionally prefixed with "act_".`
70
+ }
71
+ });
72
+ process.exit(1);
73
+ }
74
+ return withActPrefix(id);
75
+ }
76
+ let accounts;
77
+ try {
78
+ accounts = await fetchConnectedAccounts();
79
+ } catch (err) {
80
+ if (err instanceof ApiError && needsConnectionFix(err.code, err.message)) {
81
+ handleConnectionError("meta_ads", err.message);
82
+ }
53
83
  writeAdsJson({
54
84
  ok: false,
55
85
  error: {
56
86
  code: "MISSING_ACCOUNT_ID",
57
- message: "Pass --account-id or set BAKER_META_AD_ACCOUNT_ID. Run `baker ads meta accounts` to find IDs."
87
+ message: "Could not look up this company's Meta ad accounts. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID. Run `baker ads meta accounts` to find IDs."
58
88
  }
59
89
  });
60
90
  process.exit(1);
61
91
  }
62
- if (!ACCOUNT_ID_RE.test(id)) {
92
+ const connected = accounts.flatMap((account) => {
93
+ const accountId = connectedAccountId(account);
94
+ return accountId ? [{ id: accountId, name: account.name }] : [];
95
+ });
96
+ const [single] = connected;
97
+ if (connected.length === 1 && single) {
98
+ process.stderr.write(`Using Meta ad account ${single.name ? `"${single.name}" ` : ""}(${single.id})
99
+ `);
100
+ return single.id;
101
+ }
102
+ if (connected.length === 0) {
63
103
  writeAdsJson({
64
104
  ok: false,
65
105
  error: {
66
- code: "INVALID_ACCOUNT_ID",
67
- message: `Invalid account ID "${id}". Expected numeric ID, optionally prefixed with "act_".`
106
+ code: "MISSING_ACCOUNT_ID",
107
+ message: "Meta is connected, but no ad account is picked for this company. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID. Run `baker ads meta accounts --include-all` to find IDs."
68
108
  }
69
109
  });
70
110
  process.exit(1);
71
111
  }
72
- return id.startsWith("act_") ? id : `act_${id}`;
112
+ const list = connected.map((account) => ` ${account.id}${account.name ? ` ${account.name}` : ""}`).join("\n");
113
+ writeAdsJson({
114
+ ok: false,
115
+ error: {
116
+ code: "MULTIPLE_ACCOUNTS",
117
+ message: `This company connected ${connected.length} Meta ad accounts. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID:
118
+ ${list}`
119
+ }
120
+ });
121
+ process.exit(1);
73
122
  }
74
123
  function getDateRange(args) {
75
124
  const datePreset = args["date-preset"];
@@ -125,4 +174,4 @@ export {
125
174
  resolveEffectiveStatus,
126
175
  statusFilterHints
127
176
  };
128
- //# sourceMappingURL=chunk-VLUGGVJL.js.map
177
+ //# sourceMappingURL=chunk-KAOU6QLP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/ads/meta/shared.ts"],"sourcesContent":["import { ApiError, apiGet } from \"../../../client.ts\";\nimport { getEnv } from \"../../../env.ts\";\nimport { handleConnectionError, needsConnectionFix } from \"../../../error-handler.ts\";\nimport { writeAdsJson } from \"../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 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 envelope: AdsErrorEnvelope = {\n ok: false,\n error: {\n code: err.code,\n message: err.message,\n fix: err.code === \"FORBIDDEN\" ? metaForbiddenFix(err.message) : { action: \"reject\", explanation: err.message },\n retryable: err.code === \"RATE_LIMITED\" || err.code === \"UNAVAILABLE\" || err.code === \"INTERNAL_ERROR\",\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]+$/;\n\n/** A row of `/api/ads/meta/accounts` — the company's picked accounts, as `baker ads meta accounts` prints them. */\ninterface ConnectedMetaAccount {\n externalId?: string;\n id?: string;\n account_id?: string;\n name?: string;\n}\n\nfunction withActPrefix(id: string): string {\n return id.startsWith(\"act_\") ? id : `act_${id}`;\n}\n\n/**\n * Read past both caches — the CLI's disk cache and the backend's hour-long one:\n * an account picked since the last listing must turn a sole-account default\n * into a refusal at once, not an hour later.\n */\nfunction fetchConnectedAccounts(): Promise<ConnectedMetaAccount[]> {\n return apiGet<ConnectedMetaAccount[]>(\"/api/ads/meta/accounts\", { \"skip-cache\": \"true\" });\n}\n\nfunction connectedAccountId(account: ConnectedMetaAccount): string | undefined {\n const id = account.externalId ?? account.id ?? account.account_id;\n return id && ACCOUNT_ID_RE.test(id) ? withActPrefix(id) : undefined;\n}\n\n/**\n * The Meta ad account a command works on: `--account-id`, else\n * `BAKER_META_AD_ACCOUNT_ID`, else the company's only connected account — the\n * default `baker ads meta accounts` promises. With several connected, nothing\n * is picked for the agent: the refusal lists them so the next call can name one.\n */\nexport async function resolveAccountIdArg(args: Record<string, unknown>): Promise<string> {\n const fromArgs = args[\"account-id\"] as string | undefined;\n const id = fromArgs || getEnv().BAKER_META_AD_ACCOUNT_ID;\n if (id) {\n if (!ACCOUNT_ID_RE.test(id)) {\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 return withActPrefix(id);\n }\n\n let accounts: ConnectedMetaAccount[];\n try {\n accounts = await fetchConnectedAccounts();\n } catch (err) {\n if (err instanceof ApiError && needsConnectionFix(err.code, err.message)) {\n handleConnectionError(\"meta_ads\", err.message);\n }\n writeAdsJson({\n ok: false,\n error: {\n code: \"MISSING_ACCOUNT_ID\",\n message:\n \"Could not look up this company's Meta ad accounts. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID. Run `baker ads meta accounts` to find IDs.\",\n },\n });\n process.exit(1);\n }\n\n const connected = accounts.flatMap((account) => {\n const accountId = connectedAccountId(account);\n return accountId ? [{ id: accountId, name: account.name }] : [];\n });\n const [single] = connected;\n if (connected.length === 1 && single) {\n process.stderr.write(`Using Meta ad account ${single.name ? `\"${single.name}\" ` : \"\"}(${single.id})\\n`);\n return single.id;\n }\n if (connected.length === 0) {\n writeAdsJson({\n ok: false,\n error: {\n code: \"MISSING_ACCOUNT_ID\",\n message:\n \"Meta is connected, but no ad account is picked for this company. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID. Run `baker ads meta accounts --include-all` to find IDs.\",\n },\n });\n process.exit(1);\n }\n const list = connected.map((account) => ` ${account.id}${account.name ? ` ${account.name}` : \"\"}`).join(\"\\n\");\n writeAdsJson({\n ok: false,\n error: {\n code: \"MULTIPLE_ACCOUNTS\",\n message: `This company connected ${connected.length} Meta ad accounts. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID:\\n${list}`,\n },\n });\n process.exit(1);\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 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":";;;;;;;;;;;;;;AAMA,IAAM,SAAS;AAaR,SAAS,iBAAiB,SAA2B;AAC1D,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,OA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