@koda-sl/baker-cli 0.883.0 → 0.884.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +3 -1
  2. package/dist/{account-reads-TSDWJ3A2.js → account-reads-7DPRPWBK.js} +3 -2
  3. package/dist/{account-reads-TSDWJ3A2.js.map → account-reads-7DPRPWBK.js.map} +1 -1
  4. package/dist/{ads-ZSHBQHNK.js → ads-Z2YUBDUF.js} +2 -2
  5. package/dist/{analytics-6TNLZ4LA.js → analytics-E5OPCERI.js} +6 -5
  6. package/dist/{analytics-6TNLZ4LA.js.map → analytics-E5OPCERI.js.map} +1 -1
  7. package/dist/{changes-7WLOTKVE.js → changes-FQ2NWBJQ.js} +3 -2
  8. package/dist/{changes-7WLOTKVE.js.map → changes-FQ2NWBJQ.js.map} +1 -1
  9. package/dist/{chunk-Z65I6WS6.js → chunk-DX4SRYED.js} +13 -5
  10. package/dist/chunk-DX4SRYED.js.map +1 -0
  11. package/dist/{chunk-J464JWY7.js → chunk-ENTB4ILS.js} +8 -4
  12. package/dist/chunk-ENTB4ILS.js.map +1 -0
  13. package/dist/{chunk-JOQBRK4E.js → chunk-FRWCTFTP.js} +9 -4
  14. package/dist/chunk-FRWCTFTP.js.map +1 -0
  15. package/dist/{chunk-BX5AAH7T.js → chunk-IDLSLJIM.js} +4 -2
  16. package/dist/{chunk-BX5AAH7T.js.map → chunk-IDLSLJIM.js.map} +1 -1
  17. package/dist/chunk-LVLAFUXQ.js +37 -0
  18. package/dist/chunk-LVLAFUXQ.js.map +1 -0
  19. package/dist/cli.js +6 -6
  20. package/dist/{config-UR3ZKS25.js → config-Z52BRC3M.js} +3 -2
  21. package/dist/{config-UR3ZKS25.js.map → config-Z52BRC3M.js.map} +1 -1
  22. package/dist/{conversion-upload-command-CWMZEFCT.js → conversion-upload-command-ZZ5JYMBL.js} +7 -4
  23. package/dist/conversion-upload-command-ZZ5JYMBL.js.map +1 -0
  24. package/dist/{draft-KMRFGWIO.js → draft-3L5UZ3JP.js} +7 -4
  25. package/dist/draft-3L5UZ3JP.js.map +1 -0
  26. package/dist/{draft-XWJF772C.js → draft-CZEMQHTX.js} +3 -2
  27. package/dist/{draft-XWJF772C.js.map → draft-CZEMQHTX.js.map} +1 -1
  28. package/dist/{draft-5H6MKAKW.js → draft-FOHLBTWV.js} +3 -2
  29. package/dist/{draft-5H6MKAKW.js.map → draft-FOHLBTWV.js.map} +1 -1
  30. package/dist/{forecast-WTVRSFFA.js → forecast-SXZBIHFB.js} +3 -2
  31. package/dist/{forecast-WTVRSFFA.js.map → forecast-SXZBIHFB.js.map} +1 -1
  32. package/dist/{ga4-K6ARTEPX.js → ga4-6J3IMDSU.js} +12 -12
  33. package/dist/{google-N3GW4MDV.js → google-F77XV4ZC.js} +59 -40
  34. package/dist/google-F77XV4ZC.js.map +1 -0
  35. package/dist/{hubspot-BG4BI3RU.js → hubspot-24MLH5N7.js} +2 -2
  36. package/dist/{plan-C5U4U55M.js → plan-JVD6BMEO.js} +3 -2
  37. package/dist/{plan-C5U4U55M.js.map → plan-JVD6BMEO.js.map} +1 -1
  38. package/dist/{read-UXFNPEQ5.js → read-VI63RNL6.js} +3 -2
  39. package/dist/{read-UXFNPEQ5.js.map → read-VI63RNL6.js.map} +1 -1
  40. package/dist/{search-terms-WKE47TW5.js → search-terms-SWRRTKBV.js} +3 -2
  41. package/dist/{search-terms-WKE47TW5.js.map → search-terms-SWRRTKBV.js.map} +1 -1
  42. package/dist/{sends-5UCPQZ7F.js → sends-PEQJOPRM.js} +19 -4
  43. package/dist/sends-PEQJOPRM.js.map +1 -0
  44. package/dist/{shopify-NJFARTN3.js → shopify-IRHELCGF.js} +3 -2
  45. package/dist/{shopify-NJFARTN3.js.map → shopify-IRHELCGF.js.map} +1 -1
  46. package/dist/{sources-XYKENWZF.js → sources-CACBM65R.js} +38 -17
  47. package/dist/sources-CACBM65R.js.map +1 -0
  48. package/dist/{tag-manager-5Q5MHQPL.js → tag-manager-QO6VW57E.js} +10 -10
  49. package/dist/{themes-LWG3LX7O.js → themes-GMZOWC3X.js} +3 -2
  50. package/dist/{themes-LWG3LX7O.js.map → themes-GMZOWC3X.js.map} +1 -1
  51. package/dist/{write-commands-IAMIUSK4.js → write-commands-GRBE5V34.js} +3 -2
  52. package/dist/{write-commands-IAMIUSK4.js.map → write-commands-GRBE5V34.js.map} +1 -1
  53. package/dist/{write-commands-JXP2NHRY.js → write-commands-MZUVJBGO.js} +3 -2
  54. package/dist/{write-commands-JXP2NHRY.js.map → write-commands-MZUVJBGO.js.map} +1 -1
  55. package/package.json +1 -1
  56. package/dist/chunk-J464JWY7.js.map +0 -1
  57. package/dist/chunk-JOQBRK4E.js.map +0 -1
  58. package/dist/chunk-Z65I6WS6.js.map +0 -1
  59. package/dist/conversion-upload-command-CWMZEFCT.js.map +0 -1
  60. package/dist/draft-KMRFGWIO.js.map +0 -1
  61. package/dist/google-N3GW4MDV.js.map +0 -1
  62. package/dist/sends-5UCPQZ7F.js.map +0 -1
  63. package/dist/sources-XYKENWZF.js.map +0 -1
  64. /package/dist/{ads-ZSHBQHNK.js.map → ads-Z2YUBDUF.js.map} +0 -0
  65. /package/dist/{ga4-K6ARTEPX.js.map → ga4-6J3IMDSU.js.map} +0 -0
  66. /package/dist/{hubspot-BG4BI3RU.js.map → hubspot-24MLH5N7.js.map} +0 -0
  67. /package/dist/{tag-manager-5Q5MHQPL.js.map → tag-manager-QO6VW57E.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import "./chunk-BX5AAH7T.js";
1
+ import "./chunk-IDLSLJIM.js";
2
2
  import {
3
3
  failNotConnected
4
4
  } from "./chunk-WN5FEDWT.js";
@@ -1044,4 +1044,4 @@ export {
1044
1044
  hubspotCommand,
1045
1045
  workflowViewHints
1046
1046
  };
1047
- //# sourceMappingURL=hubspot-BG4BI3RU.js.map
1047
+ //# sourceMappingURL=hubspot-24MLH5N7.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-5YOMORZ2.js";
4
4
  import {
5
5
  TAG_MANAGER_TIMEOUT_MS
6
- } from "./chunk-J464JWY7.js";
6
+ } from "./chunk-ENTB4ILS.js";
7
7
  import {
8
8
  trackingPlanErrorEnvelope
9
9
  } from "./chunk-SPLOBKTE.js";
@@ -11,6 +11,7 @@ import {
11
11
  ANALYTICS_EVENT_DOORS
12
12
  } from "./chunk-7JM5OH6I.js";
13
13
  import "./chunk-5TURKO4J.js";
14
+ import "./chunk-LVLAFUXQ.js";
14
15
  import "./chunk-MTMWOUKN.js";
15
16
  import "./chunk-D5FY4FAK.js";
16
17
  import "./chunk-NYUWPJ4K.js";
@@ -210,4 +211,4 @@ var planCommand = defineCommand({
210
211
  export {
211
212
  planCommand
212
213
  };
213
- //# sourceMappingURL=plan-C5U4U55M.js.map
214
+ //# sourceMappingURL=plan-JVD6BMEO.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/analytics/plan.ts","../../api/src/analytics/trackingPlanWire.ts","../../api/src/analytics/trackingPlan.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { trackingPlanRequestSchema, trackingPlanResponseSchema } from \"@baker/api/analytics/trackingPlanWire\";\nimport { defineCommand } from \"citty\";\nimport { apiPost } from \"../../client.ts\";\nimport { getEnv } from \"../../env.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { TAG_MANAGER_TIMEOUT_MS } from \"../tag-manager/shared.ts\";\nimport { trackingPlanErrorEnvelope } from \"./errorEnvelope.ts\";\n\nconst description =\n \"Start here before building a replacement Form: read the agreed journeys, event names, purposes and readiness. --json @plan.json stages the complete plan, with optional wireConversions, funnel steps and a managed Tag Manager installation. Each event records its actual emitter or the missing change and owner. Prepared is not verified. See analytics.md for the contract. Repeating installation preparation replaces its own staged tags; applies only at Publish. --full includes evidence; the default keeps the decision inventory compact.\";\nconst args = {\n json: {\n type: \"string\" as const,\n description: \"Preparation request as JSON or @path; omit to read the effective plan\",\n required: false,\n },\n full: { type: \"boolean\" as const, description: \"Include all journey and verification evidence\", required: false },\n};\nregisterSchema({ command: \"analytics.plan\", routes: [\"POST /api/analytics/plan\"], effect: \"stage\", description, args });\n\nexport const planCommand = defineCommand({\n meta: { name: \"plan\", description },\n args,\n run: async ({ args }) => {\n try {\n const input: unknown = args.json\n ? JSON.parse(args.json.startsWith(\"@\") ? readFileSync(args.json.slice(1), \"utf8\") : args.json)\n : {};\n const parsed = trackingPlanRequestSchema.parse(input);\n const body = { ...parsed, chatId: getEnv().BAKER_CHAT_ID };\n const response = trackingPlanResponseSchema.parse(\n // Preparing stages the Tag Manager install, which queues behind other companies' requests.\n await apiPost(\"/api/analytics/plan\", body, { timeoutMs: TAG_MANAGER_TIMEOUT_MS }),\n );\n const plan = response.data.plan;\n writeJsonEnvelope({\n ...response,\n data: {\n ...response.data,\n plan:\n args.full || !plan\n ? plan\n : {\n journeys: plan.journeys.map(\n ({ key, name, strategy, status, destinationUrl, requirement, owner }) => ({\n key,\n name,\n strategy,\n status,\n destinationUrl,\n requirement,\n owner,\n }),\n ),\n events: plan.events.map(\n ({ eventKey, name, purpose, door, sourceEvent, status, requirement, owner }) => ({\n eventKey,\n name,\n purpose,\n door,\n sourceEvent,\n status,\n requirement,\n owner,\n }),\n ),\n },\n },\n });\n } catch (error) {\n writeJsonEnvelope({ ok: false, error: trackingPlanErrorEnvelope(error) });\n process.exitCode = 1;\n }\n },\n});\n","import { z } from \"zod\";\nimport { funnelStepSchema } from \"../funnel/wire\";\nimport { parseEventKey } from \"./eventKey\";\nimport { trackingPlanSchema } from \"./trackingPlan\";\n\nconst key = z.string().trim().min(1).max(100);\nconst variableName = z\n .string()\n .trim()\n .min(1)\n .max(200)\n .refine((value) => !/[{}<>\"'\\\\\\r\\n]/.test(value), \"Use a plain container variable name\");\nexport const trackingInstallationSchema = z.object({\n containerId: key,\n baseTagName: key,\n folderId: key.optional(),\n consent: z.enum([\"auto\", \"strict\"]).default(\"auto\"),\n measure: z.enum([\"campaigns\", \"outcomes\", \"all\"]).default(\"campaigns\"),\n events: z\n .array(\n z.object({\n eventKey: key.refine((value) => parseEventKey(value) !== null, \"Use an existing Baker event key\"),\n tagName: key,\n triggerId: key,\n properties: z.record(key, variableName).default({}),\n eventIdVariable: variableName.optional(),\n }),\n )\n .max(50),\n});\nexport type TrackingInstallation = z.infer<typeof trackingInstallationSchema>;\nexport const trackingPlanRequestSchema = z\n .object({\n chatId: z.string().optional(),\n plan: trackingPlanSchema.optional(),\n wireConversions: z.boolean().default(false),\n steps: z.array(funnelStepSchema).max(30).optional(),\n installation: trackingInstallationSchema.optional(),\n })\n .superRefine((request, ctx) => {\n if (!request.plan && (request.installation || request.wireConversions || request.steps))\n ctx.addIssue({ code: \"custom\", message: \"Preparation needs the agreed tracking plan\" });\n });\nexport const trackingPlanResponseSchema = z.object({\n ok: z.literal(true),\n data: z.object({ plan: trackingPlanSchema.nullable(), staged: z.boolean() }),\n hints: z.array(z.string()).optional(),\n});\nexport type TrackingPlanResponse = z.infer<typeof trackingPlanResponseSchema>;\n","import { z } from \"zod\";\nimport { ANALYTICS_EVENT_DOORS } from \"./eventDoors\";\nimport { parseEventKey } from \"./eventKey\";\nimport { describeSendEvent } from \"./sends\";\n\nconst text = z.string().trim().min(1).max(2000);\nconst key = z.string().trim().min(1).max(100);\nconst webUrl = z\n .url()\n .refine(\n (value) => URL.canParse(value) && [\"https:\", \"http:\"].includes(new URL(value).protocol),\n \"Use a website address\",\n );\n\nconst trackingEventSchema = z\n .object({\n eventKey: key.refine((value) => parseEventKey(value) !== null, \"Use an existing Baker event key\"),\n name: text,\n purpose: z.enum([\"conversion\", \"progress\", \"diagnostic\", \"uncounted\"]),\n door: z.enum(ANALYTICS_EVENT_DOORS),\n sourceEvent: key.optional(),\n emitterEvidence: text.optional(),\n status: z.enum([\"prepared\", \"waiting\", \"published\", \"verified\"]),\n requirement: text.optional(),\n owner: text.optional(),\n verificationEvidence: text.optional(),\n })\n .superRefine((event, ctx) => {\n if (event.status === \"waiting\") {\n if (!event.requirement || !event.owner)\n ctx.addIssue({ code: \"custom\", message: \"A waiting event needs its requirement and owner\" });\n } else if (!event.emitterEvidence) {\n ctx.addIssue({ code: \"custom\", message: \"A prepared event needs evidence that the source emits it\" });\n }\n if ([\"published\", \"verified\"].includes(event.status) && !event.verificationEvidence) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Published or verified tracking needs evidence; a staged tag is only prepared\",\n });\n }\n });\nexport type TrackingEvent = z.infer<typeof trackingEventSchema>;\n\nconst trackingJourneySchema = z\n .object({\n key,\n name: text,\n entryUrls: z.array(webUrl).max(50),\n destinationUrl: webUrl,\n strategy: z.enum([\"native\", \"embed\", \"api\", \"link\"]),\n status: z.enum([\"supported\", \"waiting\"]),\n requiredFields: z.array(key).max(100),\n attribution: text,\n acceptanceEvidence: text.optional(),\n continuationEvidence: text.optional(),\n requirement: text.optional(),\n owner: text.optional(),\n })\n .superRefine((journey, ctx) => {\n if (journey.strategy === \"link\" && journey.requiredFields.length > 0)\n ctx.addIssue({\n code: \"custom\",\n message: \"A link handoff must not capture details that the destination asks for again\",\n });\n if (journey.status === \"waiting\" && (!journey.requirement || !journey.owner))\n ctx.addIssue({ code: \"custom\", message: \"A waiting journey needs its requirement and owner\" });\n if (\n journey.status === \"supported\" &&\n journey.strategy === \"api\" &&\n (!journey.acceptanceEvidence || !journey.continuationEvidence)\n )\n ctx.addIssue({\n code: \"custom\",\n message: \"An API replacement needs accepted-submission and continuation evidence\",\n });\n });\n\nexport const trackingPlanSchema = z\n .object({\n journeys: z.array(trackingJourneySchema).max(30),\n events: z.array(trackingEventSchema).max(100),\n })\n .superRefine((plan, ctx) => {\n for (const entries of [plan.journeys.map((journey) => journey.key), plan.events.map((event) => event.eventKey)]) {\n if (new Set(entries).size !== entries.length)\n ctx.addIssue({ code: \"custom\", message: \"Each journey and event must appear once\" });\n }\n });\nexport type TrackingPlan = z.infer<typeof trackingPlanSchema>;\n\nexport const TRACKING_STATUS_LABEL = {\n prepared: \"Prepared\",\n waiting: \"Waiting for a change\",\n published: \"Published\",\n verified: \"Verified\",\n} as const;\n\nexport const TRACKING_PURPOSE_LABEL = {\n conversion: \"Conversion\",\n progress: \"Progress\",\n diagnostic: \"Diagnostic\",\n uncounted: \"Not counted\",\n} as const;\n\nexport const TRACKING_DOOR_LABEL = {\n pages: \"Baker pages\",\n website: \"Website pixel\",\n server: \"Your server\",\n integrations: \"Integration\",\n} as const;\n\n/** Review the journey, event mapping, requirements and supporting evidence. */\nexport function describeTrackingPlan(plan: TrackingPlan | null | undefined): string {\n if (!plan) return \"No tracking plan\";\n return (\n [\n ...plan.journeys.map((journey) =>\n [\n journey.name,\n (\n {\n native: \"Existing platform form\",\n embed: \"Embedded Form\",\n api: \"Connected submission\",\n link: \"Link to existing Form\",\n } as const\n )[journey.strategy],\n journey.status === \"supported\" ? \"Supported\" : \"Waiting for a change\",\n journey.entryUrls.join(\", \"),\n `to ${journey.destinationUrl}`,\n `Fields: ${journey.requiredFields.join(\", \") || \"none\"}`,\n journey.attribution,\n journey.acceptanceEvidence,\n journey.continuationEvidence,\n journey.requirement,\n journey.owner,\n ]\n .filter(Boolean)\n .join(\" · \"),\n ),\n ...plan.events.map((event) =>\n [\n event.name,\n `${event.sourceEvent ? `App event: ${event.sourceEvent} → ` : \"\"}Report event: ${describeSendEvent(event.eventKey)}`,\n TRACKING_PURPOSE_LABEL[event.purpose],\n TRACKING_DOOR_LABEL[event.door],\n TRACKING_STATUS_LABEL[event.status],\n event.emitterEvidence,\n event.requirement,\n event.owner,\n event.verificationEvidence,\n ]\n .filter(Boolean)\n .join(\" · \"),\n ),\n ].join(\"\\n\") || \"No journeys or events\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;;;ACA7B,SAAS,KAAAA,UAAS;;;ACAlB,SAAS,SAAS;AAKlB,IAAM,OAAO,EAAE,OA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M;AAAA,UACJ,GAAG,SAAS;AAAA,UACZ,MACEA,MAAK,QAAQ,CAAC,OACV,OACA;AAAA,YACE,UAAU,KAAK,SAAS;AAAA,cACtB,CAAC,EAAE,KAAAC,MAAK,MAAM,UAAU,QAAQ,gBAAgB,aAAa,MAAM,OAAO;AAAA,gBACxE,KAAAA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,cACF;AAAA,YACF;AAAA,YACA,QAAQ,KAAK,OAAO;AAAA,cAClB,CAAC,EAAE,UAAU,MAAM,SAAS,MAAM,aAAa,QAAQ,aAAa,MAAM,OAAO;AAAA,gBAC/E;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACR;AAAA,MACF,CAAC;AAAA,IACH,SAAS,OAAO;AACd,wBAAkB,EAAE,IAAI,OAAO,OAAO,0BAA0B,KAAK,EAAE,CAAC;AACxE,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF,CAAC;","names":["z","key","z","args","key"]}
1
+ {"version":3,"sources":["../src/commands/analytics/plan.ts","../../api/src/analytics/trackingPlanWire.ts","../../api/src/analytics/trackingPlan.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { trackingPlanRequestSchema, trackingPlanResponseSchema } from \"@baker/api/analytics/trackingPlanWire\";\nimport { defineCommand } from \"citty\";\nimport { apiPost } from \"../../client.ts\";\nimport { getEnv } from \"../../env.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { TAG_MANAGER_TIMEOUT_MS } from \"../tag-manager/shared.ts\";\nimport { trackingPlanErrorEnvelope } from \"./errorEnvelope.ts\";\n\nconst description =\n \"Start here before building a replacement Form: read the agreed journeys, event names, purposes and readiness. --json @plan.json stages the complete plan, with optional wireConversions, funnel steps and a managed Tag Manager installation. Each event records its actual emitter or the missing change and owner. Prepared is not verified. See analytics.md for the contract. Repeating installation preparation replaces its own staged tags; applies only at Publish. --full includes evidence; the default keeps the decision inventory compact.\";\nconst args = {\n json: {\n type: \"string\" as const,\n description: \"Preparation request as JSON or @path; omit to read the effective plan\",\n required: false,\n },\n full: { type: \"boolean\" as const, description: \"Include all journey and verification evidence\", required: false },\n};\nregisterSchema({ command: \"analytics.plan\", routes: [\"POST /api/analytics/plan\"], effect: \"stage\", description, args });\n\nexport const planCommand = defineCommand({\n meta: { name: \"plan\", description },\n args,\n run: async ({ args }) => {\n try {\n const input: unknown = args.json\n ? JSON.parse(args.json.startsWith(\"@\") ? readFileSync(args.json.slice(1), \"utf8\") : args.json)\n : {};\n const parsed = trackingPlanRequestSchema.parse(input);\n const body = { ...parsed, chatId: getEnv().BAKER_CHAT_ID };\n const response = trackingPlanResponseSchema.parse(\n // Preparing stages the Tag Manager install, which queues behind other companies' requests.\n await apiPost(\"/api/analytics/plan\", body, { timeoutMs: TAG_MANAGER_TIMEOUT_MS }),\n );\n const plan = response.data.plan;\n writeJsonEnvelope({\n ...response,\n data: {\n ...response.data,\n plan:\n args.full || !plan\n ? plan\n : {\n journeys: plan.journeys.map(\n ({ key, name, strategy, status, destinationUrl, requirement, owner }) => ({\n key,\n name,\n strategy,\n status,\n destinationUrl,\n requirement,\n owner,\n }),\n ),\n events: plan.events.map(\n ({ eventKey, name, purpose, door, sourceEvent, status, requirement, owner }) => ({\n eventKey,\n name,\n purpose,\n door,\n sourceEvent,\n status,\n requirement,\n owner,\n }),\n ),\n },\n },\n });\n } catch (error) {\n writeJsonEnvelope({ ok: false, error: trackingPlanErrorEnvelope(error) });\n process.exitCode = 1;\n }\n },\n});\n","import { z } from \"zod\";\nimport { funnelStepSchema } from \"../funnel/wire\";\nimport { parseEventKey } from \"./eventKey\";\nimport { trackingPlanSchema } from \"./trackingPlan\";\n\nconst key = z.string().trim().min(1).max(100);\nconst variableName = z\n .string()\n .trim()\n .min(1)\n .max(200)\n .refine((value) => !/[{}<>\"'\\\\\\r\\n]/.test(value), \"Use a plain container variable name\");\nexport const trackingInstallationSchema = z.object({\n containerId: key,\n baseTagName: key,\n folderId: key.optional(),\n consent: z.enum([\"auto\", \"strict\"]).default(\"auto\"),\n measure: z.enum([\"campaigns\", \"outcomes\", \"all\"]).default(\"campaigns\"),\n events: z\n .array(\n z.object({\n eventKey: key.refine((value) => parseEventKey(value) !== null, \"Use an existing Baker event key\"),\n tagName: key,\n triggerId: key,\n properties: z.record(key, variableName).default({}),\n eventIdVariable: variableName.optional(),\n }),\n )\n .max(50),\n});\nexport type TrackingInstallation = z.infer<typeof trackingInstallationSchema>;\nexport const trackingPlanRequestSchema = z\n .object({\n chatId: z.string().optional(),\n plan: trackingPlanSchema.optional(),\n wireConversions: z.boolean().default(false),\n steps: z.array(funnelStepSchema).max(30).optional(),\n installation: trackingInstallationSchema.optional(),\n })\n .superRefine((request, ctx) => {\n if (!request.plan && (request.installation || request.wireConversions || request.steps))\n ctx.addIssue({ code: \"custom\", message: \"Preparation needs the agreed tracking plan\" });\n });\nexport const trackingPlanResponseSchema = z.object({\n ok: z.literal(true),\n data: z.object({ plan: trackingPlanSchema.nullable(), staged: z.boolean() }),\n hints: z.array(z.string()).optional(),\n});\nexport type TrackingPlanResponse = z.infer<typeof trackingPlanResponseSchema>;\n","import { z } from \"zod\";\nimport { ANALYTICS_EVENT_DOORS } from \"./eventDoors\";\nimport { parseEventKey } from \"./eventKey\";\nimport { describeSendEvent } from \"./sends\";\n\nconst text = z.string().trim().min(1).max(2000);\nconst key = z.string().trim().min(1).max(100);\nconst webUrl = z\n .url()\n .refine(\n (value) => URL.canParse(value) && [\"https:\", \"http:\"].includes(new URL(value).protocol),\n \"Use a website address\",\n );\n\nconst trackingEventSchema = z\n .object({\n eventKey: key.refine((value) => parseEventKey(value) !== null, \"Use an existing Baker event key\"),\n name: text,\n purpose: z.enum([\"conversion\", \"progress\", \"diagnostic\", \"uncounted\"]),\n door: z.enum(ANALYTICS_EVENT_DOORS),\n sourceEvent: key.optional(),\n emitterEvidence: text.optional(),\n status: z.enum([\"prepared\", \"waiting\", \"published\", \"verified\"]),\n requirement: text.optional(),\n owner: text.optional(),\n verificationEvidence: text.optional(),\n })\n .superRefine((event, ctx) => {\n if (event.status === \"waiting\") {\n if (!event.requirement || !event.owner)\n ctx.addIssue({ code: \"custom\", message: \"A waiting event needs its requirement and owner\" });\n } else if (!event.emitterEvidence) {\n ctx.addIssue({ code: \"custom\", message: \"A prepared event needs evidence that the source emits it\" });\n }\n if ([\"published\", \"verified\"].includes(event.status) && !event.verificationEvidence) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Published or verified tracking needs evidence; a staged tag is only prepared\",\n });\n }\n });\nexport type TrackingEvent = z.infer<typeof trackingEventSchema>;\n\nconst trackingJourneySchema = z\n .object({\n key,\n name: text,\n entryUrls: z.array(webUrl).max(50),\n destinationUrl: webUrl,\n strategy: z.enum([\"native\", \"embed\", \"api\", \"link\"]),\n status: z.enum([\"supported\", \"waiting\"]),\n requiredFields: z.array(key).max(100),\n attribution: text,\n acceptanceEvidence: text.optional(),\n continuationEvidence: text.optional(),\n requirement: text.optional(),\n owner: text.optional(),\n })\n .superRefine((journey, ctx) => {\n if (journey.strategy === \"link\" && journey.requiredFields.length > 0)\n ctx.addIssue({\n code: \"custom\",\n message: \"A link handoff must not capture details that the destination asks for again\",\n });\n if (journey.status === \"waiting\" && (!journey.requirement || !journey.owner))\n ctx.addIssue({ code: \"custom\", message: \"A waiting journey needs its requirement and owner\" });\n if (\n journey.status === \"supported\" &&\n journey.strategy === \"api\" &&\n (!journey.acceptanceEvidence || !journey.continuationEvidence)\n )\n ctx.addIssue({\n code: \"custom\",\n message: \"An API replacement needs accepted-submission and continuation evidence\",\n });\n });\n\nexport const trackingPlanSchema = z\n .object({\n journeys: z.array(trackingJourneySchema).max(30),\n events: z.array(trackingEventSchema).max(100),\n })\n .superRefine((plan, ctx) => {\n for (const entries of [plan.journeys.map((journey) => journey.key), plan.events.map((event) => event.eventKey)]) {\n if (new Set(entries).size !== entries.length)\n ctx.addIssue({ code: \"custom\", message: \"Each journey and event must appear once\" });\n }\n });\nexport type TrackingPlan = z.infer<typeof trackingPlanSchema>;\n\nexport const TRACKING_STATUS_LABEL = {\n prepared: \"Prepared\",\n waiting: \"Waiting for a change\",\n published: \"Published\",\n verified: \"Verified\",\n} as const;\n\nexport const TRACKING_PURPOSE_LABEL = {\n conversion: \"Conversion\",\n progress: \"Progress\",\n diagnostic: \"Diagnostic\",\n uncounted: \"Not counted\",\n} as const;\n\nexport const TRACKING_DOOR_LABEL = {\n pages: \"Baker pages\",\n website: \"Website pixel\",\n server: \"Your server\",\n integrations: \"Integration\",\n} as const;\n\n/** Review the journey, event mapping, requirements and supporting evidence. */\nexport function describeTrackingPlan(plan: TrackingPlan | null | undefined): string {\n if (!plan) return \"No tracking plan\";\n return (\n [\n ...plan.journeys.map((journey) =>\n [\n journey.name,\n (\n {\n native: \"Existing platform form\",\n embed: \"Embedded Form\",\n api: \"Connected submission\",\n link: \"Link to existing Form\",\n } as const\n )[journey.strategy],\n journey.status === \"supported\" ? \"Supported\" : \"Waiting for a change\",\n journey.entryUrls.join(\", \"),\n `to ${journey.destinationUrl}`,\n `Fields: ${journey.requiredFields.join(\", \") || \"none\"}`,\n journey.attribution,\n journey.acceptanceEvidence,\n journey.continuationEvidence,\n journey.requirement,\n journey.owner,\n ]\n .filter(Boolean)\n .join(\" · \"),\n ),\n ...plan.events.map((event) =>\n [\n event.name,\n `${event.sourceEvent ? `App event: ${event.sourceEvent} → ` : \"\"}Report event: ${describeSendEvent(event.eventKey)}`,\n TRACKING_PURPOSE_LABEL[event.purpose],\n TRACKING_DOOR_LABEL[event.door],\n TRACKING_STATUS_LABEL[event.status],\n event.emitterEvidence,\n event.requirement,\n event.owner,\n event.verificationEvidence,\n ]\n .filter(Boolean)\n .join(\" · \"),\n ),\n ].join(\"\\n\") || \"No journeys or events\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;AAAA;AAAA,QAE1C,MAAM,QAAQ,uBAAuB,MAAM,EAAE,WAAW,uBAAuB,CAAC;AAAA,MAClF;AACA,YAAM,OAAO,SAAS,KAAK;AAC3B,wBAAkB;AAAA,QAChB,GAAG;AAAA,QACH,MAAM;AAAA,UACJ,GAAG,SAAS;AAAA,UACZ,MACEA,MAAK,QAAQ,CAAC,OACV,OACA;AAAA,YACE,UAAU,KAAK,SAAS;AAAA,cACtB,CAAC,EAAE,KAAAC,MAAK,MAAM,UAAU,QAAQ,gBAAgB,aAAa,MAAM,OAAO;AAAA,gBACxE,KAAAA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,cACF;AAAA,YACF;AAAA,YACA,QAAQ,KAAK,OAAO;AAAA,cAClB,CAAC,EAAE,UAAU,MAAM,SAAS,MAAM,aAAa,QAAQ,aAAa,MAAM,OAAO;AAAA,gBAC/E;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACR;AAAA,MACF,CAAC;AAAA,IACH,SAAS,OAAO;AACd,wBAAkB,EAAE,IAAI,OAAO,OAAO,0BAA0B,KAAK,EAAE,CAAC;AACxE,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF,CAAC;","names":["z","key","z","args","key"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  TAG_MANAGER_TIMEOUT_MS,
3
3
  handleError
4
- } from "./chunk-J464JWY7.js";
4
+ } from "./chunk-ENTB4ILS.js";
5
5
  import {
6
6
  connectedResourceHints
7
7
  } from "./chunk-P4NSJS54.js";
@@ -9,6 +9,7 @@ import {
9
9
  AVAILABLE_ARG,
10
10
  writeAvailableAccounts
11
11
  } from "./chunk-VWTL4ELG.js";
12
+ import "./chunk-LVLAFUXQ.js";
12
13
  import "./chunk-MTMWOUKN.js";
13
14
  import "./chunk-D5FY4FAK.js";
14
15
  import {
@@ -163,4 +164,4 @@ export {
163
164
  containersHints,
164
165
  readCommand
165
166
  };
166
- //# sourceMappingURL=read-UXFNPEQ5.js.map
167
+ //# sourceMappingURL=read-VI63RNL6.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/tag-manager/read.ts"],"sourcesContent":["import type { TagManagerContainer, TagManagerContainersResponse, TagManagerReadResponse } from \"@baker/api/tag-manager\";\nimport { defineCommand } from \"citty\";\nimport { AVAILABLE_ARG, writeAvailableAccounts } from \"../../available-accounts.ts\";\nimport { apiGet, apiPost } from \"../../client.ts\";\nimport { connectedResourceHints } from \"../../connected-resources.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { handleError, TAG_MANAGER_TIMEOUT_MS } from \"./shared.ts\";\n\nregisterSchema({\n command: \"tagManager.containers\",\n description:\n \"List the Google Tag Manager containers this company selected. There can be several, and Baker may read and change all of them. Start here to confirm which containers you are managing.\",\n args: { available: AVAILABLE_ARG },\n});\n\nregisterSchema({\n command: \"tagManager.read\",\n description:\n \"Read what is currently inside a Tag Manager container: tags, triggers, variables, folders and enabled built-in variables. Start here before proposing any change, so you edit what exists instead of duplicating it. Pass --container when the company connected more than one. Compact by default: each tag names the triggers it fires on (firesOn, built-ins included), and data.measures maps each id the tags send to (meta:<pixel>, googleAnalytics:G-…, googleAds:AW-…) to the tag ids sending there. Narrow with --search <text> (name, type, Custom HTML, trigger conditions) or --id <ids>, which also gives Custom HTML tags their script URLs (src); pass --full for raw Tag Manager objects of what is left, trigger ids included.\",\n args: {\n container: {\n type: \"string\",\n description: \"Numeric container id (optional only when one container is connected)\",\n required: false,\n },\n workspace: { type: \"string\", description: \"Workspace id (defaults to the default workspace)\", required: false },\n entities: {\n type: \"string\",\n description: \"Comma-separated subset: tag,trigger,variable,folder,builtInVariable\",\n required: false,\n },\n full: { type: \"boolean\", description: \"Include the raw Tag Manager object for each entity\", required: false },\n search: {\n type: \"string\",\n description:\n \"Only entities mentioning this text (case-insensitive): name, type, parameters incl. Custom HTML, trigger conditions — e.g. hubspot, go.example.com\",\n required: false,\n },\n id: { type: \"string\", description: \"Only these entity ids, comma-separated (e.g. 24,126)\", required: false },\n },\n});\n\n/**\n * A company can connect several containers. Reading the list as \"the container\"\n * is the mistake to head off here: with more than one, nothing may be read or\n * staged without naming which, because Baker refuses to guess.\n *\n */\nexport function containersHints(\n containers: TagManagerContainer[],\n unavailableContainers: NonNullable<TagManagerContainersResponse[\"unavailableContainers\"]> = [],\n): string[] {\n const hints = connectedResourceHints({\n plural: \"Tag Manager containers\",\n singular: \"Tag Manager container\",\n flag: \"--container\",\n resources: containers.map((container) => ({\n id: container.containerId,\n label: `${container.publicId} · ${container.name}`,\n })),\n });\n if (unavailableContainers.length > 0) {\n const [available] = containers;\n if (containers.length === 1 && available) {\n hints.length = 0;\n hints.push(\n `Use --container ${available.containerId} for ${available.publicId} (${available.name}); ` +\n \"another selected container cannot be opened.\",\n );\n }\n hints.push(\n `Tag Manager cannot open ${unavailableContainers.map((container) => `${container.publicId} (${container.name})`).join(\", \")}. ` +\n \"Ask the user to reconnect with a Google account that has access to these containers.\",\n );\n }\n return hints;\n}\n\nexport const containersCommand = defineCommand({\n meta: {\n name: \"containers\",\n description: `List Tag Manager containers selected by this company.\n\nStart here:\n baker tag-manager containers\n baker tag-manager containers --available # every container the login reaches, selected or not`,\n },\n args: { available: AVAILABLE_ARG },\n run: async ({ args }) => {\n if (args.available) return writeAvailableAccounts(\"google-tag-manager\", handleError);\n try {\n const data = await apiGet<TagManagerContainersResponse>(\"/api/tag-manager/containers\");\n writeJsonEnvelope({ ok: true, data, hints: containersHints(data.containers, data.unavailableContainers) });\n } catch (err) {\n handleError(err);\n }\n },\n});\n\nexport const readCommand = defineCommand({\n meta: {\n name: \"read\",\n description: `Read the current contents of the Tag Manager container — always do this before staging changes.\n\nStart here:\n baker tag-manager read\n baker tag-manager read --entities tag,trigger\n baker tag-manager read --entities tag --search hubspot # which tags load HubSpot, their script src, on which triggers\n baker tag-manager read --entities trigger --search go.example.com # triggers whose conditions name a host\n baker tag-manager read --entities tag --id 24,126 --full # those tags' raw objects (HTML, parameters)\n\nCompact tags carry firesOn (trigger names, built-ins like \"All Pages\" included); their trigger ids (built-ins included) come with --id <tag id> --full.\ndata.measures maps where the tags send (meta:<pixel id>, googleAnalytics:G-…, googleAds:AW-…, hubspot:<id>) to the tag ids sending there.`,\n },\n args: {\n container: { type: \"string\", description: \"Numeric container id\", required: false },\n workspace: { type: \"string\", description: \"Workspace id\", required: false },\n entities: { type: \"string\", description: \"Comma-separated entity subset\", required: false },\n full: { type: \"boolean\", description: \"Include raw Tag Manager objects\", required: false },\n search: {\n type: \"string\",\n description: \"Only entities mentioning this text: name, type, parameters, Custom HTML, trigger conditions\",\n required: false,\n },\n id: { type: \"string\", description: \"Only these entity ids, comma-separated\", required: false },\n },\n run: async ({ args }) => {\n const list = (value: unknown) =>\n typeof value === \"string\" && value.length > 0\n ? value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n : undefined;\n const entities = list(args.entities);\n const ids = list(args.id);\n const search = typeof args.search === \"string\" && args.search.length > 0 ? args.search : undefined;\n try {\n const data = await apiPost<TagManagerReadResponse>(\n \"/api/tag-manager/read\",\n { containerId: args.container, workspaceId: args.workspace, entities, full: args.full === true, ids, search },\n { timeoutMs: TAG_MANAGER_TIMEOUT_MS },\n );\n // One line: the container's name and public id are already in data.container, and a\n // compact tag names its triggers without their ids, so this says where the ids are.\n const hints: string[] = [\n `Stage changes with --container ${data.container.containerId}. Name a trigger or variable by its numeric id ` +\n \"(--entities trigger,variable) or {{Name}}, one staged in this chat by its gtm_temp_* ref.\",\n ];\n if (data.publicationWarning) hints.push(data.publicationWarning);\n if (\n (ids || search) &&\n [data.tags, data.triggers, data.variables, data.folders, data.builtInVariables].every(\n (rows) => rows.length === 0,\n )\n ) {\n hints.push(\n `Nothing in the entities read matched ${search ? `--search \"${search}\"` : `--id ${ids?.join(\",\")}`}. ` +\n \"That is not proof the container lacks it: drop the filter or widen --entities before concluding.\",\n );\n }\n if (data.installedContainerMismatch) {\n hints.push(data.installedContainerMismatch);\n }\n writeJsonEnvelope({ ok: true, data, hints });\n } catch (err) {\n handleError(err);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,qBAAqB;AAQ9B,eAAe;AAAA,EACb,SAAS;AAAA,EACT,aACE;AAAA,EACF,MAAM,EAAE,WAAW,cAAc;AACnC,CAAC;AAED,eAAe;AAAA,EACb,SAAS;AAAA,EACT,aACE;AAAA,EACF,MAAM;AAAA,IACJ,WAAW;AAAA,MACT,MAAM;AAAA,MACN,aAAa;AAAA,MACb,UAAU;AAAA,IACZ;AAAA,IACA,WAAW,EAAE,MAAM,UAAU,aAAa,oDAAoD,UAAU,MAAM;AAAA,IAC9G,UAAU;AAAA,MACR,MAAM;AAAA,MACN,aAAa;AAAA,MACb,UAAU;AAAA,IACZ;AAAA,IACA,MAAM,EAAE,MAAM,WAAW,aAAa,sDAAsD,UAAU,MAAM;AAAA,IAC5G,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,aACE;AAAA,MACF,UAAU;AAAA,IACZ;AAAA,IACA,IAAI,EAAE,MAAM,UAAU,aAAa,wDAAwD,UAAU,MAAM;AAAA,EAC7G;AACF,CAAC;AAQM,SAAS,gBACd,YACA,wBAA4F,CAAC,GACnF;AACV,QAAM,QAAQ,uBAAuB;AAAA,IACnC,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,MAAM;AAAA,IACN,WAAW,WAAW,IAAI,CAAC,eAAe;AAAA,MACxC,IAAI,UAAU;AAAA,MACd,OAAO,GAAG,UAAU,QAAQ,SAAM,UAAU,IAAI;AAAA,IAClD,EAAE;AAAA,EACJ,CAAC;AACD,MAAI,sBAAsB,SAAS,GAAG;AACpC,UAAM,CAAC,SAAS,IAAI;AACpB,QAAI,W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AAA,IACjB;AAAA,EACF;AACF,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/commands/tag-manager/read.ts"],"sourcesContent":["import type { TagManagerContainer, TagManagerContainersResponse, TagManagerReadResponse } from \"@baker/api/tag-manager\";\nimport { defineCommand } from \"citty\";\nimport { AVAILABLE_ARG, writeAvailableAccounts } from \"../../available-accounts.ts\";\nimport { apiGet, apiPost } from \"../../client.ts\";\nimport { connectedResourceHints } from \"../../connected-resources.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { handleError, TAG_MANAGER_TIMEOUT_MS } from \"./shared.ts\";\n\nregisterSchema({\n command: \"tagManager.containers\",\n description:\n \"List the Google Tag Manager containers this company selected. There can be several, and Baker may read and change all of them. Start here to confirm which containers you are managing.\",\n args: { available: AVAILABLE_ARG },\n});\n\nregisterSchema({\n command: \"tagManager.read\",\n description:\n \"Read what is currently inside a Tag Manager container: tags, triggers, variables, folders and enabled built-in variables. Start here before proposing any change, so you edit what exists instead of duplicating it. Pass --container when the company connected more than one. Compact by default: each tag names the triggers it fires on (firesOn, built-ins included), and data.measures maps each id the tags send to (meta:<pixel>, googleAnalytics:G-…, googleAds:AW-…) to the tag ids sending there. Narrow with --search <text> (name, type, Custom HTML, trigger conditions) or --id <ids>, which also gives Custom HTML tags their script URLs (src); pass --full for raw Tag Manager objects of what is left, trigger ids included.\",\n args: {\n container: {\n type: \"string\",\n description: \"Numeric container id (optional only when one container is connected)\",\n required: false,\n },\n workspace: { type: \"string\", description: \"Workspace id (defaults to the default workspace)\", required: false },\n entities: {\n type: \"string\",\n description: \"Comma-separated subset: tag,trigger,variable,folder,builtInVariable\",\n required: false,\n },\n full: { type: \"boolean\", description: \"Include the raw Tag Manager object for each entity\", required: false },\n search: {\n type: \"string\",\n description:\n \"Only entities mentioning this text (case-insensitive): name, type, parameters incl. Custom HTML, trigger conditions — e.g. hubspot, go.example.com\",\n required: false,\n },\n id: { type: \"string\", description: \"Only these entity ids, comma-separated (e.g. 24,126)\", required: false },\n },\n});\n\n/**\n * A company can connect several containers. Reading the list as \"the container\"\n * is the mistake to head off here: with more than one, nothing may be read or\n * staged without naming which, because Baker refuses to guess.\n *\n */\nexport function containersHints(\n containers: TagManagerContainer[],\n unavailableContainers: NonNullable<TagManagerContainersResponse[\"unavailableContainers\"]> = [],\n): string[] {\n const hints = connectedResourceHints({\n plural: \"Tag Manager containers\",\n singular: \"Tag Manager container\",\n flag: \"--container\",\n resources: containers.map((container) => ({\n id: container.containerId,\n label: `${container.publicId} · ${container.name}`,\n })),\n });\n if (unavailableContainers.length > 0) {\n const [available] = containers;\n if (containers.length === 1 && available) {\n hints.length = 0;\n hints.push(\n `Use --container ${available.containerId} for ${available.publicId} (${available.name}); ` +\n \"another selected container cannot be opened.\",\n );\n }\n hints.push(\n `Tag Manager cannot open ${unavailableContainers.map((container) => `${container.publicId} (${container.name})`).join(\", \")}. ` +\n \"Ask the user to reconnect with a Google account that has access to these containers.\",\n );\n }\n return hints;\n}\n\nexport const containersCommand = defineCommand({\n meta: {\n name: \"containers\",\n description: `List Tag Manager containers selected by this company.\n\nStart here:\n baker tag-manager containers\n baker tag-manager containers --available # every container the login reaches, selected or not`,\n },\n args: { available: AVAILABLE_ARG },\n run: async ({ args }) => {\n if (args.available) return writeAvailableAccounts(\"google-tag-manager\", handleError);\n try {\n const data = await apiGet<TagManagerContainersResponse>(\"/api/tag-manager/containers\");\n writeJsonEnvelope({ ok: true, data, hints: containersHints(data.containers, data.unavailableContainers) });\n } catch (err) {\n handleError(err);\n }\n },\n});\n\nexport const readCommand = defineCommand({\n meta: {\n name: \"read\",\n description: `Read the current contents of the Tag Manager container — always do this before staging changes.\n\nStart here:\n baker tag-manager read\n baker tag-manager read --entities tag,trigger\n baker tag-manager read --entities tag --search hubspot # which tags load HubSpot, their script src, on which triggers\n baker tag-manager read --entities trigger --search go.example.com # triggers whose conditions name a host\n baker tag-manager read --entities tag --id 24,126 --full # those tags' raw objects (HTML, parameters)\n\nCompact tags carry firesOn (trigger names, built-ins like \"All Pages\" included); their trigger ids (built-ins included) come with --id <tag id> --full.\ndata.measures maps where the tags send (meta:<pixel id>, googleAnalytics:G-…, googleAds:AW-…, hubspot:<id>) to the tag ids sending there.`,\n },\n args: {\n container: { type: \"string\", description: \"Numeric container id\", required: false },\n workspace: { type: \"string\", description: \"Workspace id\", required: false },\n entities: { type: \"string\", description: \"Comma-separated entity subset\", required: false },\n full: { type: \"boolean\", description: \"Include raw Tag Manager objects\", required: false },\n search: {\n type: \"string\",\n description: \"Only entities mentioning this text: name, type, parameters, Custom HTML, trigger conditions\",\n required: false,\n },\n id: { type: \"string\", description: \"Only these entity ids, comma-separated\", required: false },\n },\n run: async ({ args }) => {\n const list = (value: unknown) =>\n typeof value === \"string\" && value.length > 0\n ? value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n : undefined;\n const entities = list(args.entities);\n const ids = list(args.id);\n const search = typeof args.search === \"string\" && args.search.length > 0 ? args.search : undefined;\n try {\n const data = await apiPost<TagManagerReadResponse>(\n \"/api/tag-manager/read\",\n { containerId: args.container, workspaceId: args.workspace, entities, full: args.full === true, ids, search },\n { timeoutMs: TAG_MANAGER_TIMEOUT_MS },\n );\n // One line: the container's name and public id are already in data.container, and a\n // compact tag names its triggers without their ids, so this says where the ids are.\n const hints: string[] = [\n `Stage changes with --container ${data.container.containerId}. Name a trigger or variable by its numeric id ` +\n \"(--entities trigger,variable) or {{Name}}, one staged in this chat by its gtm_temp_* ref.\",\n ];\n if (data.publicationWarning) hints.push(data.publicationWarning);\n if (\n (ids || search) &&\n [data.tags, data.triggers, data.variables, data.folders, data.builtInVariables].every(\n (rows) => rows.length === 0,\n )\n ) {\n hints.push(\n `Nothing in the entities read matched ${search ? `--search \"${search}\"` : `--id ${ids?.join(\",\")}`}. ` +\n \"That is not proof the container lacks it: drop the filter or widen --entities before concluding.\",\n );\n }\n if (data.installedContainerMismatch) {\n hints.push(data.installedContainerMismatch);\n }\n writeJsonEnvelope({ ok: true, data, hints });\n } catch (err) {\n handleError(err);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,qBAAqB;AAQ9B,eAAe;AAAA,EACb,SAAS;AAAA,EACT,aACE;AAAA,EACF,MAAM,EAAE,WAAW,cAAc;AACnC,CAAC;AAED,eAAe;AAAA,EACb,SAAS;AAAA,EACT,aACE;AAAA,EACF,MAAM;AAAA,IACJ,WAAW;AAAA,MACT,MAAM;AAAA,MACN,aAAa;AAAA,MACb,UAAU;AAAA,IACZ;AAAA,IACA,WAAW,EAAE,MAAM,UAAU,aAAa,oDAAoD,UAAU,MAAM;AAAA,IAC9G,UAAU;AAAA,MACR,MAAM;AAAA,MACN,aAAa;AAAA,MACb,UAAU;AAAA,IACZ;AAAA,IACA,MAAM,EAAE,MAAM,WAAW,aAAa,sDAAsD,UAAU,MAAM;AAAA,IAC5G,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,aACE;AAAA,MACF,UAAU;AAAA,IACZ;AAAA,IACA,IAAI,EAAE,MAAM,UAAU,aAAa,wDAAwD,UAAU,MAAM;AAAA,EAC7G;AACF,CAAC;AAQM,SAAS,gBACd,YACA,wBAA4F,CAAC,GACnF;AACV,QAAM,QAAQ,uBAAuB;AAAA,IACnC,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,MAAM;AAAA,IACN,WAAW,WAAW,IAAI,CAAC,eAAe;AAAA,MACxC,IAAI,UAAU;AAAA,MACd,OAAO,GAAG,UAAU,QAAQ,SAAM,UAAU,IAAI;AAAA,IAClD,EAAE;AAAA,EACJ,CAAC;AACD,MAAI,sBAAsB,SAAS,GAAG;AACpC,UAAM,CAAC,SAAS,IAAI;AACpB,QAAI,WAAW,WAAW,KAAK,WAAW;AACxC,YAAM,SAAS;AACf,YAAM;AAAA,QACJ,mBAAmB,UAAU,WAAW,QAAQ,UAAU,QAAQ,KAAK,UAAU,IAAI;AAAA,M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E.js";
12
+ } from "./chunk-FRWCTFTP.js";
13
+ import "./chunk-LVLAFUXQ.js";
13
14
  import "./chunk-MTMWOUKN.js";
14
15
  import "./chunk-S7J2JP3U.js";
15
16
  import "./chunk-UKENQSZ2.js";
@@ -409,4 +410,4 @@ export {
409
410
  searchTermsHints,
410
411
  searchTermsRequest
411
412
  };
412
- //# sourceMappingURL=search-terms-WKE47TW5.js.map
413
+ //# sourceMappingURL=search-terms-SWRRTKBV.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../api/src/ads-google/search-terms.ts","../src/commands/ads/google/search-terms.ts"],"sourcesContent":["/**\n * Search terms as a negative-keyword decision needs them, answered in one read: `baker ads google\n * search-terms` (where the money went, per term or per word, and which terms a negative already\n * blocks) and `baker ads google negative-keywords check` (what a candidate negative would block).\n *\n * The backend reads the account live (`convex/ads/google/searchTerms.ts`) with the queries below,\n * every page of them, and answers the compact table built here; the raw rows never leave it. Which\n * negative blocks what follows Google's negative matching (`./negative-match`), with the negatives\n * that actually apply to each place a term spent: its campaign's, its ad group's, every shared list\n * attached to its campaign, and the account's own negative lists.\n */\nimport { z } from \"zod\";\nimport { NUMERIC_ID_REGEX } from \"./limits\";\nimport { isContiguousRun, matchTokens, negativeBlocks, negativeCovers } from \"./negative-match\";\nimport { expandPreset, getPreset, isValidDateRange, type PresetDefinition } from \"./presets\";\n\nconst customerId = z.string().regex(NUMERIC_ID_REGEX, \"customerId must be the bare numeric customer id\");\nconst scopeFields = {\n customerId,\n managerId: z.string().optional(),\n dateRange: z\n .string()\n .default(\"LAST_30_DAYS\")\n .refine(\n isValidDateRange,\n \"dateRange must be a GAQL literal (LAST_30_DAYS) or BETWEEN 'YYYY-MM-DD' AND 'YYYY-MM-DD'\",\n ),\n campaignIds: z.array(z.string().regex(NUMERIC_ID_REGEX, \"a campaign id is digits only\")).min(1).max(100).optional(),\n};\n\nexport const SEARCH_TERM_GROUPINGS = [\"term\", \"ngram\"] as const;\nexport const SEARCH_TERM_COVERAGE = [\"all\", \"unblocked\", \"blocked\"] as const;\nexport const NEGATIVE_MATCH_TYPES = [\"BROAD\", \"PHRASE\", \"EXACT\"] as const;\n\nexport const googleSearchTermsRequestSchema = z.object({\n ...scopeFields,\n groupBy: z.enum(SEARCH_TERM_GROUPINGS).default(\"term\"),\n /** Words per n-gram when grouping by ngram. */\n ngram: z.number().int().min(1).max(4).default(1),\n /** Split conversions by conversion action, secondary actions included. */\n byConversionAction: z.boolean().default(false),\n coverage: z.enum(SEARCH_TERM_COVERAGE).default(\"all\"),\n /** Only rows with no conversions: the waste. */\n zeroConversions: z.boolean().default(false),\n /** Only rows with conversions: the converters, low-spend ones included. */\n converting: z.boolean().default(false),\n minCost: z.number().min(0).default(0),\n /** Only search terms containing one of these words or phrases; `matching` totals them. */\n contains: z.array(z.string().trim().min(1).max(80)).min(1).max(20).optional(),\n limit: z.number().int().min(1).max(500).default(30),\n /** Term rows: every campaign and ad group each term spent in (places). */\n full: z.boolean().default(false),\n});\nexport type GoogleSearchTermsRequest = z.input<typeof googleSearchTermsRequestSchema>;\n\nexport const googleNegativeCheckRequestSchema = z.object({\n ...scopeFields,\n negatives: z\n .array(z.object({ text: z.string().trim().min(1).max(80), matchType: z.enum(NEGATIVE_MATCH_TYPES) }))\n .min(1)\n .max(200),\n /** Every converting term and keyword it would block, and the coverage per campaign and ad group. */\n full: z.boolean().default(false),\n});\nexport type GoogleNegativeCheckRequest = z.input<typeof googleNegativeCheckRequestSchema>;\n\nconst NEGATIVE_LEVELS = [\"campaign\", \"ad_group\", \"list\", \"account_list\"] as const;\n\n/** A live negative and where it applies from. */\nconst negativeSourceSchema = z.object({\n text: z.string(),\n matchType: z.string(),\n /** `list`: a shared list attached to the campaign; `account_list`: the account's own list, on every campaign. */\n level: z.enum(NEGATIVE_LEVELS),\n /** The shared list's name, for the list levels. */\n list: z.string().optional(),\n});\nexport type NegativeSource = z.infer<typeof negativeSourceSchema>;\n\n/** Conversions per conversion action, the name a value: Convex refuses an accented field name. */\nconst actionCountsSchema = z.array(z.object({ action: z.string(), conversions: z.number() }));\n\n/** Where a term spent: one campaign and ad group, its own numbers, and what stops it there. */\nconst searchTermPlaceSchema = z.object({\n campaignId: z.string(),\n adGroupId: z.string(),\n cost: z.number(),\n clicks: z.number(),\n conversions: z.number(),\n blockedBy: negativeSourceSchema.optional(),\n});\nexport type SearchTermPlace = z.infer<typeof searchTermPlaceSchema>;\n\nconst searchTermWasteRowSchema = z.object({\n /** The search term, or the n-gram. */\n text: z.string(),\n /** N-gram rows: how many search terms hold it. */\n terms: z.number().optional(),\n cost: z.number(),\n clicks: z.number(),\n impressions: z.number(),\n conversions: z.number(),\n /** Every conversion action that counted one, secondary included (all conversions). */\n conversionsByAction: actionCountsSchema.optional(),\n campaigns: z.number(),\n /**\n * The campaigns it spent in: where a negative for it is staged. Term rows always; n-gram rows only\n * with `full`, because a word spans most campaigns and the ids alone took half the table's tokens.\n */\n campaignIds: z.array(z.string()).optional(),\n /**\n * Term rows: of the campaign and ad group places it spent, how many a live negative now blocks.\n * N-gram rows: of the search terms holding it, how many are blocked everywhere they spent.\n */\n blocked: z.enum([\"none\", \"some\", \"all\"]),\n /** Term rows: the first live negative that blocks it. */\n blockedBy: negativeSourceSchema.optional(),\n /** Term rows: every place it spent, with what blocks it there. */\n places: z.array(searchTermPlaceSchema).optional(),\n});\nexport type SearchTermWasteRow = z.infer<typeof searchTermWasteRowSchema>;\n\nconst metricTotalsSchema = z.object({\n searchTerms: z.number(),\n cost: z.number(),\n clicks: z.number(),\n conversions: z.number(),\n});\n\nexport const googleSearchTermsResponseSchema = z.object({\n dateRange: z.string(),\n groupBy: z.enum(SEARCH_TERM_GROUPINGS),\n /** Every search term in the window, before any filter. */\n totals: metricTotalsSchema.extend({ zeroConversionCost: z.number() }),\n /** With `contains`: the search terms holding one of the words, totalled across their ad groups. */\n matching: metricTotalsSchema.optional(),\n /** Rows matching the filters; `rows` is the first `limit`, by cost. */\n totalRows: z.number(),\n rows: z.array(searchTermWasteRowSchema),\n});\nexport type GoogleSearchTermsResponse = z.infer<typeof googleSearchTermsResponseSchema>;\n\nconst negativeCheckRowSchema = z.object({\n text: z.string(),\n matchType: z.string(),\n /** Campaigns checked: those named, else every one with a live keyword or a search term in the window. */\n campaigns: z.number(),\n /**\n * Campaigns where live negatives already block every query it would: one at the campaign or an\n * attached list, or one in each of the campaign's ad groups.\n */\n coveredIn: z.number(),\n coveredBy: negativeSourceSchema.optional(),\n /** The campaigns checked where it is not covered: where staging it would change something. */\n uncoveredCampaignIds: z.array(z.string()),\n /** Search terms of the window it would newly block, counting only the places they spent unblocked. */\n wouldBlock: z.object({\n terms: z.number(),\n cost: z.number(),\n clicks: z.number(),\n conversions: z.number(),\n /** How many of those terms converted there. */\n convertingTerms: z.number(),\n }),\n /** Those that converted: the cost of adding it. The first five, every one with `full`. */\n convertingTerms: z.array(z.object({ text: z.string(), conversions: z.number() })),\n /** Serving keywords in those campaigns it would stop. */\n blocksKeywords: z.number(),\n /** The first five of them, every one with `full`. */\n keywords: z.array(\n z.object({ text: z.string(), matchType: z.string(), campaignId: z.string(), adGroupId: z.string() }),\n ),\n /** With `full`: per campaign checked, what covers it there, and in each ad group it is seen in. */\n coverage: z\n .array(\n z.object({\n campaignId: z.string(),\n coveredBy: negativeSourceSchema.optional(),\n adGroups: z.array(z.object({ adGroupId: z.string(), coveredBy: negativeSourceSchema.optional() })),\n }),\n )\n .optional(),\n});\nexport type NegativeCheckRow = z.infer<typeof negativeCheckRowSchema>;\n\nexport const googleNegativeCheckResponseSchema = z.object({\n dateRange: z.string(),\n rows: z.array(negativeCheckRowSchema),\n});\nexport type GoogleNegativeCheckResponse = z.infer<typeof googleNegativeCheckResponseSchema>;\n\n// --- the reads ---\n\nconst TERMS: PresetDefinition = {\n name: \"search-term-costs\",\n description: \"\",\n gaqlTemplate:\n \"SELECT campaign.id, ad_group.id, search_term_view.search_term, metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions FROM search_term_view WHERE segments.date DURING {dateRange} AND campaign.status != 'REMOVED'\",\n defaultDateRange: \"LAST_30_DAYS\",\n defaultLimit: 0,\n};\n\n// Conversion segments only select with conversion metrics, so the split by action is its own read.\nconst TERM_ACTIONS: PresetDefinition = {\n name: \"search-term-actions\",\n description: \"\",\n gaqlTemplate:\n \"SELECT campaign.id, ad_group.id, search_term_view.search_term, segments.conversion_action_name, metrics.all_conversions FROM search_term_view WHERE segments.date DURING {dateRange} AND metrics.all_conversions > 0 AND campaign.status != 'REMOVED'\",\n defaultDateRange: \"LAST_30_DAYS\",\n defaultLimit: 0,\n};\n\n// Every negative list's terms, the account's own included: an account-level list never attaches to a campaign.\nconst LISTS: PresetDefinition = {\n name: \"negative-list-terms\",\n description: \"\",\n gaqlTemplate:\n \"SELECT shared_set.id, shared_set.name, shared_set.type, shared_criterion.resource_name, shared_criterion.keyword.text, shared_criterion.keyword.match_type FROM shared_criterion WHERE shared_set.type IN ('NEGATIVE_KEYWORDS', 'ACCOUNT_LEVEL_NEGATIVE_KEYWORDS') AND shared_set.status = 'ENABLED'\",\n defaultDateRange: \"ALL_TIME\",\n defaultLimit: 0,\n};\n\n// The lists applied to the whole account: they block on every campaign.\nconst ACCOUNT_LISTS: PresetDefinition = {\n name: \"account-negative-lists\",\n description: \"\",\n gaqlTemplate:\n \"SELECT customer_negative_criterion.resource_name, customer_negative_criterion.negative_keyword_list.shared_set FROM customer_negative_criterion WHERE customer_negative_criterion.type = 'NEGATIVE_KEYWORD_LIST'\",\n defaultDateRange: \"ALL_TIME\",\n defaultLimit: 0,\n};\n\nexport type SearchTermRead =\n | \"terms\"\n | \"termActions\"\n | \"negatives\"\n | \"lists\"\n | \"attachments\"\n | \"accountLists\"\n | \"keywords\";\nexport type SearchTermRows = Partial<Record<SearchTermRead, Array<Record<string, unknown>>>>;\n\n/** One GAQL statement the backend reads to its last page, and the rows it feeds. */\nexport interface SearchTermQuery {\n read: SearchTermRead;\n /** The negative-keywords level the statement reads; its rows carry it as `level`. */\n level?: string;\n query: string;\n}\n\nfunction expanded(\n read: SearchTermRead,\n preset: PresetDefinition | undefined,\n dateRange: string,\n campaignIds?: string[],\n) {\n if (!preset) throw new Error(`No preset for ${read}`);\n const { query, levels, error } = expandPreset(preset, { dateRange, campaignIds });\n if (error) throw new Error(error);\n return levels ? levels.map((part) => ({ read, level: part.level, query: part.query })) : [{ read, query }];\n}\n\n/** What spent and what serves: the terms (and their actions) and, for a check, the serving keywords. */\nexport function searchTermQueries(\n request: { dateRange: string; campaignIds?: string[]; byConversionAction?: boolean },\n purpose: \"terms\" | \"check\",\n): SearchTermQuery[] {\n const { dateRange, campaignIds } = request;\n return [\n ...expanded(\"terms\", TERMS, dateRange, campaignIds),\n ...(purpose === \"terms\" && request.byConversionAction\n ? expanded(\"termActions\", TERM_ACTIONS, dateRange, campaignIds)\n : []),\n ...(purpose === \"check\" ? keywordQueries(dateRange, campaignIds) : []),\n ];\n}\n\n/** The positive keywords of those campaigns (every campaign without), each row its campaign and ad group. */\nexport function keywordQueries(dateRange: string, campaignIds?: string[]): SearchTermQuery[] {\n return expanded(\"keywords\", getPreset(\"positive-keywords\"), dateRange, campaignIds);\n}\n\n/** Campaigns per `campaign.id IN (…)`: an account-wide negatives read took 137 pages (BAKER-2476). */\nconst CAMPAIGNS_PER_READ = 100;\n\n/** The campaigns the rows spent or serve in: the only ones whose negatives the answer needs. */\nexport function campaignsOf(rows: SearchTermRows): string[] {\n return [...new Set([...(rows.terms ?? []), ...(rows.keywords ?? [])].map((row) => text(row[\"campaign.id\"])))]\n .filter(Boolean)\n .sort();\n}\n\n/** The negatives in force on those campaigns: their own, their ad groups', the shared lists attached to them and the account's. */\nexport function negativeQueries(dateRange: string, campaignIds: string[]): SearchTermQuery[] {\n if (campaignIds.length === 0) return [];\n const chunks: string[][] = [];\n for (let i = 0; i < campaignIds.length; i += CAMPAIGNS_PER_READ)\n chunks.push(campaignIds.slice(i, i + CAMPAIGNS_PER_READ));\n return [\n ...chunks.flatMap((ids) => expanded(\"negatives\", getPreset(\"negative-keywords\"), dateRange, ids)),\n ...chunks.flatMap((ids) => expanded(\"attachments\", getPreset(\"negative-list-attachments\"), dateRange, ids)),\n ...negativeListQueries(dateRange),\n ];\n}\n\n/** Every negative list's terms and which lists cover the whole account: the same for every campaign. */\nexport function negativeListQueries(dateRange: string): SearchTermQuery[] {\n return [...expanded(\"lists\", LISTS, dateRange), ...expanded(\"accountLists\", ACCOUNT_LISTS, dateRange)];\n}\n\n/** Every campaign each negative list is attached to, the whole account's at once. */\nexport function listAttachmentQueries(dateRange: string): SearchTermQuery[] {\n return expanded(\"attachments\", getPreset(\"negative-list-attachments\"), dateRange);\n}\n\n// --- the negatives in force ---\n\ninterface LiveNegative {\n tokens: string[];\n matchType: string;\n source: NegativeSource;\n}\n\ninterface Inventory {\n byCampaign: Map<string, LiveNegative[]>;\n byAdGroup: Map<string, LiveNegative[]>;\n byList: Map<string, LiveNegative[]>;\n attached: Map<string, string[]>;\n /** The lists applied to the whole account. */\n account: string[];\n}\n\nconst text = (value: unknown): string => (typeof value === \"string\" ? value : value == null ? \"\" : String(value));\nconst num = (value: unknown): number => {\n const n = Number(value ?? 0);\n return Number.isFinite(n) ? n : 0;\n};\n\nfunction push<V>(map: Map<string, V[]>, key: string, value: V): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\nfunction liveNegative(\n textValue: unknown,\n matchType: unknown,\n source: Omit<NegativeSource, \"text\" | \"matchType\">,\n): LiveNegative {\n const words = text(textValue);\n const type = text(matchType);\n return { tokens: matchTokens(words), matchType: type, source: { text: words, matchType: type, ...source } };\n}\n\nfunction inventoryOf(rows: SearchTermRows): Inventory {\n const inventory: Inventory = {\n byCampaign: new Map(),\n byAdGroup: new Map(),\n byList: new Map(),\n attached: new Map(),\n account: [],\n };\n for (const row of rows.negatives ?? []) {\n if (row.level === \"ad_group\") {\n const negative = liveNegative(\n row[\"ad_group_criterion.keyword.text\"],\n row[\"ad_group_criterion.keyword.match_type\"],\n { level: \"ad_group\" },\n );\n push(inventory.byAdGroup, text(row[\"ad_group.id\"]), negative);\n } else {\n const negative = liveNegative(\n row[\"campaign_criterion.keyword.text\"],\n row[\"campaign_criterion.keyword.match_type\"],\n { level: \"campaign\" },\n );\n push(inventory.byCampaign, text(row[\"campaign.id\"]), negative);\n }\n }\n for (const row of rows.lists ?? []) {\n const accountLevel = text(row[\"shared_set.type\"]) === \"ACCOUNT_LEVEL_NEGATIVE_KEYWORDS\";\n const negative = liveNegative(row[\"shared_criterion.keyword.text\"], row[\"shared_criterion.keyword.match_type\"], {\n level: accountLevel ? \"account_list\" : \"list\",\n list: text(row[\"shared_set.name\"]),\n });\n push(inventory.byList, text(row[\"shared_set.id\"]), negative);\n }\n for (const row of rows.attachments ?? [])\n push(inventory.attached, text(row[\"campaign.id\"]), text(row[\"shared_set.id\"]));\n for (const row of rows.accountLists ?? []) {\n // A resource name, `customers/<id>/sharedSets/<id>`.\n const list = /sharedSets\\/(\\d+)$/.exec(text(row[\"customer_negative_criterion.negative_keyword_list.shared_set\"]));\n if (list?.[1]) inventory.account.push(list[1]);\n }\n return inventory;\n}\n\n/** The live negatives a whole campaign answers to: its own, its attached lists' and the account's. */\nfunction campaignNegatives(inventory: Inventory, campaignId: string): LiveNegative[] {\n return [\n ...(inventory.byCampaign.get(campaignId) ?? []),\n ...[...(inventory.attached.get(campaignId) ?? []), ...inventory.account].flatMap(\n (list) => inventory.byList.get(list) ?? [],\n ),\n ];\n}\n\nconst adGroupNegatives = (inventory: Inventory, adGroupId: string) => inventory.byAdGroup.get(adGroupId) ?? [];\n\n/** The first live negative stopping a query in this campaign and ad group. */\nfunction blockerAt(inventory: Inventory, tokens: string[], campaignId: string, adGroupId: string) {\n return [...campaignNegatives(inventory, campaignId), ...adGroupNegatives(inventory, adGroupId)].find(\n (n) => n.tokens.length > 0 && negativeBlocks(n, tokens),\n )?.source;\n}\n\n/** What a keyword or negative being staged meets among the live ones, from `negativeQueries` and `keywordQueries` rows. */\nexport interface LiveNegativeChecks {\n /** The first live negative stopping a search for `query` in a campaign (and one of its ad groups). */\n blocker(query: string, campaignId: string, adGroupId?: string): NegativeSource | undefined;\n /** A live negative already blocking every search the candidate would, on a campaign (or ad group) or in a list. */\n coverer(\n candidate: { text: string; matchType: string },\n at: { campaignId: string; adGroupId?: string } | { listId: string },\n ): NegativeSource | undefined;\n /** The live keywords of a campaign (or one ad group; every campaign when none) the candidate negative would stop. */\n blockedKeywords(\n candidate: { text: string; matchType: string },\n campaignId: string | undefined,\n adGroupId?: string,\n ): Array<{ text: string; matchType: string }>;\n /** The campaigns a negative list covers: those it is attached to, or every campaign for the account's list. */\n listCampaigns(listId: string): string[] | \"every\";\n}\n\nexport function liveNegativeChecks(rows: SearchTermRows): LiveNegativeChecks {\n const inventory = inventoryOf(rows);\n const asCandidate = (c: { text: string; matchType: string }) => ({\n tokens: matchTokens(c.text),\n matchType: c.matchType,\n });\n return {\n blocker: (query, campaignId, adGroupId = \"\") => blockerAt(inventory, matchTokens(query), campaignId, adGroupId),\n coverer: (candidate, at) =>\n coverIn(\n \"listId\" in at\n ? (inventory.byList.get(at.listId) ?? [])\n : [\n ...campaignNegatives(inventory, at.campaignId),\n ...(at.adGroupId ? adGroupNegatives(inventory, at.adGroupId) : []),\n ],\n asCandidate(candidate),\n ),\n blockedKeywords: (candidate, campaignId, adGroupId) =>\n (rows.keywords ?? [])\n .filter(\n (row) =>\n (campaignId === undefined || text(row[\"campaign.id\"]) === campaignId) &&\n (adGroupId === undefined || text(row[\"ad_group.id\"]) === adGroupId) &&\n negativeBlocks(asCandidate(candidate), matchTokens(text(row[\"ad_group_criterion.keyword.text\"]))),\n )\n .map((row) => ({\n text: text(row[\"ad_group_criterion.keyword.text\"]),\n matchType: text(row[\"ad_group_criterion.keyword.match_type\"]),\n })),\n listCampaigns: (listId) =>\n inventory.account.includes(listId)\n ? \"every\"\n : [...inventory.attached].filter(([, lists]) => lists.includes(listId)).map(([campaignId]) => campaignId),\n };\n}\n\n// --- search terms, per term ---\n\ninterface Place {\n campaignId: string;\n adGroupId: string;\n cost: number;\n clicks: number;\n conversions: number;\n blockedBy?: NegativeSource;\n}\n\ninterface Term {\n text: string;\n tokens: string[];\n cost: number;\n clicks: number;\n impressions: number;\n conversions: number;\n byAction: Map<string, number>;\n places: Map<string, Place>;\n}\n\nfunction termsOf(rows: SearchTermRows, inventory: Inventory): Map<string, Term> {\n const terms = new Map<string, Term>();\n const placeFor = (row: Record<string, unknown>): { term: Term; place: Place } => {\n const tokens = matchTokens(text(row[\"search_term_view.search_term\"]));\n const key = tokens.join(\" \");\n let term = terms.get(key);\n if (!term) {\n term = {\n text: key,\n tokens,\n cost: 0,\n clicks: 0,\n impressions: 0,\n conversions: 0,\n byAction: new Map(),\n places: new Map(),\n };\n terms.set(key, term);\n }\n const campaignId = text(row[\"campaign.id\"]);\n const adGroupId = text(row[\"ad_group.id\"]);\n const placeKey = `${campaignId}|${adGroupId}`;\n let place = term.places.get(placeKey);\n if (!place) {\n place = {\n campaignId,\n adGroupId,\n cost: 0,\n clicks: 0,\n conversions: 0,\n blockedBy: blockerAt(inventory, tokens, campaignId, adGroupId),\n };\n term.places.set(placeKey, place);\n }\n return { term, place };\n };\n for (const row of rows.terms ?? []) {\n const { term, place } = placeFor(row);\n const cost = num(row[\"metrics.cost_micros\"]) / 1_000_000;\n const clicks = num(row[\"metrics.clicks\"]);\n const conversions = num(row[\"metrics.conversions\"]);\n term.cost += cost;\n term.clicks += clicks;\n term.impressions += num(row[\"metrics.impressions\"]);\n term.conversions += conversions;\n place.cost += cost;\n place.clicks += clicks;\n place.conversions += conversions;\n }\n for (const row of rows.termActions ?? []) {\n const { term } = placeFor(row);\n const action = text(row[\"segments.conversion_action_name\"]) || \"(unnamed action)\";\n term.byAction.set(action, (term.byAction.get(action) ?? 0) + num(row[\"metrics.all_conversions\"]));\n }\n return terms;\n}\n\nconst round2 = (value: number): number => Math.round(value * 100) / 100;\n\nfunction blockedState(blocked: number, of: number): SearchTermWasteRow[\"blocked\"] {\n if (blocked === 0) return \"none\";\n return blocked === of ? \"all\" : \"some\";\n}\n\nfunction actionsOf(byAction: Map<string, number>): Array<{ action: string; conversions: number }> {\n return [...byAction]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([action, n]) => ({ action, conversions: round2(n) }));\n}\n\nconst campaignIdsOf = (places: Iterable<Place>) => [...new Set([...places].map((p) => p.campaignId))].sort();\n\nfunction termRow(term: Term, byAction: boolean, full: boolean): SearchTermWasteRow {\n const places = [...term.places.values()];\n const blockedBy = places.find((p) => p.blockedBy)?.blockedBy;\n const campaignIds = campaignIdsOf(places);\n return {\n text: term.text,\n cost: round2(term.cost),\n clicks: term.clicks,\n impressions: term.impressions,\n conversions: round2(term.conversions),\n ...(byAction ? { conversionsByAction: actionsOf(term.byAction) } : {}),\n campaigns: campaignIds.length,\n campaignIds,\n blocked: blockedState(places.filter((p) => p.blockedBy).length, places.length),\n ...(blockedBy ? { blockedBy } : {}),\n ...(full\n ? {\n places: places\n .sort((a, b) => b.cost - a.cost)\n .map((p) => ({\n campaignId: p.campaignId,\n adGroupId: p.adGroupId,\n cost: round2(p.cost),\n clicks: p.clicks,\n conversions: round2(p.conversions),\n ...(p.blockedBy ? { blockedBy: p.blockedBy } : {}),\n })),\n }\n : {}),\n };\n}\n\nfunction ngramsOf(tokens: string[], n: number): Set<string> {\n const grams = new Set<string>();\n for (let i = 0; i + n <= tokens.length; i += 1) grams.add(tokens.slice(i, i + n).join(\" \"));\n return grams;\n}\n\nfunction ngramRows(terms: Term[], n: number, byAction: boolean, full: boolean): SearchTermWasteRow[] {\n const grams = new Map<string, { term: Term[]; byAction: Map<string, number> }>();\n for (const term of terms) {\n for (const gram of ngramsOf(term.tokens, n)) {\n let entry = grams.get(gram);\n if (!entry) {\n entry = { term: [], byAction: new Map() };\n grams.set(gram, entry);\n }\n entry.term.push(term);\n for (const [action, count] of term.byAction)\n entry.byAction.set(action, (entry.byAction.get(action) ?? 0) + count);\n }\n }\n return [...grams].map(([gram, entry]) => {\n const sum = (pick: (t: Term) => number) => entry.term.reduce((total, t) => total + pick(t), 0);\n const blocked = entry.term.filter((t) => [...t.places.values()].every((p) => p.blockedBy)).length;\n const campaignIds = campaignIdsOf(entry.term.flatMap((t) => [...t.places.values()]));\n return {\n text: gram,\n terms: entry.term.length,\n cost: round2(sum((t) => t.cost)),\n clicks: sum((t) => t.clicks),\n impressions: sum((t) => t.impressions),\n conversions: round2(sum((t) => t.conversions)),\n ...(byAction ? { conversionsByAction: actionsOf(entry.byAction) } : {}),\n campaigns: campaignIds.length,\n ...(full ? { campaignIds } : {}),\n blocked: blockedState(blocked, entry.term.length),\n };\n });\n}\n\nexport function searchTermsAnswer(\n request: z.output<typeof googleSearchTermsRequestSchema>,\n rows: SearchTermRows,\n): GoogleSearchTermsResponse {\n const terms = [...termsOf(rows, inventoryOf(rows)).values()];\n // Whole words, in order: `car` is not in `scar removal`.\n const words = request.contains?.map((word) => matchTokens(word));\n const matching = words ? terms.filter((t) => words.some((word) => isContiguousRun(t.tokens, word))) : terms;\n const all =\n request.groupBy === \"ngram\"\n ? ngramRows(matching, request.ngram, request.byConversionAction, request.full)\n : matching.map((term) => termRow(term, request.byConversionAction, request.full));\n const kept = all\n .filter((row) => row.cost >= request.minCost)\n .filter((row) => !request.zeroConversions || row.conversions === 0)\n .filter((row) => !request.converting || row.conversions > 0)\n .filter((row) => request.coverage === \"all\" || (request.coverage === \"blocked\") === (row.blocked === \"all\"))\n .sort((a, b) => b.cost - a.cost || a.text.localeCompare(b.text));\n const total = (pick: (t: Term) => number, of = terms) => round2(of.reduce((sum, t) => sum + pick(t), 0));\n return {\n dateRange: request.dateRange,\n groupBy: request.groupBy,\n totals: {\n searchTerms: terms.length,\n cost: total((t) => t.cost),\n clicks: total((t) => t.clicks),\n conversions: total((t) => t.conversions),\n zeroConversionCost: total((t) => (t.conversions === 0 ? t.cost : 0)),\n },\n ...(words\n ? {\n matching: {\n searchTerms: matching.length,\n cost: total((t) => t.cost, matching),\n clicks: total((t) => t.clicks, matching),\n conversions: total((t) => t.conversions, matching),\n },\n }\n : {}),\n totalRows: kept.length,\n rows: kept.slice(0, request.limit),\n };\n}\n\n// --- what a candidate negative would do ---\n\nconst CHECK_SAMPLE = 5;\n\ntype Candidate = { tokens: string[]; matchType: string };\n\nconst coverIn = (negatives: LiveNegative[], candidate: Candidate) =>\n negatives.find((n) => negativeCovers(n, candidate))?.source;\n\n/**\n * What already covers the candidate in one campaign: a negative of the campaign, an attached list or\n * the account's; else one in every ad group the campaign is seen in (by its keywords and search terms).\n */\nfunction campaignCoverage(inventory: Inventory, campaignId: string, adGroupIds: string[], candidate: Candidate) {\n const campaign = coverIn(campaignNegatives(inventory, campaignId), candidate);\n const adGroups = adGroupIds.map((adGroupId) => {\n const coveredBy = campaign ?? coverIn(adGroupNegatives(inventory, adGroupId), candidate);\n return { adGroupId, ...(coveredBy ? { coveredBy } : {}) };\n });\n const everyAdGroup = adGroups.length > 0 && adGroups.every((a) => a.coveredBy) ? adGroups[0]?.coveredBy : undefined;\n const coveredBy = campaign ?? everyAdGroup;\n return { campaignId, ...(coveredBy ? { coveredBy } : {}), adGroups };\n}\n\nexport function negativeCheckAnswer(\n request: z.output<typeof googleNegativeCheckRequestSchema>,\n rows: SearchTermRows,\n): GoogleNegativeCheckResponse {\n const inventory = inventoryOf(rows);\n const terms = [...termsOf(rows, inventory).values()];\n const keywords = (rows.keywords ?? []).map((row) => ({\n text: text(row[\"ad_group_criterion.keyword.text\"]),\n tokens: matchTokens(text(row[\"ad_group_criterion.keyword.text\"])),\n matchType: text(row[\"ad_group_criterion.keyword.match_type\"]),\n campaignId: text(row[\"campaign.id\"]),\n adGroupId: text(row[\"ad_group.id\"]),\n }));\n const seen = [\n ...keywords.map((k) => ({ campaignId: k.campaignId, adGroupId: k.adGroupId })),\n ...terms.flatMap((t) => [...t.places.values()]),\n ];\n const adGroupsOf = new Map<string, Set<string>>();\n for (const { campaignId, adGroupId } of seen) {\n const groups = adGroupsOf.get(campaignId) ?? new Set<string>();\n if (adGroupId) groups.add(adGroupId);\n adGroupsOf.set(campaignId, groups);\n }\n const campaigns = [...new Set(request.campaignIds ?? seen.map((s) => s.campaignId))].sort();\n const checked = new Set(campaigns);\n const sample = <T>(items: T[]) => (request.full ? items : items.slice(0, CHECK_SAMPLE));\n return {\n dateRange: request.dateRange,\n rows: request.negatives.map((entry) => {\n const candidate = { tokens: matchTokens(entry.text), matchType: entry.matchType };\n const coverage = campaigns.map((id) =>\n campaignCoverage(inventory, id, [...(adGroupsOf.get(id) ?? [])].sort(), candidate),\n );\n const covered = coverage.filter((c) => c.coveredBy);\n // Only the places a term spent unblocked count: where it is already stopped, nothing changes.\n const newlyBlocked = terms.flatMap((t) => {\n if (!negativeBlocks(candidate, t.tokens)) return [];\n const places = [...t.places.values()].filter((p) => checked.has(p.campaignId) && !p.blockedBy);\n if (places.length === 0) return [];\n const sum = (pick: (p: Place) => number) => places.reduce((total, p) => total + pick(p), 0);\n return [\n {\n text: t.text,\n cost: sum((p) => p.cost),\n clicks: sum((p) => p.clicks),\n conversions: sum((p) => p.conversions),\n },\n ];\n });\n const converting = newlyBlocked.filter((t) => t.conversions > 0).sort((a, b) => b.conversions - a.conversions);\n const blockedKeywords = keywords.filter((k) => checked.has(k.campaignId) && negativeBlocks(candidate, k.tokens));\n const total = (pick: (t: (typeof newlyBlocked)[number]) => number) =>\n round2(newlyBlocked.reduce((sum, t) => sum + pick(t), 0));\n return {\n text: candidate.tokens.join(\" \"),\n matchType: entry.matchType,\n campaigns: campaigns.length,\n coveredIn: covered.length,\n ...(covered[0]?.coveredBy ? { coveredBy: covered[0].coveredBy } : {}),\n uncoveredCampaignIds: coverage.filter((c) => !c.coveredBy).map((c) => c.campaignId),\n wouldBlock: {\n terms: newlyBlocked.length,\n cost: total((t) => t.cost),\n clicks: total((t) => t.clicks),\n conversions: total((t) => t.conversions),\n convertingTerms: converting.length,\n },\n convertingTerms: sample(converting).map((t) => ({ text: t.text, conversions: round2(t.conversions) })),\n blocksKeywords: blockedKeywords.length,\n keywords: sample(blockedKeywords).map(({ tokens: _tokens, ...keyword }) => keyword),\n ...(request.full ? { coverage } : {}),\n };\n }),\n };\n}\n","/**\n * `baker ads google search-terms` and `negative-keywords check` — the negative-keyword questions\n * answered in one live read each: where search-term money went (per term or per word), which terms\n * a negative already blocks, and what a candidate negative would block. The backend reads every\n * page and the negatives in force and answers a compact table (`@baker/api/ads-google/search-terms`).\n */\nimport {\n type GoogleNegativeCheckRequest,\n type GoogleNegativeCheckResponse,\n type GoogleSearchTermsRequest,\n type GoogleSearchTermsResponse,\n googleNegativeCheckRequestSchema,\n googleNegativeCheckResponseSchema,\n googleSearchTermsRequestSchema,\n googleSearchTermsResponseSchema,\n} from \"@baker/api/ads-google/search-terms\";\nimport { defineCommand } from \"citty\";\nimport type { z } from \"zod\";\nimport { apiPost } from \"../../../client.ts\";\nimport { registerSchema } from \"../../../schemas.ts\";\nimport { getManagerIdForCustomer } from \"../cache.ts\";\nimport { writeJsonEnvelope } from \"../output.ts\";\nimport { exitWithServiceReadError } from \"./service-read-errors.ts\";\nimport { failWriteValidation, keywordEntries, listFlag, requireCustomerId } from \"./write-shared.ts\";\n\nconst SCOPE_ARGS = {\n \"customer-id\": { type: \"string\", description: \"Google Ads customer ID (10 digits; dashes are fine)\" },\n \"date-range\": {\n type: \"string\",\n description: \"LAST_30_DAYS (default), any GAQL DURING literal, or \\\"BETWEEN 'YYYY-MM-DD' AND 'YYYY-MM-DD'\\\"\",\n },\n \"campaign-id\": { type: \"string\", description: \"Only these campaigns, comma-separated ids\" },\n} as const;\n\nconst SEARCH_TERMS_ARGS = {\n ...SCOPE_ARGS,\n \"group-by\": { type: \"string\", description: \"term (default) | ngram — one row per word (or --ngram 2: word pair)\" },\n ngram: { type: \"string\", description: \"Words per n-gram with --group-by ngram: 1 (default) to 4\" },\n \"by-conversion-action\": {\n type: \"boolean\",\n description: \"Split conversions per conversion action (secondary ones like an MQL included)\",\n },\n unblocked: { type: \"boolean\", description: \"Only rows no live negative fully blocks: the candidates left to act on\" },\n blocked: { type: \"boolean\", description: \"Only rows a live negative already blocks everywhere they spent\" },\n \"zero-conversions\": { type: \"boolean\", description: \"Only rows with no conversions: the waste\" },\n converting: {\n type: \"boolean\",\n description: \"Only rows with conversions: the converters, low-spend ones included\",\n },\n contains: {\n type: \"string\",\n description: \"Only terms containing one of these words, comma-separated; data.matching totals them\",\n },\n \"min-cost\": { type: \"string\", description: \"Only rows that cost at least this, in the account's currency\" },\n limit: { type: \"string\", description: \"Rows, by cost (default 30, max 500); totalRows counts every match\" },\n full: {\n type: \"boolean\",\n description:\n \"Every column: impressions, per word the campaigns it spent in (campaignIds), and per term each campaign and ad group it spent in (places)\",\n },\n} as const;\n\nconst CHECK_ARGS = {\n ...SCOPE_ARGS,\n text: { type: \"string\", description: 'Candidate negatives, comma-separated, each with an optional \":MATCH_TYPE\"' },\n file: { type: \"string\", description: \"Text file with one candidate negative[:MATCH_TYPE] per line\" },\n \"match-type\": { type: \"string\", description: \"Default match type: EXACT | PHRASE | BROAD\" },\n full: {\n type: \"boolean\",\n description:\n \"Every converting term and keyword it would block (not the first 5), and coverage per campaign and ad group\",\n },\n} as const;\n\ntype ArgDefs = Record<string, { type: \"string\" | \"boolean\"; description: string }>;\n\nfunction schemaArgs(args: ArgDefs) {\n return Object.fromEntries(\n Object.entries(args).map(([name, arg]) => [\n name,\n { type: arg.type, description: arg.description, required: false },\n ]),\n );\n}\n\nregisterSchema({\n command: \"ads.google.search-terms\",\n routes: [\"POST /api/ads/google/search-terms\"],\n effect: \"read_live\",\n description:\n \"Where search-term money went, in one read: every page of the account's search terms, totalled per term (or per word with --group-by ngram), by cost, with clicks, conversions (--by-conversion-action splits them per action, secondary ones included), the campaigns it spent in (campaigns; campaignIds names them per term, per word only with --full), and whether a live negative already blocks it — blocked none | some | all and blockedBy (the negative, its match type and level: campaign, ad_group, list or account_list, with the list's name); --full adds impressions, the campaign ids per word and each campaign and ad group a term spent in (places). Start here for any search-term or negative-keyword audit: `baker ads google search-terms --customer-id 1234567890 --group-by ngram --zero-conversions`; then `--unblocked` for the terms left to act on. Never pull `--preset search-terms --all` to total it yourself.\",\n args: schemaArgs(SEARCH_TERMS_ARGS),\n});\n\nregisterSchema({\n command: \"ads.google.negative-keywords.check\",\n routes: [\"POST /api/ads/google/negative-keywords/check\"],\n effect: \"read_live\",\n description:\n 'Before staging negatives: per candidate, the live negative that already covers it (coveredBy, coveredIn campaigns), the search terms of the window it would newly block (wouldBlock: terms, cost, clicks, conversions; convertingTerms names those that converted) and the serving keywords it would silence (blocksKeywords, keywords). Google\\'s negative matching, with campaign, ad-group, attached shared-list and account-list negatives. Start here: `baker ads google negative-keywords check --customer-id 1234567890 --campaign-id 123 --text \"free,jobs:PHRASE\" --match-type BROAD`. Covered means a live negative blocks every query the candidate would, by both match types; uncoveredCampaignIds names where staging it changes something, and --full gives coverage per campaign and ad group. Stage only where it is uncovered, with no convertingTerms and no keywords.',\n args: schemaArgs(CHECK_ARGS),\n});\n\nasync function read<S extends z.ZodTypeAny>(path: string, schema: S, request: Record<string, unknown>) {\n const customerId = String(request.customerId);\n const managerId = getManagerIdForCustomer(customerId);\n const { data } = await apiPost<{ ok: true; data: unknown }>(path, {\n ...request,\n ...(managerId ? { managerId } : {}),\n });\n return schema.parse(data) as z.output<S>;\n}\n\nfunction parsed<S extends z.ZodTypeAny>(schema: S, body: Record<string, unknown>): z.input<S> {\n const result = schema.safeParse(body);\n if (!result.success) {\n const issue = result.error.issues[0];\n failWriteValidation(issue ? `${issue.path.join(\".\") || \"request\"}: ${issue.message}` : \"Invalid flags\");\n }\n return body as z.input<S>;\n}\n\nfunction number(value: unknown): number | undefined {\n return typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : undefined;\n}\n\nfunction scope(args: Record<string, unknown>) {\n return {\n customerId: requireCustomerId(args),\n ...(typeof args[\"date-range\"] === \"string\" ? { dateRange: args[\"date-range\"] } : {}),\n ...(listFlag(args[\"campaign-id\"]) ? { campaignIds: listFlag(args[\"campaign-id\"]) } : {}),\n };\n}\n\n/** Boolean flags sent as `true` when passed, and their request field. */\nconst SEARCH_TERMS_SWITCHES = [\n [\"by-conversion-action\", \"byConversionAction\"],\n [\"zero-conversions\", \"zeroConversions\"],\n [\"converting\", \"converting\"],\n [\"full\", \"full\"],\n] as const;\n\nexport function searchTermsRequest(args: Record<string, unknown>): GoogleSearchTermsRequest {\n if (args.blocked && args.unblocked) failWriteValidation(\"pass --blocked or --unblocked, not both\");\n if (args.converting && args[\"zero-conversions\"])\n failWriteValidation(\"pass --converting or --zero-conversions, not both\");\n const coverage = args.unblocked ? \"unblocked\" : args.blocked ? \"blocked\" : undefined;\n return parsed(googleSearchTermsRequestSchema, {\n ...scope(args),\n ...(typeof args[\"group-by\"] === \"string\" ? { groupBy: args[\"group-by\"] } : {}),\n ...(number(args.ngram) !== undefined ? { ngram: number(args.ngram) } : {}),\n ...Object.fromEntries(SEARCH_TERMS_SWITCHES.filter(([flag]) => args[flag]).map(([, field]) => [field, true])),\n ...(coverage ? { coverage } : {}),\n ...(number(args[\"min-cost\"]) !== undefined ? { minCost: number(args[\"min-cost\"]) } : {}),\n ...(listFlag(args.contains) ? { contains: listFlag(args.contains) } : {}),\n ...(number(args.limit) !== undefined ? { limit: number(args.limit) } : {}),\n });\n}\n\nexport function searchTermsHints(data: GoogleSearchTermsResponse, customerId: string): string[] {\n const hints: string[] = [];\n if (data.totalRows > data.rows.length)\n hints.push(\n `${data.rows.length} of ${data.totalRows} rows, by cost: raise --limit or add --min-cost to see the rest.`,\n );\n if (data.rows.some((row) => row.blocked === \"all\"))\n hints.push(\n \"blocked all = a live negative already stops it everywhere it spent (it spent before the negative existed): do not stage it again.\",\n );\n if (data.rows.some((row) => row.blocked === \"some\"))\n hints.push(\n data.groupBy === \"ngram\"\n ? \"blocked some = some of the search terms holding the word are already blocked everywhere they spent, others are not: list the ones left with `--contains <word> --unblocked` (term rows), not a negative for the whole word.\"\n : \"blocked some = a live negative stops it in some of the campaigns or ad groups it spent in, not all: `--full` lists each place (campaignId, adGroupId, its spend, blockedBy). Add the negative only where it still spends, at the level that fits — an ad-group negative may be deliberate, so never widen it to the campaign without saying why.\",\n );\n if (data.rows.length > 0)\n hints.push(\n `Before staging negatives, check what they would block: baker ads google negative-keywords check --customer-id ${customerId} --text \"<term>,<term>\" --match-type PHRASE.`,\n );\n return hints;\n}\n\nexport const searchTermsCommand = defineCommand({\n meta: {\n name: \"search-terms\",\n description: `Search-term spend per term or per word, and what a live negative already blocks. Read-only.\n\nStart here for a search-term or negative-keyword audit — one call, every page, a compact table:\n baker ads google search-terms --customer-id 1234567890 --group-by ngram --zero-conversions\n baker ads google search-terms --customer-id 1234567890 --unblocked --min-cost 10 --by-conversion-action\n baker ads google search-terms --customer-id 1234567890 --campaign-id 123 --date-range LAST_7_DAYS`,\n },\n args: SEARCH_TERMS_ARGS,\n run: async ({ args }) => {\n const request = searchTermsRequest(args);\n try {\n const data = await read(\"/api/ads/google/search-terms\", googleSearchTermsResponseSchema, request);\n const rows = args.full ? data.rows : data.rows.map(({ impressions: _i, ...row }) => row);\n writeJsonEnvelope({ ok: true, data: { ...data, rows }, hints: searchTermsHints(data, request.customerId) });\n } catch (err) {\n exitWithServiceReadError(err);\n }\n },\n});\n\nexport function negativeCheckRequest(args: Record<string, unknown>, rawArgs?: readonly string[]) {\n const negatives = keywordEntries(args, rawArgs);\n return parsed(googleNegativeCheckRequestSchema, {\n ...scope(args),\n negatives,\n ...(args.full ? { full: true } : {}),\n }) as GoogleNegativeCheckRequest;\n}\n\nexport function negativeCheckHints(data: GoogleNegativeCheckResponse): string[] {\n const hints: string[] = [];\n const covered = data.rows.filter((row) => row.coveredIn > 0 && row.coveredIn === row.campaigns);\n if (covered.length > 0)\n hints.push(\n `${covered.map((row) => `\"${row.text}\"`).join(\", \")} already blocked by a live negative in every campaign checked: do not stage again.`,\n );\n const harmful = data.rows.filter((row) => row.convertingTerms.length > 0 || row.blocksKeywords > 0);\n if (harmful.length > 0)\n hints.push(\n `${harmful.map((row) => `\"${row.text}\"`).join(\", \")} would block converting search terms or serving keywords: narrow the match type (PHRASE/EXACT) or drop it, and tell the user why.`,\n );\n const cut = data.rows.filter(\n (row) => row.convertingTerms.length < row.wouldBlock.convertingTerms || row.keywords.length < row.blocksKeywords,\n );\n if (cut.length > 0)\n hints.push(\n `${cut.map((row) => `\"${row.text}\"`).join(\", \")}: convertingTerms and keywords list the first 5; --full lists every one.`,\n );\n return hints;\n}\n\nexport const negativeCheckCommand = defineCommand({\n meta: {\n name: \"check\",\n description: `What candidate negatives would block, before staging them. Read-only.\n\nStart here:\n baker ads google negative-keywords check --customer-id 1234567890 --campaign-id 123 --text \"free,jobs:PHRASE\" --match-type BROAD\n baker ads google negative-keywords check --customer-id 1234567890 --file candidates.txt --match-type PHRASE`,\n },\n args: CHECK_ARGS,\n run: async ({ args, rawArgs }) => {\n const request = negativeCheckRequest(args, rawArgs);\n try {\n const data = await read(\"/api/ads/google/negative-keywords/check\", googleNegativeCheckResponseSchema, request);\n const hints = negativeCheckHints(data);\n writeJsonEnvelope(hints.length > 0 ? { ok: true, data, hints } : { ok: true, data });\n } catch (err) {\n exitWithServiceReadError(err);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,SAAS;AAKlB,IAAM,aAAa,EAAE,OAAO,EAAE,MAAM,kBAAkB,iDAAiD;AACvG,IAAM,cAAc;AAAA,EAClB;AAAA,EACA,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,WAAW,EACR,OAAO,EACP,QAAQ,cAAc,EACtB;AAAA,IACC;AAAA,IACA;AAAA,EACF;AAAA,EACF,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,kBAAkB,8BAA8B,CAAC,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AACpH;AAEO,IAAM,wBAAwB,C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IAAI,GAAG,EAAE,KAAK,IAAI,CAAC;AAAA,IACjD;AACF,SAAO;AACT;AAEO,IAAM,uBAAuB,cAAc;AAAA,EAChD,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA,EAKf;AAAA,EACA,MAAM;AAAA,EACN,KAAK,OAAO,EAAE,MAAM,QAAQ,MAAM;AAChC,UAAM,UAAU,qBAAqB,MAAM,OAAO;AAClD,QAAI;AACF,YAAM,OAAO,MAAM,KAAK,2CAA2C,mCAAmC,OAAO;AAC7G,YAAM,QAAQ,mBAAmB,IAAI;AACrC,wBAAkB,MAAM,SAAS,IAAI,EAAE,IAAI,MAAM,MAAM,MAAM,IAAI,EAAE,IAAI,MAAM,KAAK,CAAC;AAAA,IACrF,SAAS,KAAK;AACZ,+BAAyB,GAAG;AAAA,IAC9B;AAAA,EACF;AACF,CAAC;","names":["customerId"]}
1
+ {"version":3,"sources":["../../api/src/ads-google/search-terms.ts","../src/commands/ads/google/search-terms.ts"],"sourcesContent":["/**\n * Search terms as a negative-keyword decision needs them, answered in one read: `baker ads google\n * search-terms` (where the money went, per term or per word, and which terms a negative already\n * blocks) and `baker ads google negative-keywords check` (what a candidate negative would block).\n *\n * The backend reads the account live (`convex/ads/google/searchTerms.ts`) with the queries below,\n * every page of them, and answers the compact table built here; the raw rows never leave it. Which\n * negative blocks what follows Google's negative matching (`./negative-match`), with the negatives\n * that actually apply to each place a term spent: its campaign's, its ad group's, every shared list\n * attached to its campaign, and the account's own negative lists.\n */\nimport { z } from \"zod\";\nimport { NUMERIC_ID_REGEX } from \"./limits\";\nimport { isContiguousRun, matchTokens, negativeBlocks, negativeCovers } from \"./negative-match\";\nimport { expandPreset, getPreset, isValidDateRange, type PresetDefinition } from \"./presets\";\n\nconst customerId = z.string().regex(NUMERIC_ID_REGEX, \"customerId must be the bare numeric customer id\");\nconst scopeFields = {\n customerId,\n managerId: z.string().optional(),\n dateRange: z\n .string()\n .default(\"LAST_30_DAYS\")\n .refine(\n isValidDateRange,\n \"dateRange must be a GAQL literal (LAST_30_DAYS) or BETWEEN 'YYYY-MM-DD' AND 'YYYY-MM-DD'\",\n ),\n campaignIds: z.array(z.string().regex(NUMERIC_ID_REGEX, \"a campaign id is digits only\")).min(1).max(100).optional(),\n};\n\nexport const SEARCH_TERM_GROUPINGS = [\"term\", \"ngram\"] as const;\nexport const SEARCH_TERM_COVERAGE = [\"all\", \"unblocked\", \"blocked\"] as const;\nexport const NEGATIVE_MATCH_TYPES = [\"BROAD\", \"PHRASE\", \"EXACT\"] as const;\n\nexport const googleSearchTermsRequestSchema = z.object({\n ...scopeFields,\n groupBy: z.enum(SEARCH_TERM_GROUPINGS).default(\"term\"),\n /** Words per n-gram when grouping by ngram. */\n ngram: z.number().int().min(1).max(4).default(1),\n /** Split conversions by conversion action, secondary actions included. */\n byConversionAction: z.boolean().default(false),\n coverage: z.enum(SEARCH_TERM_COVERAGE).default(\"all\"),\n /** Only rows with no conversions: the waste. */\n zeroConversions: z.boolean().default(false),\n /** Only rows with conversions: the converters, low-spend ones included. */\n converting: z.boolean().default(false),\n minCost: z.number().min(0).default(0),\n /** Only search terms containing one of these words or phrases; `matching` totals them. */\n contains: z.array(z.string().trim().min(1).max(80)).min(1).max(20).optional(),\n limit: z.number().int().min(1).max(500).default(30),\n /** Term rows: every campaign and ad group each term spent in (places). */\n full: z.boolean().default(false),\n});\nexport type GoogleSearchTermsRequest = z.input<typeof googleSearchTermsRequestSchema>;\n\nexport const googleNegativeCheckRequestSchema = z.object({\n ...scopeFields,\n negatives: z\n .array(z.object({ text: z.string().trim().min(1).max(80), matchType: z.enum(NEGATIVE_MATCH_TYPES) }))\n .min(1)\n .max(200),\n /** Every converting term and keyword it would block, and the coverage per campaign and ad group. */\n full: z.boolean().default(false),\n});\nexport type GoogleNegativeCheckRequest = z.input<typeof googleNegativeCheckRequestSchema>;\n\nconst NEGATIVE_LEVELS = [\"campaign\", \"ad_group\", \"list\", \"account_list\"] as const;\n\n/** A live negative and where it applies from. */\nconst negativeSourceSchema = z.object({\n text: z.string(),\n matchType: z.string(),\n /** `list`: a shared list attached to the campaign; `account_list`: the account's own list, on every campaign. */\n level: z.enum(NEGATIVE_LEVELS),\n /** The shared list's name, for the list levels. */\n list: z.string().optional(),\n});\nexport type NegativeSource = z.infer<typeof negativeSourceSchema>;\n\n/** Conversions per conversion action, the name a value: Convex refuses an accented field name. */\nconst actionCountsSchema = z.array(z.object({ action: z.string(), conversions: z.number() }));\n\n/** Where a term spent: one campaign and ad group, its own numbers, and what stops it there. */\nconst searchTermPlaceSchema = z.object({\n campaignId: z.string(),\n adGroupId: z.string(),\n cost: z.number(),\n clicks: z.number(),\n conversions: z.number(),\n blockedBy: negativeSourceSchema.optional(),\n});\nexport type SearchTermPlace = z.infer<typeof searchTermPlaceSchema>;\n\nconst searchTermWasteRowSchema = z.object({\n /** The search term, or the n-gram. */\n text: z.string(),\n /** N-gram rows: how many search terms hold it. */\n terms: z.number().optional(),\n cost: z.number(),\n clicks: z.number(),\n impressions: z.number(),\n conversions: z.number(),\n /** Every conversion action that counted one, secondary included (all conversions). */\n conversionsByAction: actionCountsSchema.optional(),\n campaigns: z.number(),\n /**\n * The campaigns it spent in: where a negative for it is staged. Term rows always; n-gram rows only\n * with `full`, because a word spans most campaigns and the ids alone took half the table's tokens.\n */\n campaignIds: z.array(z.string()).optional(),\n /**\n * Term rows: of the campaign and ad group places it spent, how many a live negative now blocks.\n * N-gram rows: of the search terms holding it, how many are blocked everywhere they spent.\n */\n blocked: z.enum([\"none\", \"some\", \"all\"]),\n /** Term rows: the first live negative that blocks it. */\n blockedBy: negativeSourceSchema.optional(),\n /** Term rows: every place it spent, with what blocks it there. */\n places: z.array(searchTermPlaceSchema).optional(),\n});\nexport type SearchTermWasteRow = z.infer<typeof searchTermWasteRowSchema>;\n\nconst metricTotalsSchema = z.object({\n searchTerms: z.number(),\n cost: z.number(),\n clicks: z.number(),\n conversions: z.number(),\n});\n\nexport const googleSearchTermsResponseSchema = z.object({\n dateRange: z.string(),\n groupBy: z.enum(SEARCH_TERM_GROUPINGS),\n /** Every search term in the window, before any filter. */\n totals: metricTotalsSchema.extend({ zeroConversionCost: z.number() }),\n /** With `contains`: the search terms holding one of the words, totalled across their ad groups. */\n matching: metricTotalsSchema.optional(),\n /** Rows matching the filters; `rows` is the first `limit`, by cost. */\n totalRows: z.number(),\n rows: z.array(searchTermWasteRowSchema),\n});\nexport type GoogleSearchTermsResponse = z.infer<typeof googleSearchTermsResponseSchema>;\n\nconst negativeCheckRowSchema = z.object({\n text: z.string(),\n matchType: z.string(),\n /** Campaigns checked: those named, else every one with a live keyword or a search term in the window. */\n campaigns: z.number(),\n /**\n * Campaigns where live negatives already block every query it would: one at the campaign or an\n * attached list, or one in each of the campaign's ad groups.\n */\n coveredIn: z.number(),\n coveredBy: negativeSourceSchema.optional(),\n /** The campaigns checked where it is not covered: where staging it would change something. */\n uncoveredCampaignIds: z.array(z.string()),\n /** Search terms of the window it would newly block, counting only the places they spent unblocked. */\n wouldBlock: z.object({\n terms: z.number(),\n cost: z.number(),\n clicks: z.number(),\n conversions: z.number(),\n /** How many of those terms converted there. */\n convertingTerms: z.number(),\n }),\n /** Those that converted: the cost of adding it. The first five, every one with `full`. */\n convertingTerms: z.array(z.object({ text: z.string(), conversions: z.number() })),\n /** Serving keywords in those campaigns it would stop. */\n blocksKeywords: z.number(),\n /** The first five of them, every one with `full`. */\n keywords: z.array(\n z.object({ text: z.string(), matchType: z.string(), campaignId: z.string(), adGroupId: z.string() }),\n ),\n /** With `full`: per campaign checked, what covers it there, and in each ad group it is seen in. */\n coverage: z\n .array(\n z.object({\n campaignId: z.string(),\n coveredBy: negativeSourceSchema.optional(),\n adGroups: z.array(z.object({ adGroupId: z.string(), coveredBy: negativeSourceSchema.optional() })),\n }),\n )\n .optional(),\n});\nexport type NegativeCheckRow = z.infer<typeof negativeCheckRowSchema>;\n\nexport const googleNegativeCheckResponseSchema = z.object({\n dateRange: z.string(),\n rows: z.array(negativeCheckRowSchema),\n});\nexport type GoogleNegativeCheckResponse = z.infer<typeof googleNegativeCheckResponseSchema>;\n\n// --- the reads ---\n\nconst TERMS: PresetDefinition = {\n name: \"search-term-costs\",\n description: \"\",\n gaqlTemplate:\n \"SELECT campaign.id, ad_group.id, search_term_view.search_term, metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions FROM search_term_view WHERE segments.date DURING {dateRange} AND campaign.status != 'REMOVED'\",\n defaultDateRange: \"LAST_30_DAYS\",\n defaultLimit: 0,\n};\n\n// Conversion segments only select with conversion metrics, so the split by action is its own read.\nconst TERM_ACTIONS: PresetDefinition = {\n name: \"search-term-actions\",\n description: \"\",\n gaqlTemplate:\n \"SELECT campaign.id, ad_group.id, search_term_view.search_term, segments.conversion_action_name, metrics.all_conversions FROM search_term_view WHERE segments.date DURING {dateRange} AND metrics.all_conversions > 0 AND campaign.status != 'REMOVED'\",\n defaultDateRange: \"LAST_30_DAYS\",\n defaultLimit: 0,\n};\n\n// Every negative list's terms, the account's own included: an account-level list never attaches to a campaign.\nconst LISTS: PresetDefinition = {\n name: \"negative-list-terms\",\n description: \"\",\n gaqlTemplate:\n \"SELECT shared_set.id, shared_set.name, shared_set.type, shared_criterion.resource_name, shared_criterion.keyword.text, shared_criterion.keyword.match_type FROM shared_criterion WHERE shared_set.type IN ('NEGATIVE_KEYWORDS', 'ACCOUNT_LEVEL_NEGATIVE_KEYWORDS') AND shared_set.status = 'ENABLED'\",\n defaultDateRange: \"ALL_TIME\",\n defaultLimit: 0,\n};\n\n// The lists applied to the whole account: they block on every campaign.\nconst ACCOUNT_LISTS: PresetDefinition = {\n name: \"account-negative-lists\",\n description: \"\",\n gaqlTemplate:\n \"SELECT customer_negative_criterion.resource_name, customer_negative_criterion.negative_keyword_list.shared_set FROM customer_negative_criterion WHERE customer_negative_criterion.type = 'NEGATIVE_KEYWORD_LIST'\",\n defaultDateRange: \"ALL_TIME\",\n defaultLimit: 0,\n};\n\nexport type SearchTermRead =\n | \"terms\"\n | \"termActions\"\n | \"negatives\"\n | \"lists\"\n | \"attachments\"\n | \"accountLists\"\n | \"keywords\";\nexport type SearchTermRows = Partial<Record<SearchTermRead, Array<Record<string, unknown>>>>;\n\n/** One GAQL statement the backend reads to its last page, and the rows it feeds. */\nexport interface SearchTermQuery {\n read: SearchTermRead;\n /** The negative-keywords level the statement reads; its rows carry it as `level`. */\n level?: string;\n query: string;\n}\n\nfunction expanded(\n read: SearchTermRead,\n preset: PresetDefinition | undefined,\n dateRange: string,\n campaignIds?: string[],\n) {\n if (!preset) throw new Error(`No preset for ${read}`);\n const { query, levels, error } = expandPreset(preset, { dateRange, campaignIds });\n if (error) throw new Error(error);\n return levels ? levels.map((part) => ({ read, level: part.level, query: part.query })) : [{ read, query }];\n}\n\n/** What spent and what serves: the terms (and their actions) and, for a check, the serving keywords. */\nexport function searchTermQueries(\n request: { dateRange: string; campaignIds?: string[]; byConversionAction?: boolean },\n purpose: \"terms\" | \"check\",\n): SearchTermQuery[] {\n const { dateRange, campaignIds } = request;\n return [\n ...expanded(\"terms\", TERMS, dateRange, campaignIds),\n ...(purpose === \"terms\" && request.byConversionAction\n ? expanded(\"termActions\", TERM_ACTIONS, dateRange, campaignIds)\n : []),\n ...(purpose === \"check\" ? keywordQueries(dateRange, campaignIds) : []),\n ];\n}\n\n/** The positive keywords of those campaigns (every campaign without), each row its campaign and ad group. */\nexport function keywordQueries(dateRange: string, campaignIds?: string[]): SearchTermQuery[] {\n return expanded(\"keywords\", getPreset(\"positive-keywords\"), dateRange, campaignIds);\n}\n\n/** Campaigns per `campaign.id IN (…)`: an account-wide negatives read took 137 pages (BAKER-2476). */\nconst CAMPAIGNS_PER_READ = 100;\n\n/** The campaigns the rows spent or serve in: the only ones whose negatives the answer needs. */\nexport function campaignsOf(rows: SearchTermRows): string[] {\n return [...new Set([...(rows.terms ?? []), ...(rows.keywords ?? [])].map((row) => text(row[\"campaign.id\"])))]\n .filter(Boolean)\n .sort();\n}\n\n/** The negatives in force on those campaigns: their own, their ad groups', the shared lists attached to them and the account's. */\nexport function negativeQueries(dateRange: string, campaignIds: string[]): SearchTermQuery[] {\n if (campaignIds.length === 0) return [];\n const chunks: string[][] = [];\n for (let i = 0; i < campaignIds.length; i += CAMPAIGNS_PER_READ)\n chunks.push(campaignIds.slice(i, i + CAMPAIGNS_PER_READ));\n return [\n ...chunks.flatMap((ids) => expanded(\"negatives\", getPreset(\"negative-keywords\"), dateRange, ids)),\n ...chunks.flatMap((ids) => expanded(\"attachments\", getPreset(\"negative-list-attachments\"), dateRange, ids)),\n ...negativeListQueries(dateRange),\n ];\n}\n\n/** Every negative list's terms and which lists cover the whole account: the same for every campaign. */\nexport function negativeListQueries(dateRange: string): SearchTermQuery[] {\n return [...expanded(\"lists\", LISTS, dateRange), ...expanded(\"accountLists\", ACCOUNT_LISTS, dateRange)];\n}\n\n/** Every campaign each negative list is attached to, the whole account's at once. */\nexport function listAttachmentQueries(dateRange: string): SearchTermQuery[] {\n return expanded(\"attachments\", getPreset(\"negative-list-attachments\"), dateRange);\n}\n\n// --- the negatives in force ---\n\ninterface LiveNegative {\n tokens: string[];\n matchType: string;\n source: NegativeSource;\n}\n\ninterface Inventory {\n byCampaign: Map<string, LiveNegative[]>;\n byAdGroup: Map<string, LiveNegative[]>;\n byList: Map<string, LiveNegative[]>;\n attached: Map<string, string[]>;\n /** The lists applied to the whole account. */\n account: string[];\n}\n\nconst text = (value: unknown): string => (typeof value === \"string\" ? value : value == null ? \"\" : String(value));\nconst num = (value: unknown): number => {\n const n = Number(value ?? 0);\n return Number.isFinite(n) ? n : 0;\n};\n\nfunction push<V>(map: Map<string, V[]>, key: string, value: V): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\nfunction liveNegative(\n textValue: unknown,\n matchType: unknown,\n source: Omit<NegativeSource, \"text\" | \"matchType\">,\n): LiveNegative {\n const words = text(textValue);\n const type = text(matchType);\n return { tokens: matchTokens(words), matchType: type, source: { text: words, matchType: type, ...source } };\n}\n\nfunction inventoryOf(rows: SearchTermRows): Inventory {\n const inventory: Inventory = {\n byCampaign: new Map(),\n byAdGroup: new Map(),\n byList: new Map(),\n attached: new Map(),\n account: [],\n };\n for (const row of rows.negatives ?? []) {\n if (row.level === \"ad_group\") {\n const negative = liveNegative(\n row[\"ad_group_criterion.keyword.text\"],\n row[\"ad_group_criterion.keyword.match_type\"],\n { level: \"ad_group\" },\n );\n push(inventory.byAdGroup, text(row[\"ad_group.id\"]), negative);\n } else {\n const negative = liveNegative(\n row[\"campaign_criterion.keyword.text\"],\n row[\"campaign_criterion.keyword.match_type\"],\n { level: \"campaign\" },\n );\n push(inventory.byCampaign, text(row[\"campaign.id\"]), negative);\n }\n }\n for (const row of rows.lists ?? []) {\n const accountLevel = text(row[\"shared_set.type\"]) === \"ACCOUNT_LEVEL_NEGATIVE_KEYWORDS\";\n const negative = liveNegative(row[\"shared_criterion.keyword.text\"], row[\"shared_criterion.keyword.match_type\"], {\n level: accountLevel ? \"account_list\" : \"list\",\n list: text(row[\"shared_set.name\"]),\n });\n push(inventory.byList, text(row[\"shared_set.id\"]), negative);\n }\n for (const row of rows.attachments ?? [])\n push(inventory.attached, text(row[\"campaign.id\"]), text(row[\"shared_set.id\"]));\n for (const row of rows.accountLists ?? []) {\n // A resource name, `customers/<id>/sharedSets/<id>`.\n const list = /sharedSets\\/(\\d+)$/.exec(text(row[\"customer_negative_criterion.negative_keyword_list.shared_set\"]));\n if (list?.[1]) inventory.account.push(list[1]);\n }\n return inventory;\n}\n\n/** The live negatives a whole campaign answers to: its own, its attached lists' and the account's. */\nfunction campaignNegatives(inventory: Inventory, campaignId: string): LiveNegative[] {\n return [\n ...(inventory.byCampaign.get(campaignId) ?? []),\n ...[...(inventory.attached.get(campaignId) ?? []), ...inventory.account].flatMap(\n (list) => inventory.byList.get(list) ?? [],\n ),\n ];\n}\n\nconst adGroupNegatives = (inventory: Inventory, adGroupId: string) => inventory.byAdGroup.get(adGroupId) ?? [];\n\n/** The first live negative stopping a query in this campaign and ad group. */\nfunction blockerAt(inventory: Inventory, tokens: string[], campaignId: string, adGroupId: string) {\n return [...campaignNegatives(inventory, campaignId), ...adGroupNegatives(inventory, adGroupId)].find(\n (n) => n.tokens.length > 0 && negativeBlocks(n, tokens),\n )?.source;\n}\n\n/** What a keyword or negative being staged meets among the live ones, from `negativeQueries` and `keywordQueries` rows. */\nexport interface LiveNegativeChecks {\n /** The first live negative stopping a search for `query` in a campaign (and one of its ad groups). */\n blocker(query: string, campaignId: string, adGroupId?: string): NegativeSource | undefined;\n /** A live negative already blocking every search the candidate would, on a campaign (or ad group) or in a list. */\n coverer(\n candidate: { text: string; matchType: string },\n at: { campaignId: string; adGroupId?: string } | { listId: string },\n ): NegativeSource | undefined;\n /** The live keywords of a campaign (or one ad group; every campaign when none) the candidate negative would stop. */\n blockedKeywords(\n candidate: { text: string; matchType: string },\n campaignId: string | undefined,\n adGroupId?: string,\n ): Array<{ text: string; matchType: string }>;\n /** The campaigns a negative list covers: those it is attached to, or every campaign for the account's list. */\n listCampaigns(listId: string): string[] | \"every\";\n}\n\nexport function liveNegativeChecks(rows: SearchTermRows): LiveNegativeChecks {\n const inventory = inventoryOf(rows);\n const asCandidate = (c: { text: string; matchType: string }) => ({\n tokens: matchTokens(c.text),\n matchType: c.matchType,\n });\n return {\n blocker: (query, campaignId, adGroupId = \"\") => blockerAt(inventory, matchTokens(query), campaignId, adGroupId),\n coverer: (candidate, at) =>\n coverIn(\n \"listId\" in at\n ? (inventory.byList.get(at.listId) ?? [])\n : [\n ...campaignNegatives(inventory, at.campaignId),\n ...(at.adGroupId ? adGroupNegatives(inventory, at.adGroupId) : []),\n ],\n asCandidate(candidate),\n ),\n blockedKeywords: (candidate, campaignId, adGroupId) =>\n (rows.keywords ?? [])\n .filter(\n (row) =>\n (campaignId === undefined || text(row[\"campaign.id\"]) === campaignId) &&\n (adGroupId === undefined || text(row[\"ad_group.id\"]) === adGroupId) &&\n negativeBlocks(asCandidate(candidate), matchTokens(text(row[\"ad_group_criterion.keyword.text\"]))),\n )\n .map((row) => ({\n text: text(row[\"ad_group_criterion.keyword.text\"]),\n matchType: text(row[\"ad_group_criterion.keyword.match_type\"]),\n })),\n listCampaigns: (listId) =>\n inventory.account.includes(listId)\n ? \"every\"\n : [...inventory.attached].filter(([, lists]) => lists.includes(listId)).map(([campaignId]) => campaignId),\n };\n}\n\n// --- search terms, per term ---\n\ninterface Place {\n campaignId: string;\n adGroupId: string;\n cost: number;\n clicks: number;\n conversions: number;\n blockedBy?: NegativeSource;\n}\n\ninterface Term {\n text: string;\n tokens: string[];\n cost: number;\n clicks: number;\n impressions: number;\n conversions: number;\n byAction: Map<string, number>;\n places: Map<string, Place>;\n}\n\nfunction termsOf(rows: SearchTermRows, inventory: Inventory): Map<string, Term> {\n const terms = new Map<string, Term>();\n const placeFor = (row: Record<string, unknown>): { term: Term; place: Place } => {\n const tokens = matchTokens(text(row[\"search_term_view.search_term\"]));\n const key = tokens.join(\" \");\n let term = terms.get(key);\n if (!term) {\n term = {\n text: key,\n tokens,\n cost: 0,\n clicks: 0,\n impressions: 0,\n conversions: 0,\n byAction: new Map(),\n places: new Map(),\n };\n terms.set(key, term);\n }\n const campaignId = text(row[\"campaign.id\"]);\n const adGroupId = text(row[\"ad_group.id\"]);\n const placeKey = `${campaignId}|${adGroupId}`;\n let place = term.places.get(placeKey);\n if (!place) {\n place = {\n campaignId,\n adGroupId,\n cost: 0,\n clicks: 0,\n conversions: 0,\n blockedBy: blockerAt(inventory, tokens, campaignId, adGroupId),\n };\n term.places.set(placeKey, place);\n }\n return { term, place };\n };\n for (const row of rows.terms ?? []) {\n const { term, place } = placeFor(row);\n const cost = num(row[\"metrics.cost_micros\"]) / 1_000_000;\n const clicks = num(row[\"metrics.clicks\"]);\n const conversions = num(row[\"metrics.conversions\"]);\n term.cost += cost;\n term.clicks += clicks;\n term.impressions += num(row[\"metrics.impressions\"]);\n term.conversions += conversions;\n place.cost += cost;\n place.clicks += clicks;\n place.conversions += conversions;\n }\n for (const row of rows.termActions ?? []) {\n const { term } = placeFor(row);\n const action = text(row[\"segments.conversion_action_name\"]) || \"(unnamed action)\";\n term.byAction.set(action, (term.byAction.get(action) ?? 0) + num(row[\"metrics.all_conversions\"]));\n }\n return terms;\n}\n\nconst round2 = (value: number): number => Math.round(value * 100) / 100;\n\nfunction blockedState(blocked: number, of: number): SearchTermWasteRow[\"blocked\"] {\n if (blocked === 0) return \"none\";\n return blocked === of ? \"all\" : \"some\";\n}\n\nfunction actionsOf(byAction: Map<string, number>): Array<{ action: string; conversions: number }> {\n return [...byAction]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([action, n]) => ({ action, conversions: round2(n) }));\n}\n\nconst campaignIdsOf = (places: Iterable<Place>) => [...new Set([...places].map((p) => p.campaignId))].sort();\n\nfunction termRow(term: Term, byAction: boolean, full: boolean): SearchTermWasteRow {\n const places = [...term.places.values()];\n const blockedBy = places.find((p) => p.blockedBy)?.blockedBy;\n const campaignIds = campaignIdsOf(places);\n return {\n text: term.text,\n cost: round2(term.cost),\n clicks: term.clicks,\n impressions: term.impressions,\n conversions: round2(term.conversions),\n ...(byAction ? { conversionsByAction: actionsOf(term.byAction) } : {}),\n campaigns: campaignIds.length,\n campaignIds,\n blocked: blockedState(places.filter((p) => p.blockedBy).length, places.length),\n ...(blockedBy ? { blockedBy } : {}),\n ...(full\n ? {\n places: places\n .sort((a, b) => b.cost - a.cost)\n .map((p) => ({\n campaignId: p.campaignId,\n adGroupId: p.adGroupId,\n cost: round2(p.cost),\n clicks: p.clicks,\n conversions: round2(p.conversions),\n ...(p.blockedBy ? { blockedBy: p.blockedBy } : {}),\n })),\n }\n : {}),\n };\n}\n\nfunction ngramsOf(tokens: string[], n: number): Set<string> {\n const grams = new Set<string>();\n for (let i = 0; i + n <= tokens.length; i += 1) grams.add(tokens.slice(i, i + n).join(\" \"));\n return grams;\n}\n\nfunction ngramRows(terms: Term[], n: number, byAction: boolean, full: boolean): SearchTermWasteRow[] {\n const grams = new Map<string, { term: Term[]; byAction: Map<string, number> }>();\n for (const term of terms) {\n for (const gram of ngramsOf(term.tokens, n)) {\n let entry = grams.get(gram);\n if (!entry) {\n entry = { term: [], byAction: new Map() };\n grams.set(gram, entry);\n }\n entry.term.push(term);\n for (const [action, count] of term.byAction)\n entry.byAction.set(action, (entry.byAction.get(action) ?? 0) + count);\n }\n }\n return [...grams].map(([gram, entry]) => {\n const sum = (pick: (t: Term) => number) => entry.term.reduce((total, t) => total + pick(t), 0);\n const blocked = entry.term.filter((t) => [...t.places.values()].every((p) => p.blockedBy)).length;\n const campaignIds = campaignIdsOf(entry.term.flatMap((t) => [...t.places.values()]));\n return {\n text: gram,\n terms: entry.term.length,\n cost: round2(sum((t) => t.cost)),\n clicks: sum((t) => t.clicks),\n impressions: sum((t) => t.impressions),\n conversions: round2(sum((t) => t.conversions)),\n ...(byAction ? { conversionsByAction: actionsOf(entry.byAction) } : {}),\n campaigns: campaignIds.length,\n ...(full ? { campaignIds } : {}),\n blocked: blockedState(blocked, entry.term.length),\n };\n });\n}\n\nexport function searchTermsAnswer(\n request: z.output<typeof googleSearchTermsRequestSchema>,\n rows: SearchTermRows,\n): GoogleSearchTermsResponse {\n const terms = [...termsOf(rows, inventoryOf(rows)).values()];\n // Whole words, in order: `car` is not in `scar removal`.\n const words = request.contains?.map((word) => matchTokens(word));\n const matching = words ? terms.filter((t) => words.some((word) => isContiguousRun(t.tokens, word))) : terms;\n const all =\n request.groupBy === \"ngram\"\n ? ngramRows(matching, request.ngram, request.byConversionAction, request.full)\n : matching.map((term) => termRow(term, request.byConversionAction, request.full));\n const kept = all\n .filter((row) => row.cost >= request.minCost)\n .filter((row) => !request.zeroConversions || row.conversions === 0)\n .filter((row) => !request.converting || row.conversions > 0)\n .filter((row) => request.coverage === \"all\" || (request.coverage === \"blocked\") === (row.blocked === \"all\"))\n .sort((a, b) => b.cost - a.cost || a.text.localeCompare(b.text));\n const total = (pick: (t: Term) => number, of = terms) => round2(of.reduce((sum, t) => sum + pick(t), 0));\n return {\n dateRange: request.dateRange,\n groupBy: request.groupBy,\n totals: {\n searchTerms: terms.length,\n cost: total((t) => t.cost),\n clicks: total((t) => t.clicks),\n conversions: total((t) => t.conversions),\n zeroConversionCost: total((t) => (t.conversions === 0 ? t.cost : 0)),\n },\n ...(words\n ? {\n matching: {\n searchTerms: matching.length,\n cost: total((t) => t.cost, matching),\n clicks: total((t) => t.clicks, matching),\n conversions: total((t) => t.conversions, matching),\n },\n }\n : {}),\n totalRows: kept.length,\n rows: kept.slice(0, request.limit),\n };\n}\n\n// --- what a candidate negative would do ---\n\nconst CHECK_SAMPLE = 5;\n\ntype Candidate = { tokens: string[]; matchType: string };\n\nconst coverIn = (negatives: LiveNegative[], candidate: Candidate) =>\n negatives.find((n) => negativeCovers(n, candidate))?.source;\n\n/**\n * What already covers the candidate in one campaign: a negative of the campaign, an attached list or\n * the account's; else one in every ad group the campaign is seen in (by its keywords and search terms).\n */\nfunction campaignCoverage(inventory: Inventory, campaignId: string, adGroupIds: string[], candidate: Candidate) {\n const campaign = coverIn(campaignNegatives(inventory, campaignId), candidate);\n const adGroups = adGroupIds.map((adGroupId) => {\n const coveredBy = campaign ?? coverIn(adGroupNegatives(inventory, adGroupId), candidate);\n return { adGroupId, ...(coveredBy ? { coveredBy } : {}) };\n });\n const everyAdGroup = adGroups.length > 0 && adGroups.every((a) => a.coveredBy) ? adGroups[0]?.coveredBy : undefined;\n const coveredBy = campaign ?? everyAdGroup;\n return { campaignId, ...(coveredBy ? { coveredBy } : {}), adGroups };\n}\n\nexport function negativeCheckAnswer(\n request: z.output<typeof googleNegativeCheckRequestSchema>,\n rows: SearchTermRows,\n): GoogleNegativeCheckResponse {\n const inventory = inventoryOf(rows);\n const terms = [...termsOf(rows, inventory).values()];\n const keywords = (rows.keywords ?? []).map((row) => ({\n text: text(row[\"ad_group_criterion.keyword.text\"]),\n tokens: matchTokens(text(row[\"ad_group_criterion.keyword.text\"])),\n matchType: text(row[\"ad_group_criterion.keyword.match_type\"]),\n campaignId: text(row[\"campaign.id\"]),\n adGroupId: text(row[\"ad_group.id\"]),\n }));\n const seen = [\n ...keywords.map((k) => ({ campaignId: k.campaignId, adGroupId: k.adGroupId })),\n ...terms.flatMap((t) => [...t.places.values()]),\n ];\n const adGroupsOf = new Map<string, Set<string>>();\n for (const { campaignId, adGroupId } of seen) {\n const groups = adGroupsOf.get(campaignId) ?? new Set<string>();\n if (adGroupId) groups.add(adGroupId);\n adGroupsOf.set(campaignId, groups);\n }\n const campaigns = [...new Set(request.campaignIds ?? seen.map((s) => s.campaignId))].sort();\n const checked = new Set(campaigns);\n const sample = <T>(items: T[]) => (request.full ? items : items.slice(0, CHECK_SAMPLE));\n return {\n dateRange: request.dateRange,\n rows: request.negatives.map((entry) => {\n const candidate = { tokens: matchTokens(entry.text), matchType: entry.matchType };\n const coverage = campaigns.map((id) =>\n campaignCoverage(inventory, id, [...(adGroupsOf.get(id) ?? [])].sort(), candidate),\n );\n const covered = coverage.filter((c) => c.coveredBy);\n // Only the places a term spent unblocked count: where it is already stopped, nothing changes.\n const newlyBlocked = terms.flatMap((t) => {\n if (!negativeBlocks(candidate, t.tokens)) return [];\n const places = [...t.places.values()].filter((p) => checked.has(p.campaignId) && !p.blockedBy);\n if (places.length === 0) return [];\n const sum = (pick: (p: Place) => number) => places.reduce((total, p) => total + pick(p), 0);\n return [\n {\n text: t.text,\n cost: sum((p) => p.cost),\n clicks: sum((p) => p.clicks),\n conversions: sum((p) => p.conversions),\n },\n ];\n });\n const converting = newlyBlocked.filter((t) => t.conversions > 0).sort((a, b) => b.conversions - a.conversions);\n const blockedKeywords = keywords.filter((k) => checked.has(k.campaignId) && negativeBlocks(candidate, k.tokens));\n const total = (pick: (t: (typeof newlyBlocked)[number]) => number) =>\n round2(newlyBlocked.reduce((sum, t) => sum + pick(t), 0));\n return {\n text: candidate.tokens.join(\" \"),\n matchType: entry.matchType,\n campaigns: campaigns.length,\n coveredIn: covered.length,\n ...(covered[0]?.coveredBy ? { coveredBy: covered[0].coveredBy } : {}),\n uncoveredCampaignIds: coverage.filter((c) => !c.coveredBy).map((c) => c.campaignId),\n wouldBlock: {\n terms: newlyBlocked.length,\n cost: total((t) => t.cost),\n clicks: total((t) => t.clicks),\n conversions: total((t) => t.conversions),\n convertingTerms: converting.length,\n },\n convertingTerms: sample(converting).map((t) => ({ text: t.text, conversions: round2(t.conversions) })),\n blocksKeywords: blockedKeywords.length,\n keywords: sample(blockedKeywords).map(({ tokens: _tokens, ...keyword }) => keyword),\n ...(request.full ? { coverage } : {}),\n };\n }),\n };\n}\n","/**\n * `baker ads google search-terms` and `negative-keywords check` — the negative-keyword questions\n * answered in one live read each: where search-term money went (per term or per word), which terms\n * a negative already blocks, and what a candidate negative would block. The backend reads every\n * page and the negatives in force and answers a compact table (`@baker/api/ads-google/search-terms`).\n */\nimport {\n type GoogleNegativeCheckRequest,\n type GoogleNegativeCheckResponse,\n type GoogleSearchTermsRequest,\n type GoogleSearchTermsResponse,\n googleNegativeCheckRequestSchema,\n googleNegativeCheckResponseSchema,\n googleSearchTermsRequestSchema,\n googleSearchTermsResponseSchema,\n} from \"@baker/api/ads-google/search-terms\";\nimport { defineCommand } from \"citty\";\nimport type { z } from \"zod\";\nimport { apiPost } from \"../../../client.ts\";\nimport { registerSchema } from \"../../../schemas.ts\";\nimport { getManagerIdForCustomer } from \"../cache.ts\";\nimport { writeJsonEnvelope } from \"../output.ts\";\nimport { exitWithServiceReadError } from \"./service-read-errors.ts\";\nimport { failWriteValidation, keywordEntries, listFlag, requireCustomerId } from \"./write-shared.ts\";\n\nconst SCOPE_ARGS = {\n \"customer-id\": { type: \"string\", description: \"Google Ads customer ID (10 digits; dashes are fine)\" },\n \"date-range\": {\n type: \"string\",\n description: \"LAST_30_DAYS (default), any GAQL DURING literal, or \\\"BETWEEN 'YYYY-MM-DD' AND 'YYYY-MM-DD'\\\"\",\n },\n \"campaign-id\": { type: \"string\", description: \"Only these campaigns, comma-separated ids\" },\n} as const;\n\nconst SEARCH_TERMS_ARGS = {\n ...SCOPE_ARGS,\n \"group-by\": { type: \"string\", description: \"term (default) | ngram — one row per word (or --ngram 2: word pair)\" },\n ngram: { type: \"string\", description: \"Words per n-gram with --group-by ngram: 1 (default) to 4\" },\n \"by-conversion-action\": {\n type: \"boolean\",\n description: \"Split conversions per conversion action (secondary ones like an MQL included)\",\n },\n unblocked: { type: \"boolean\", description: \"Only rows no live negative fully blocks: the candidates left to act on\" },\n blocked: { type: \"boolean\", description: \"Only rows a live negative already blocks everywhere they spent\" },\n \"zero-conversions\": { type: \"boolean\", description: \"Only rows with no conversions: the waste\" },\n converting: {\n type: \"boolean\",\n description: \"Only rows with conversions: the converters, low-spend ones included\",\n },\n contains: {\n type: \"string\",\n description: \"Only terms containing one of these words, comma-separated; data.matching totals them\",\n },\n \"min-cost\": { type: \"string\", description: \"Only rows that cost at least this, in the account's currency\" },\n limit: { type: \"string\", description: \"Rows, by cost (default 30, max 500); totalRows counts every match\" },\n full: {\n type: \"boolean\",\n description:\n \"Every column: impressions, per word the campaigns it spent in (campaignIds), and per term each campaign and ad group it spent in (places)\",\n },\n} as const;\n\nconst CHECK_ARGS = {\n ...SCOPE_ARGS,\n text: { type: \"string\", description: 'Candidate negatives, comma-separated, each with an optional \":MATCH_TYPE\"' },\n file: { type: \"string\", description: \"Text file with one candidate negative[:MATCH_TYPE] per line\" },\n \"match-type\": { type: \"string\", description: \"Default match type: EXACT | PHRASE | BROAD\" },\n full: {\n type: \"boolean\",\n description:\n \"Every converting term and keyword it would block (not the first 5), and coverage per campaign and ad group\",\n },\n} as const;\n\ntype ArgDefs = Record<string, { type: \"string\" | \"boolean\"; description: string }>;\n\nfunction schemaArgs(args: ArgDefs) {\n return Object.fromEntries(\n Object.entries(args).map(([name, arg]) => [\n name,\n { type: arg.type, description: arg.description, required: false },\n ]),\n );\n}\n\nregisterSchema({\n command: \"ads.google.search-terms\",\n routes: [\"POST /api/ads/google/search-terms\"],\n effect: \"read_live\",\n description:\n \"Where search-term money went, in one read: every page of the account's search terms, totalled per term (or per word with --group-by ngram), by cost, with clicks, conversions (--by-conversion-action splits them per action, secondary ones included), the campaigns it spent in (campaigns; campaignIds names them per term, per word only with --full), and whether a live negative already blocks it — blocked none | some | all and blockedBy (the negative, its match type and level: campaign, ad_group, list or account_list, with the list's name); --full adds impressions, the campaign ids per word and each campaign and ad group a term spent in (places). Start here for any search-term or negative-keyword audit: `baker ads google search-terms --customer-id 1234567890 --group-by ngram --zero-conversions`; then `--unblocked` for the terms left to act on. Never pull `--preset search-terms --all` to total it yourself.\",\n args: schemaArgs(SEARCH_TERMS_ARGS),\n});\n\nregisterSchema({\n command: \"ads.google.negative-keywords.check\",\n routes: [\"POST /api/ads/google/negative-keywords/check\"],\n effect: \"read_live\",\n description:\n 'Before staging negatives: per candidate, the live negative that already covers it (coveredBy, coveredIn campaigns), the search terms of the window it would newly block (wouldBlock: terms, cost, clicks, conversions; convertingTerms names those that converted) and the serving keywords it would silence (blocksKeywords, keywords). Google\\'s negative matching, with campaign, ad-group, attached shared-list and account-list negatives. Start here: `baker ads google negative-keywords check --customer-id 1234567890 --campaign-id 123 --text \"free,jobs:PHRASE\" --match-type BROAD`. Covered means a live negative blocks every query the candidate would, by both match types; uncoveredCampaignIds names where staging it changes something, and --full gives coverage per campaign and ad group. Stage only where it is uncovered, with no convertingTerms and no keywords.',\n args: schemaArgs(CHECK_ARGS),\n});\n\nasync function read<S extends z.ZodTypeAny>(path: string, schema: S, request: Record<string, unknown>) {\n const customerId = String(request.customerId);\n const managerId = getManagerIdForCustomer(customerId);\n const { data } = await apiPost<{ ok: true; data: unknown }>(path, {\n ...request,\n ...(managerId ? { managerId } : {}),\n });\n return schema.parse(data) as z.output<S>;\n}\n\nfunction parsed<S extends z.ZodTypeAny>(schema: S, body: Record<string, unknown>): z.input<S> {\n const result = schema.safeParse(body);\n if (!result.success) {\n const issue = result.error.issues[0];\n failWriteValidation(issue ? `${issue.path.join(\".\") || \"request\"}: ${issue.message}` : \"Invalid flags\");\n }\n return body as z.input<S>;\n}\n\nfunction number(value: unknown): number | undefined {\n return typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : undefined;\n}\n\nfunction scope(args: Record<string, unknown>) {\n return {\n customerId: requireCustomerId(args),\n ...(typeof args[\"date-range\"] === \"string\" ? { dateRange: args[\"date-range\"] } : {}),\n ...(listFlag(args[\"campaign-id\"]) ? { campaignIds: listFlag(args[\"campaign-id\"]) } : {}),\n };\n}\n\n/** Boolean flags sent as `true` when passed, and their request field. */\nconst SEARCH_TERMS_SWITCHES = [\n [\"by-conversion-action\", \"byConversionAction\"],\n [\"zero-conversions\", \"zeroConversions\"],\n [\"converting\", \"converting\"],\n [\"full\", \"full\"],\n] as const;\n\nexport function searchTermsRequest(args: Record<string, unknown>): GoogleSearchTermsRequest {\n if (args.blocked && args.unblocked) failWriteValidation(\"pass --blocked or --unblocked, not both\");\n if (args.converting && args[\"zero-conversions\"])\n failWriteValidation(\"pass --converting or --zero-conversions, not both\");\n const coverage = args.unblocked ? \"unblocked\" : args.blocked ? \"blocked\" : undefined;\n return parsed(googleSearchTermsRequestSchema, {\n ...scope(args),\n ...(typeof args[\"group-by\"] === \"string\" ? { groupBy: args[\"group-by\"] } : {}),\n ...(number(args.ngram) !== undefined ? { ngram: number(args.ngram) } : {}),\n ...Object.fromEntries(SEARCH_TERMS_SWITCHES.filter(([flag]) => args[flag]).map(([, field]) => [field, true])),\n ...(coverage ? { coverage } : {}),\n ...(number(args[\"min-cost\"]) !== undefined ? { minCost: number(args[\"min-cost\"]) } : {}),\n ...(listFlag(args.contains) ? { contains: listFlag(args.contains) } : {}),\n ...(number(args.limit) !== undefined ? { limit: number(args.limit) } : {}),\n });\n}\n\nexport function searchTermsHints(data: GoogleSearchTermsResponse, customerId: string): string[] {\n const hints: string[] = [];\n if (data.totalRows > data.rows.length)\n hints.push(\n `${data.rows.length} of ${data.totalRows} rows, by cost: raise --limit or add --min-cost to see the rest.`,\n );\n if (data.rows.some((row) => row.blocked === \"all\"))\n hints.push(\n \"blocked all = a live negative already stops it everywhere it spent (it spent before the negative existed): do not stage it again.\",\n );\n if (data.rows.some((row) => row.blocked === \"some\"))\n hints.push(\n data.groupBy === \"ngram\"\n ? \"blocked some = some of the search terms holding the word are already blocked everywhere they spent, others are not: list the ones left with `--contains <word> --unblocked` (term rows), not a negative for the whole word.\"\n : \"blocked some = a live negative stops it in some of the campaigns or ad groups it spent in, not all: `--full` lists each place (campaignId, adGroupId, its spend, blockedBy). Add the negative only where it still spends, at the level that fits — an ad-group negative may be deliberate, so never widen it to the campaign without saying why.\",\n );\n if (data.rows.length > 0)\n hints.push(\n `Before staging negatives, check what they would block: baker ads google negative-keywords check --customer-id ${customerId} --text \"<term>,<term>\" --match-type PHRASE.`,\n );\n return hints;\n}\n\nexport const searchTermsCommand = defineCommand({\n meta: {\n name: \"search-terms\",\n description: `Search-term spend per term or per word, and what a live negative already blocks. Read-only.\n\nStart here for a search-term or negative-keyword audit — one call, every page, a compact table:\n baker ads google search-terms --customer-id 1234567890 --group-by ngram --zero-conversions\n baker ads google search-terms --customer-id 1234567890 --unblocked --min-cost 10 --by-conversion-action\n baker ads google search-terms --customer-id 1234567890 --campaign-id 123 --date-range LAST_7_DAYS`,\n },\n args: SEARCH_TERMS_ARGS,\n run: async ({ args }) => {\n const request = searchTermsRequest(args);\n try {\n const data = await read(\"/api/ads/google/search-terms\", googleSearchTermsResponseSchema, request);\n const rows = args.full ? data.rows : data.rows.map(({ impressions: _i, ...row }) => row);\n writeJsonEnvelope({ ok: true, data: { ...data, rows }, hints: searchTermsHints(data, request.customerId) });\n } catch (err) {\n exitWithServiceReadError(err);\n }\n },\n});\n\nexport function negativeCheckRequest(args: Record<string, unknown>, rawArgs?: readonly string[]) {\n const negatives = keywordEntries(args, rawArgs);\n return parsed(googleNegativeCheckRequestSchema, {\n ...scope(args),\n negatives,\n ...(args.full ? { full: true } : {}),\n }) as GoogleNegativeCheckRequest;\n}\n\nexport function negativeCheckHints(data: GoogleNegativeCheckResponse): string[] {\n const hints: string[] = [];\n const covered = data.rows.filter((row) => row.coveredIn > 0 && row.coveredIn === row.campaigns);\n if (covered.length > 0)\n hints.push(\n `${covered.map((row) => `\"${row.text}\"`).join(\", \")} already blocked by a live negative in every campaign checked: do not stage again.`,\n );\n const harmful = data.rows.filter((row) => row.convertingTerms.length > 0 || row.blocksKeywords > 0);\n if (harmful.length > 0)\n hints.push(\n `${harmful.map((row) => `\"${row.text}\"`).join(\", \")} would block converting search terms or serving keywords: narrow the match type (PHRASE/EXACT) or drop it, and tell the user why.`,\n );\n const cut = data.rows.filter(\n (row) => row.convertingTerms.length < row.wouldBlock.convertingTerms || row.keywords.length < row.blocksKeywords,\n );\n if (cut.length > 0)\n hints.push(\n `${cut.map((row) => `\"${row.text}\"`).join(\", \")}: convertingTerms and keywords list the first 5; --full lists every one.`,\n );\n return hints;\n}\n\nexport const negativeCheckCommand = defineCommand({\n meta: {\n name: \"check\",\n description: `What candidate negatives would block, before staging them. Read-only.\n\nStart here:\n baker ads google negative-keywords check --customer-id 1234567890 --campaign-id 123 --text \"free,jobs:PHRASE\" --match-type BROAD\n baker ads google negative-keywords check --customer-id 1234567890 --file candidates.txt --match-type PHRASE`,\n },\n args: CHECK_ARGS,\n run: async ({ args, rawArgs }) => {\n const request = negativeCheckRequest(args, rawArgs);\n try {\n const data = await read(\"/api/ads/google/negative-keywords/check\", googleNegativeCheckResponseSchema, request);\n const hints = negativeCheckHints(data);\n writeJsonEnvelope(hints.length > 0 ? { ok: true, data, hints } : { ok: true, data });\n } catch (err) {\n exitWithServiceReadError(err);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,SAAS;AAKlB,IAAM,aAAa,EAAE,OAAO,EAAE,MAAM,kBAAkB,iDAAiD;AACvG,IAAM,cAAc;AAAA,EAClB;AAAA,EACA,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IAAI,GAAG,EAAE,KAAK,IAAI,CAAC;AAAA,IACrD;AACF,QAAM,MAAM,KAAK,KAAK;AAAA,IACpB,CAAC,QAAQ,IAAI,gBAAgB,SAAS,IAAI,WAAW,mBAAmB,IAAI,SAAS,SAAS,IAAI;AAAA,EACpG;AACA,MAAI,IAAI,SAAS;AACf,UAAM;AAAA,MACJ,GAAG,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,IAAI,GAAG,EAAE,KAAK,IAAI,CAAC;AAAA,IACjD;AACF,SAAO;AACT;AAEO,IAAM,uBAAuB,cAAc;AAAA,EAChD,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA,EAKf;AAAA,EACA,MAAM;AAAA,EACN,KAAK,OAAO,EAAE,MAAM,QAAQ,MAAM;AAChC,UAAM,UAAU,qBAAqB,MAAM,OAAO;AAClD,QAAI;AACF,YAAM,OAAO,MAAM,KAAK,2CAA2C,mCAAmC,OAAO;AAC7G,YAAM,QAAQ,mBAAmB,IAAI;AACrC,wBAAkB,MAAM,SAAS,IAAI,EAAE,IAAI,MAAM,MAAM,MAAM,IAAI,EAAE,IAAI,MAAM,KAAK,CAAC;AAAA,IACrF,SAAS,KAAK;AACZ,+BAAyB,GAAG;AAAA,IAC9B;AAAA,EACF;AACF,CAAC;","names":["customerId"]}
@@ -37,7 +37,7 @@ function parseSendsArgs(raw, argv, now = Date.now()) {
37
37
  const remove = onlyOnce(raw.remove, "--remove", argv);
38
38
  if (platform !== void 0 && remove !== void 0) {
39
39
  throw new ConversionArgsError(
40
- "--platform narrows a read, and --remove stages a change: a removal is answered in full, never narrowed. Drop --platform."
40
+ "--platform narrows a read, and --remove stages a change: a removal is answered with what it staged, never narrowed. Drop --platform."
41
41
  );
42
42
  }
43
43
  const days = raw.days === void 0 ? void 0 : Number(raw.days);
@@ -211,6 +211,20 @@ function sendsView(response, full, platform) {
211
211
  ...response.hints && response.hints.length > 0 ? { hints: response.hints } : {}
212
212
  };
213
213
  }
214
+ function sendsAnswer(response, args2) {
215
+ const target = args2.set?.id ?? args2.remove;
216
+ if (target === void 0 || args2.full) return sendsView(response, args2.full, args2.platform);
217
+ const send = response.data.sends.find((row) => row.id === target);
218
+ return {
219
+ ok: true,
220
+ data: {
221
+ ...response.data.staged === void 0 ? {} : { staged: response.data.staged },
222
+ ...send === void 0 ? {} : { send },
223
+ total: response.data.sends.length
224
+ },
225
+ ...response.hints && response.hints.length > 0 ? { hints: response.hints } : {}
226
+ };
227
+ }
214
228
  function onlyTo(data, platform) {
215
229
  const sends = data.sends.filter((send) => send.platform === platform);
216
230
  const ids = new Set(sends.map((send) => send.id));
@@ -329,7 +343,7 @@ var args = {
329
343
  },
330
344
  full: {
331
345
  type: "boolean",
332
- description: "Also return `carries` and `templateFields`: every field a send forwards and a template may read, the same for every send; with --history, the exact instants",
346
+ description: "Also return `carries` and `templateFields`: every field a send forwards and a template may read, the same for every send; with --history, the exact instants. On a --set or --remove, the whole listing instead of what was staged and the total",
333
347
  required: false
334
348
  }
335
349
  };
@@ -374,7 +388,7 @@ An empty \`events[]\` means none of the client's systems sends an event yet and
374
388
  try {
375
389
  const parsed = parseSendsArgs(raw, process.argv);
376
390
  const response = await apiPost("/api/analytics/sends", sendsWrite(parsed));
377
- writeJsonEnvelope(sendsView(response, parsed.full, parsed.platform));
391
+ writeJsonEnvelope(sendsAnswer(response, parsed));
378
392
  } catch (err) {
379
393
  handleError(err);
380
394
  }
@@ -398,8 +412,9 @@ function handleError(err) {
398
412
  export {
399
413
  parseParameterArgs,
400
414
  parseSendsArgs,
415
+ sendsAnswer,
401
416
  sendsCommand,
402
417
  sendsView,
403
418
  sendsWrite
404
419
  };
405
- //# sourceMappingURL=sends-5UCPQZ7F.js.map
420
+ //# sourceMappingURL=sends-PEQJOPRM.js.map