@koda-sl/baker-cli 0.883.0 → 0.885.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/{account-assets-FJFPB7KD.js → account-assets-Q2O3FRUE.js} +6 -6
- package/dist/{account-level-CB6I4X5W.js → account-level-NBEQ6R7X.js} +3 -3
- package/dist/{account-reads-TSDWJ3A2.js → account-reads-7DPRPWBK.js} +3 -2
- package/dist/{account-reads-TSDWJ3A2.js.map → account-reads-7DPRPWBK.js.map} +1 -1
- package/dist/{ads-ZSHBQHNK.js → ads-4QBIYBPH.js} +3 -3
- package/dist/{ads-G3N76HWA.js → ads-HKPBNXWT.js} +10 -10
- package/dist/{adsets-2HV6TJJP.js → adsets-IBLZP6EM.js} +9 -9
- package/dist/{analytics-6TNLZ4LA.js → analytics-E5OPCERI.js} +6 -5
- package/dist/{analytics-6TNLZ4LA.js.map → analytics-E5OPCERI.js.map} +1 -1
- package/dist/{asset-writes-ZOVD5O5X.js → asset-writes-NTEJDVVM.js} +3 -3
- package/dist/{audience-writes-36E6ECON.js → audience-writes-DJHKIJP7.js} +2 -2
- package/dist/{audiences-65JSGH4L.js → audiences-7TGXZS3M.js} +6 -6
- package/dist/{campaigns-PP3MFPJR.js → campaigns-VD7UOTRV.js} +9 -9
- package/dist/{catalogs-UYYPZRFW.js → catalogs-H2T4Z6AS.js} +2 -2
- package/dist/{changes-7WLOTKVE.js → changes-FQ2NWBJQ.js} +3 -2
- package/dist/{changes-7WLOTKVE.js.map → changes-FQ2NWBJQ.js.map} +1 -1
- package/dist/{chunk-Z65I6WS6.js → chunk-DX4SRYED.js} +13 -5
- package/dist/chunk-DX4SRYED.js.map +1 -0
- package/dist/{chunk-J464JWY7.js → chunk-ENTB4ILS.js} +8 -4
- package/dist/chunk-ENTB4ILS.js.map +1 -0
- package/dist/{chunk-JOQBRK4E.js → chunk-FRWCTFTP.js} +9 -4
- package/dist/chunk-FRWCTFTP.js.map +1 -0
- package/dist/{chunk-BRHYK4HQ.js → chunk-G7Q43JEZ.js} +5 -4
- package/dist/{chunk-BRHYK4HQ.js.map → chunk-G7Q43JEZ.js.map} +1 -1
- package/dist/{chunk-BX5AAH7T.js → chunk-IDLSLJIM.js} +4 -2
- package/dist/{chunk-BX5AAH7T.js.map → chunk-IDLSLJIM.js.map} +1 -1
- package/dist/{chunk-ZGYIG6OM.js → chunk-LUF2VYOK.js} +2 -2
- package/dist/chunk-LVLAFUXQ.js +37 -0
- package/dist/chunk-LVLAFUXQ.js.map +1 -0
- package/dist/{chunk-3F6AXSPB.js → chunk-ZJUUAZKY.js} +2 -2
- package/dist/cli.js +6 -6
- package/dist/{config-UR3ZKS25.js → config-Z52BRC3M.js} +3 -2
- package/dist/{config-UR3ZKS25.js.map → config-Z52BRC3M.js.map} +1 -1
- package/dist/{conversion-upload-command-CWMZEFCT.js → conversion-upload-command-ZZ5JYMBL.js} +7 -4
- package/dist/conversion-upload-command-ZZ5JYMBL.js.map +1 -0
- package/dist/{copy-writes-TEJRR2W2.js → copy-writes-FGMJ7N75.js} +3 -3
- package/dist/{creatives-ZYY5OF5U.js → creatives-67CDPYL7.js} +4 -4
- package/dist/{custom-conversions-YQPOB2IR.js → custom-conversions-RZB2622Q.js} +4 -4
- package/dist/{draft-KMRFGWIO.js → draft-3L5UZ3JP.js} +7 -4
- package/dist/draft-3L5UZ3JP.js.map +1 -0
- package/dist/{draft-XWJF772C.js → draft-CZEMQHTX.js} +3 -2
- package/dist/{draft-XWJF772C.js.map → draft-CZEMQHTX.js.map} +1 -1
- package/dist/{draft-5H6MKAKW.js → draft-FOHLBTWV.js} +3 -2
- package/dist/{draft-5H6MKAKW.js.map → draft-FOHLBTWV.js.map} +1 -1
- package/dist/{draft-OHAOBGVP.js → draft-JPWMFZNZ.js} +243 -8
- package/dist/draft-JPWMFZNZ.js.map +1 -0
- package/dist/{forecast-WTVRSFFA.js → forecast-SXZBIHFB.js} +3 -2
- package/dist/{forecast-WTVRSFFA.js.map → forecast-SXZBIHFB.js.map} +1 -1
- package/dist/{ga4-K6ARTEPX.js → ga4-6J3IMDSU.js} +12 -12
- package/dist/{google-N3GW4MDV.js → google-F77XV4ZC.js} +59 -40
- package/dist/google-F77XV4ZC.js.map +1 -0
- package/dist/{hubspot-BG4BI3RU.js → hubspot-24MLH5N7.js} +2 -2
- package/dist/{instant-experiences-YXH2AHFI.js → instant-experiences-MF2X374W.js} +2 -2
- package/dist/{leads-IGOXMIEW.js → leads-IBXGNXTX.js} +2 -2
- package/dist/{media-QOGVG6CU.js → media-YPVGQ535.js} +3 -3
- package/dist/{meta-RJH5COPE.js → meta-ZQXCUKHQ.js} +30 -30
- package/dist/{page-photos-P2XMKTVF.js → page-photos-BEAMTVP5.js} +2 -2
- package/dist/{plan-C5U4U55M.js → plan-JVD6BMEO.js} +3 -2
- package/dist/{plan-C5U4U55M.js.map → plan-JVD6BMEO.js.map} +1 -1
- package/dist/{read-UXFNPEQ5.js → read-VI63RNL6.js} +3 -2
- package/dist/{read-UXFNPEQ5.js.map → read-VI63RNL6.js.map} +1 -1
- package/dist/{rule-writes-MSMVQDQO.js → rule-writes-CVP6CH2R.js} +2 -2
- package/dist/{rules-UEKJOZTV.js → rules-LZ36YNG3.js} +7 -7
- package/dist/{search-terms-WKE47TW5.js → search-terms-SWRRTKBV.js} +3 -2
- package/dist/{search-terms-WKE47TW5.js.map → search-terms-SWRRTKBV.js.map} +1 -1
- package/dist/{sends-5UCPQZ7F.js → sends-PEQJOPRM.js} +19 -4
- package/dist/sends-PEQJOPRM.js.map +1 -0
- package/dist/{shopify-NJFARTN3.js → shopify-IRHELCGF.js} +3 -2
- package/dist/{shopify-NJFARTN3.js.map → shopify-IRHELCGF.js.map} +1 -1
- package/dist/{sources-XYKENWZF.js → sources-CACBM65R.js} +38 -17
- package/dist/sources-CACBM65R.js.map +1 -0
- package/dist/{studies-TIF7PYEB.js → studies-Y6PGWT66.js} +5 -5
- package/dist/{study-writes-RGKBOOJ6.js → study-writes-6F6O6N4E.js} +2 -2
- package/dist/{tag-manager-5Q5MHQPL.js → tag-manager-QO6VW57E.js} +10 -10
- package/dist/{targeting-YWOOD6YL.js → targeting-FRMVSXXL.js} +2 -2
- package/dist/{themes-LWG3LX7O.js → themes-GMZOWC3X.js} +3 -2
- package/dist/{themes-LWG3LX7O.js.map → themes-GMZOWC3X.js.map} +1 -1
- package/dist/{write-commands-REUTFNJ3.js → write-commands-3BMPDY3K.js} +4 -4
- package/dist/{write-commands-IAMIUSK4.js → write-commands-GRBE5V34.js} +3 -2
- package/dist/{write-commands-IAMIUSK4.js.map → write-commands-GRBE5V34.js.map} +1 -1
- package/dist/{write-commands-JXP2NHRY.js → write-commands-MZUVJBGO.js} +3 -2
- package/dist/{write-commands-JXP2NHRY.js.map → write-commands-MZUVJBGO.js.map} +1 -1
- package/package.json +1 -1
- package/dist/chunk-J464JWY7.js.map +0 -1
- package/dist/chunk-JOQBRK4E.js.map +0 -1
- package/dist/chunk-Z65I6WS6.js.map +0 -1
- package/dist/conversion-upload-command-CWMZEFCT.js.map +0 -1
- package/dist/draft-KMRFGWIO.js.map +0 -1
- package/dist/draft-OHAOBGVP.js.map +0 -1
- package/dist/google-N3GW4MDV.js.map +0 -1
- package/dist/sends-5UCPQZ7F.js.map +0 -1
- package/dist/sources-XYKENWZF.js.map +0 -1
- /package/dist/{account-assets-FJFPB7KD.js.map → account-assets-Q2O3FRUE.js.map} +0 -0
- /package/dist/{account-level-CB6I4X5W.js.map → account-level-NBEQ6R7X.js.map} +0 -0
- /package/dist/{ads-ZSHBQHNK.js.map → ads-4QBIYBPH.js.map} +0 -0
- /package/dist/{ads-G3N76HWA.js.map → ads-HKPBNXWT.js.map} +0 -0
- /package/dist/{adsets-2HV6TJJP.js.map → adsets-IBLZP6EM.js.map} +0 -0
- /package/dist/{asset-writes-ZOVD5O5X.js.map → asset-writes-NTEJDVVM.js.map} +0 -0
- /package/dist/{audience-writes-36E6ECON.js.map → audience-writes-DJHKIJP7.js.map} +0 -0
- /package/dist/{audiences-65JSGH4L.js.map → audiences-7TGXZS3M.js.map} +0 -0
- /package/dist/{campaigns-PP3MFPJR.js.map → campaigns-VD7UOTRV.js.map} +0 -0
- /package/dist/{catalogs-UYYPZRFW.js.map → catalogs-H2T4Z6AS.js.map} +0 -0
- /package/dist/{chunk-ZGYIG6OM.js.map → chunk-LUF2VYOK.js.map} +0 -0
- /package/dist/{chunk-3F6AXSPB.js.map → chunk-ZJUUAZKY.js.map} +0 -0
- /package/dist/{copy-writes-TEJRR2W2.js.map → copy-writes-FGMJ7N75.js.map} +0 -0
- /package/dist/{creatives-ZYY5OF5U.js.map → creatives-67CDPYL7.js.map} +0 -0
- /package/dist/{custom-conversions-YQPOB2IR.js.map → custom-conversions-RZB2622Q.js.map} +0 -0
- /package/dist/{ga4-K6ARTEPX.js.map → ga4-6J3IMDSU.js.map} +0 -0
- /package/dist/{hubspot-BG4BI3RU.js.map → hubspot-24MLH5N7.js.map} +0 -0
- /package/dist/{instant-experiences-YXH2AHFI.js.map → instant-experiences-MF2X374W.js.map} +0 -0
- /package/dist/{leads-IGOXMIEW.js.map → leads-IBXGNXTX.js.map} +0 -0
- /package/dist/{media-QOGVG6CU.js.map → media-YPVGQ535.js.map} +0 -0
- /package/dist/{meta-RJH5COPE.js.map → meta-ZQXCUKHQ.js.map} +0 -0
- /package/dist/{page-photos-P2XMKTVF.js.map → page-photos-BEAMTVP5.js.map} +0 -0
- /package/dist/{rule-writes-MSMVQDQO.js.map → rule-writes-CVP6CH2R.js.map} +0 -0
- /package/dist/{rules-UEKJOZTV.js.map → rules-LZ36YNG3.js.map} +0 -0
- /package/dist/{studies-TIF7PYEB.js.map → studies-Y6PGWT66.js.map} +0 -0
- /package/dist/{study-writes-RGKBOOJ6.js.map → study-writes-6F6O6N4E.js.map} +0 -0
- /package/dist/{tag-manager-5Q5MHQPL.js.map → tag-manager-QO6VW57E.js.map} +0 -0
- /package/dist/{targeting-YWOOD6YL.js.map → targeting-FRMVSXXL.js.map} +0 -0
- /package/dist/{write-commands-REUTFNJ3.js.map → write-commands-3BMPDY3K.js.map} +0 -0
|
@@ -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,CAAC,QAAQ,OAAO;AAC9C,IAAM,uBAAuB,CAAC,OAAO,aAAa,SAAS;AAC3D,IAAM,uBAAuB,CAAC,SAAS,UAAU,OAAO;AAExD,IAAM,iCAAiC,EAAE,OAAO;AAAA,EACrD,GAAG;AAAA,EACH,SAAS,EAAE,KAAK,qBA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AM;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,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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AAI,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
|
|
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(
|
|
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-
|
|
420
|
+
//# sourceMappingURL=sends-PEQJOPRM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/analytics/sends.ts"],"sourcesContent":["/**\n * `baker analytics sends` — where this company's system events are sent, and\n * changing it.\n *\n * A send hangs off an event one of the client's own systems raises, by its\n * key: `page:deal_won` from HubSpot → Meta Purchase. Every such event is\n * uploaded to the platform with who the person is, the click that brought\n * them and the amount forwarded automatically. Nothing is mapped. What happens\n * on a page or in a Form is not sendable here: the page's own pixels and the\n * Form's own side effects already send those.\n *\n * A write STAGES: it lands when the chat is published, and from then on it\n * spends ad budget on every event under the key. The dashboard's Sources page\n * applies at once because the person clicking is the review; an agent's\n * proposal gets its review at Publish.\n */\n\nimport {\n isSendPlatform,\n SEND_PLATFORMS,\n type SendPlatform,\n type SendsRequest,\n type SendsResponse,\n sendEventProblem,\n sendsRequestSchema,\n} from \"@baker/api/analytics\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { ConversionArgsError, onlyOnce } from \"./conversionArgs.ts\";\n\nexport interface SendsArgs {\n set?: {\n id: string;\n eventKey: string;\n platform: string;\n tagId: string;\n event: string;\n account?: string;\n parameters?: Record<string, string>;\n };\n remove?: string;\n /** On a read: only what goes to this platform. */\n platform?: SendPlatform;\n days?: number;\n /** One send's uploads, by id, and whether only the refused ones. */\n uploads?: string;\n failedOnly?: boolean;\n /** With `uploads`: only the events it skipped, for want of anything to match. */\n skippedOnly?: boolean;\n /** When each live send was set up, and whether its integration was removed. */\n history?: boolean;\n full: boolean;\n}\n\nconst SET_FLAGS = [\"--source-event\", \"--platform\", \"--tag\", \"--event\"] as const;\n\n/**\n * The flags, checked for the shapes that would otherwise stage the wrong\n * send in silence. Pure, so the refusals are tier-1 tested.\n */\nexport function parseSendsArgs(raw: Record<string, unknown>, argv: readonly string[], now = Date.now()): SendsArgs {\n const set = parseSetFlags(raw, argv, now);\n const platform = set === undefined ? readPlatform(raw, argv) : undefined;\n const remove = onlyOnce(raw.remove, \"--remove\", argv);\n if (platform !== undefined && remove !== undefined) {\n throw new ConversionArgsError(\n \"--platform narrows a read, and --remove stages a change: a removal is answered with what it staged, never narrowed. Drop --platform.\",\n );\n }\n\n const days = raw.days === undefined ? undefined : Number(raw.days);\n if (days !== undefined && (!Number.isInteger(days) || days <= 0 || days > 400)) {\n throw new ConversionArgsError(\"--days must be a whole number of days, from 1 to 400.\");\n }\n\n const uploads = parseUploadsFlags(raw, argv);\n\n return {\n ...(set === undefined ? {} : { set }),\n ...(remove === undefined ? {} : { remove }),\n ...(platform === undefined ? {} : { platform }),\n ...(days === undefined ? {} : { days }),\n ...uploads,\n ...(raw.history === true ? { history: true } : {}),\n full: raw.full === true,\n };\n}\n\n/** `--platform` without `--set`: the destination a read is narrowed to. */\nfunction readPlatform(raw: Record<string, unknown>, argv: readonly string[]): SendPlatform | undefined {\n const platform = onlyOnce(raw.platform, \"--platform\", argv);\n return platform === undefined ? undefined : sendPlatform(platform);\n}\n\nfunction sendPlatform(platform: string): SendPlatform {\n if (!isSendPlatform(platform)) {\n throw new ConversionArgsError(\n `\"${platform}\" is not somewhere a conversion can be sent — --platform is one of ${SEND_PLATFORMS.join(\", \")}.`,\n );\n }\n return platform;\n}\n\n/** `--uploads <sendId>` and its narrowings: a named live send, never an empty one. */\nfunction parseUploadsFlags(\n raw: Record<string, unknown>,\n argv: readonly string[],\n): Pick<SendsArgs, \"uploads\" | \"failedOnly\" | \"skippedOnly\"> {\n const uploads = onlyOnce(raw.uploads, \"--uploads\", argv);\n if (raw.uploads !== undefined && uploads === undefined) {\n throw new ConversionArgsError(\n \"--uploads takes the id of a live send (`sends[].id`); read them first with `baker analytics sends`.\",\n );\n }\n if (raw.failed === true && uploads === undefined) {\n throw new ConversionArgsError(\"--failed narrows --uploads <sendId> to the refused ones; name the send.\");\n }\n if (raw.skipped === true && uploads === undefined) {\n throw new ConversionArgsError(\n \"--skipped narrows --uploads <sendId> to the events it never uploaded; name the send.\",\n );\n }\n return {\n ...(uploads === undefined ? {} : { uploads }),\n ...(raw.failed === true ? { failedOnly: true } : {}),\n ...(raw.skipped === true ? { skippedOnly: true } : {}),\n };\n}\n\n/** The value a repeated flag carries at this position, in either spelling, or nothing. */\nfunction flagValueAt(argv: readonly string[], flag: string, index: number): string | undefined {\n const arg = argv[index] ?? \"\";\n if (arg === flag) return argv[index + 1];\n return arg.startsWith(`${flag}=`) ? arg.slice(flag.length + 1) : undefined;\n}\n\n/**\n * Every `--parameter name=template` on the command line, in order. Read off\n * argv rather than the parsed args because citty keeps only the last value\n * of a repeated flag — the defect that once staged one of three UTMs.\n */\nexport function parseParameterArgs(argv: readonly string[]): Record<string, string> | undefined {\n const parameters: Record<string, string> = {};\n for (let index = 0; index < argv.length; index += 1) {\n const pair = flagValueAt(argv, \"--parameter\", index);\n if (pair === undefined) continue;\n const eq = pair.indexOf(\"=\");\n const name = (eq === -1 ? pair : pair.slice(0, eq)).trim();\n const template = eq === -1 ? \"\" : pair.slice(eq + 1).trim();\n if (name === \"\" || template === \"\") {\n throw new ConversionArgsError(\n `--parameter needs <name>=<template>, like --parameter content_name={{properties.plan}}; got \"${pair}\".`,\n );\n }\n parameters[name] = template;\n }\n return Object.keys(parameters).length === 0 ? undefined : parameters;\n}\n\n/**\n * The send `--set` describes, or nothing on a read.\n *\n * The four flags are only meaningful together and only under `--set` (but\n * `--platform` alone, which narrows a read — `readPlatform`): a send\n * described without it would answer ok and stage nothing, and a `--set` with\n * a piece missing would be refused by the server with the field named but not\n * the flag.\n */\nfunction parseSetFlags(raw: Record<string, unknown>, argv: readonly string[], now: number): SendsArgs[\"set\"] {\n if (raw.conversion !== undefined) {\n throw new ConversionArgsError(\n \"--conversion is gone: a send is on a system's EVENT, not a conversion. Pass --source-event <key> — one of events[].eventKey from a plain `baker analytics sends` (page:<name>).\",\n );\n }\n const values = {\n \"--source-event\": onlyOnce(raw[\"source-event\"] ?? raw.sourceEvent, \"--source-event\", argv),\n \"--platform\": onlyOnce(raw.platform, \"--platform\", argv),\n \"--tag\": onlyOnce(raw.tag, \"--tag\", argv),\n \"--event\": onlyOnce(raw.event, \"--event\", argv),\n };\n const given = SET_FLAGS.filter((flag) => values[flag] !== undefined);\n const set = raw.set === true;\n\n if (!set) {\n // `--platform` alone narrows a read; with any other piece of a send it describes one.\n const shaping = sendOnlyFlags(raw, argv);\n if (shaping.length > 0 || given.some((flag) => flag !== \"--platform\")) {\n throw new ConversionArgsError(\n `${[...given, ...shaping].join(\", \")} describe a send, so add --set to stage it. Without --set the command only reads, and --platform on its own narrows that read to one platform.`,\n );\n }\n return undefined;\n }\n\n const missing = SET_FLAGS.filter((flag) => values[flag] === undefined);\n if (missing.length > 0) {\n throw new ConversionArgsError(\n `--set needs ${SET_FLAGS.join(\", \")}; missing ${missing.join(\", \")}. Copy --tag from platforms[].tags of a plain \\`baker analytics sends\\`, never from memory.`,\n );\n }\n const platform = sendPlatform(values[\"--platform\"] ?? \"\");\n\n const event = values[\"--event\"] ?? \"\";\n const templated = sendEventProblem(platform, event);\n if (templated !== null) {\n throw new ConversionArgsError(`--event ${event} cannot be sent to ${platform}. ${templated}`);\n }\n\n const account = onlyOnce(raw.account, \"--account\", argv);\n const parameters = parseParameterArgs(argv);\n return {\n id: onlyOnce(raw.id, \"--id\", argv) ?? sendIdFor(now),\n eventKey: values[\"--source-event\"] ?? \"\",\n ...originFlag(raw, argv),\n platform,\n tagId: values[\"--tag\"] ?? \"\",\n event,\n ...(account === undefined ? {} : { account }),\n ...(parameters === undefined ? {} : { parameters }),\n };\n}\n\n/** The options that only shape a staged send, given on the command line. */\nfunction sendOnlyFlags(raw: Record<string, unknown>, argv: readonly string[]): string[] {\n return [\n ...(raw.parameter !== undefined || argv.some((arg) => arg === \"--parameter\" || arg.startsWith(\"--parameter=\"))\n ? [\"--parameter\"]\n : []),\n ...(raw.from === undefined ? [] : [\"--from\"]),\n ...(raw.account === undefined ? [] : [\"--account\"]),\n ...(raw.id === undefined ? [] : [\"--id\"]),\n ];\n}\n\n/**\n * Which door's events `--set` uploads, as the send spells it: every door the\n * event arrives by (`origin: \"any\"`, the default — one event, one set of\n * destinations, uploaded once when the pixel and the API both report it under\n * one event id), or only the pixel's (`website`) or only the API's and the\n * integrations' (no field at all).\n */\nfunction originFlag(raw: Record<string, unknown>, argv: readonly string[]): { origin?: \"website\" | \"any\" } {\n const from = onlyOnce(raw.from, \"--from\", argv) ?? \"any\";\n if (from === \"any\") return { origin: \"any\" };\n if (from === \"api\") return {};\n if (from === \"pixel\") return { origin: \"website\" };\n throw new ConversionArgsError(\n `--from is any, pixel or api; got \"${from}\". any — the default — uploads the event whichever door it arrives by, once when the pixel and the API both report it with the same event id; pixel only what Baker's pixel sent from the client's website; api only what the API or an integration sent.`,\n );\n}\n\n/** A short id a person can type, when the caller did not choose one. */\nfunction sendIdFor(now: number): string {\n return `s${now.toString(36).slice(-5)}`;\n}\n\n/**\n * The request body, validated against the shared schema here rather than only\n * on the server, so a malformed send is named before a round trip.\n */\nexport function sendsWrite(args: SendsArgs): SendsRequest {\n const body = {\n ...(args.set === undefined ? {} : { set: [args.set] }),\n ...(args.remove === undefined ? {} : { remove: [args.remove] }),\n ...(args.days === undefined ? {} : { days: args.days }),\n ...(args.uploads === undefined ? {} : { uploads: args.uploads }),\n ...(args.failedOnly === undefined ? {} : { failedOnly: args.failedOnly }),\n ...(args.skippedOnly === undefined ? {} : { skippedOnly: args.skippedOnly }),\n ...(args.history === undefined ? {} : { history: args.history }),\n ...(args.platform === undefined ? {} : { platform: args.platform }),\n };\n const parsed = sendsRequestSchema.safeParse(body);\n if (!parsed.success) {\n const issue = parsed.error.issues[0];\n throw new ConversionArgsError(\n `That send cannot be staged — ${issue?.path.join(\".\") || \"set\"}: ${issue?.message ?? \"invalid\"}. Run \\`baker schema analytics.sends\\` for the exact shape.`,\n );\n }\n return parsed.data;\n}\n\n/**\n * What to print. Compact by default: the sends with their outcomes, the\n * platforms with the tags that can send (where a `tagId` is copied from), and\n * the system events that can be sent. `carries` — every field a send forwards\n * — is the same list every time, so it is behind `--full`. A send's history is\n * the day it was set up and the day its integration was removed; the instants\n * are behind `--full`.\n */\nexport function sendsView(response: SendsResponse, full: boolean, platform?: SendPlatform): Record<string, unknown> {\n const data = platform === undefined ? response.data : onlyTo(response.data, platform);\n const { carries, templateFields, history, ...rest } = data;\n return {\n ok: true,\n data: {\n ...rest,\n ...(history === undefined ? {} : { history: history.map((row) => historyView(row, full)) }),\n ...(full ? { carries, templateFields } : {}),\n },\n ...(response.hints && response.hints.length > 0 ? { hints: response.hints } : {}),\n };\n}\n\n/**\n * What a call prints. A read is {@link sendsView}. A write answers with what\n * this chat staged, the live send it changes, and how many sends there are —\n * not the sends, platforms, events and parameters a read lists, which grow\n * with the company. `--full` keeps the whole listing.\n */\nexport function sendsAnswer(response: SendsResponse, args: SendsArgs): Record<string, unknown> {\n const target = args.set?.id ?? args.remove;\n if (target === undefined || args.full) return sendsView(response, args.full, args.platform);\n const send = response.data.sends.find((row) => row.id === target);\n return {\n ok: true,\n data: {\n ...(response.data.staged === undefined ? {} : { staged: response.data.staged }),\n ...(send === undefined ? {} : { send }),\n total: response.data.sends.length,\n },\n ...(response.hints && response.hints.length > 0 ? { hints: response.hints } : {}),\n };\n}\n\ntype SendsData = SendsResponse[\"data\"];\n\n/**\n * The read narrowed to one destination: its sends, live and staged, its\n * platform row and parameters, and each event's match on it alone. The\n * events themselves stay — any of them can be sent there.\n */\nfunction onlyTo(data: SendsData, platform: SendPlatform): SendsData {\n const sends = data.sends.filter((send) => send.platform === platform);\n const ids = new Set(sends.map((send) => send.id));\n const pick = (counts: Record<string, number>) => (platform in counts ? { [platform]: counts[platform] ?? 0 } : {});\n return {\n ...data,\n sends,\n ...(data.staged === undefined\n ? {}\n : {\n staged: {\n set: data.staged.set.filter((send) => send.platform === platform),\n remove: data.staged.remove.filter((id) => ids.has(id)),\n },\n }),\n platforms: data.platforms.filter((row) => row.platform === platform),\n parameters: data.parameters.filter((row) => row.platform === platform),\n events: data.events.map((event) =>\n event.match === undefined\n ? event\n : {\n ...event,\n match: { ...event.match, platforms: pick(event.match.platforms), withheld: pick(event.match.withheld) },\n },\n ),\n ...(data.history === undefined ? {} : { history: data.history.filter((row) => ids.has(row.sendId)) }),\n };\n}\n\ntype SendHistoryRow = NonNullable<SendsResponse[\"data\"][\"history\"]>[number];\n\nfunction historyView(row: SendHistoryRow, full: boolean): Record<string, string> {\n const at = (ms: number) => new Date(ms).toISOString();\n const removed = row.integrationRemovedAt;\n if (full) {\n return {\n sendId: row.sendId,\n createdAt: at(row.createdAt),\n ...(removed === undefined ? {} : { integrationRemovedAt: at(removed) }),\n };\n }\n return {\n sendId: row.sendId,\n setUpOn: at(row.createdAt).slice(0, 10),\n ...(removed === undefined ? {} : { integrationRemovedOn: at(removed).slice(0, 10) }),\n };\n}\n\nconst args = {\n set: {\n type: \"boolean\",\n description:\n \"Stage a send, described by --source-event, --platform, --tag and --event. It applies when this chat is published, and from then on every event arriving under that key is uploaded to the platform and spends ad budget — say so to the client, never that it is a preview\",\n required: false,\n },\n \"source-event\": {\n type: \"string\",\n description:\n \"The event to send, by key — one of `events[].eventKey` from a plain `baker analytics sends`: a Source's own event (page:<source name>), or a named event the client's server posts. A Form's or a page's event is refused: the page's own pixels and the Form's side effects already send those\",\n required: false,\n },\n from: {\n type: \"string\",\n description:\n \"Which door's events the send uploads: `any` (default) — the event whichever door it arrives by, uploaded once when the pixel and the API both report it with the same event id; `pixel` — only what Baker's pixel sent from the client's own website (an `events[]` row with origin `website`); `api` — only what the client's server posted or an integration like HubSpot sent\",\n required: false,\n },\n platform: {\n type: \"string\",\n description: `Where it goes: one of ${SEND_PLATFORMS.join(\", \")}. With --set, the send's destination; without it, narrows the read to that platform's sends (live and staged), its tags, parameters and each event's match there — \\`baker analytics sends --platform meta\\``,\n required: false,\n },\n tag: {\n type: \"string\",\n description:\n \"The tag on Tracking that sends it. COPY the id from `platforms[].tags[].tagId` in the response — it is only listed there when the tag holds its server credential, and one typed from memory is refused\",\n required: false,\n },\n event: {\n type: \"string\",\n description:\n 'What the platform calls it — `platforms[].eventMeans` says what each one takes: a Meta or Google Analytics event name (Purchase, Lead, generate_lead), a Google Ads conversion action id copied from `platforms[].conversionActions`, or the conversion label the person gives you (staged as its id; never type an id: one the account does not hold is refused), a LinkedIn conversion rule id, an X event tag id. On Meta and Google Analytics it may be WRITTEN FROM THE EVENT with the same {{path}} mentions --parameter takes: --event {{properties.plan}} sends each event under the plan it carries, --event \"Purchase {{properties.tier}}\" mixes text and a field. An event carrying nothing there is not uploaded. Google Ads, LinkedIn and X take an id THEY issued, so a template is refused there — pass what varies as a --parameter instead. For a GOOGLE ADS id, list the account\\'s conversion actions first and pick by name — `baker ads google query \"SELECT conversion_action.id, conversion_action.name, conversion_action.primary_for_goal FROM conversion_action WHERE conversion_action.status = \\'ENABLED\\'\"` — never guess: Google accepts an upload against an id the account does not hold and files it against nothing',\n required: false,\n },\n account: {\n type: \"string\",\n description: \"LinkedIn only: the ad account the conversion rule belongs to\",\n required: false,\n },\n parameter: {\n type: \"string\",\n description:\n \"<name>=<template>, repeatable, with --set: an EXTRA parameter the platform receives with every upload, beyond who, the click and the amount — Meta's custom_data (content_name, content_category, or your own), a GA4 event parameter, a Google Ads custom variable (must exist in the account), X's contents (content_name, num_items…); LinkedIn takes none. The template is text with {{path}} mentions over the event: its own properties as {{properties.<key>}} (a HubSpot event's --field properties.<key> rows, a server event's `properties`), and the fields `templateFields` lists (--full): value, value_currency, event_name, page_path, city, country, gclid… Example: --parameter content_name={{properties.plan}} --parameter content_category=hubspot. `parameters[]` in the response says what each platform takes\",\n required: false,\n },\n uploads: {\n type: \"string\",\n description:\n \"The id of a send (`sends[].id`) whose uploads to list, newest first over --days: which event went, when, `outcome` (success | failed | pending | skipped) and in `error` what a skipped event was missing, or why a failed one failed — a platform's code followed by its own words after the colon (auth_failed, invalid_token, invalid_event, invalid_parameter, bad_request) when the platform refused it (ChatGPT Ads' refusal is its own answer as it gave it, often JSON, with no code in front), or one of Baker's own codes (strict_denied, blocked_by_gpc, no_matchable_identifier, no_identifier, event_too_old, or a setup code such as tag_not_found; analytics.md lists them) when Baker refused it before sending and the platform never received it — the rows behind `sends[].outcome`. With --failed, only the refused ones; with --skipped, only the skipped ones\",\n required: false,\n },\n failed: {\n type: \"boolean\",\n description: \"With --uploads: only the failed uploads — refused by the platform, or by Baker before sending\",\n required: false,\n },\n skipped: {\n type: \"boolean\",\n description:\n \"With --uploads: only the events the send never uploaded because they carried nothing the platform matches a person by — each `error` names what was missing (a Meta click id or cookie, an email, a gclid…)\",\n required: false,\n },\n history: {\n type: \"boolean\",\n description:\n \"Also return `history[]`: the day each live send was set up (`setUpOn`) and, when an integration named after its event was removed since, the day it was (`integrationRemovedOn`) — read it before removing or explaining a send whose event no longer arrives. --full gives the instants\",\n required: false,\n },\n id: {\n type: \"string\",\n description:\n \"The send's id, when changing one that exists (`sends[].id` for a live one, `staged.set[].id` for one staged in this chat, like s1). Left out, a new id is minted and a NEW send is staged — so re-running a --set you already ran is refused, naming the send it would duplicate\",\n required: false,\n },\n remove: {\n type: \"string\",\n description: \"The id of a send to stop, from `sends[].id`. Staged like a set: it stops when the chat is published\",\n required: false,\n },\n days: {\n type: \"string\",\n description: \"How many days the outcome beside each send covers (default 30, up to 400)\",\n required: false,\n },\n full: {\n type: \"boolean\",\n description:\n \"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\",\n required: false,\n },\n} as const;\n\nregisterSchema({\n command: \"analytics.sends\",\n routes: [\"POST /api/analytics/sends\"],\n effect: \"stage\",\n description: \"Read where this company's system events are sent, or stage a change\",\n args,\n});\n\nexport const sendsCommand = defineCommand({\n meta: {\n name: \"sends\",\n description: `Where this company's SYSTEM EVENTS are sent — Meta, Google Ads, LinkedIn, X, Google Analytics — and what happened to each upload. A send belongs to an event one of the client's own systems raises, by key: page:deal_won from HubSpot → Meta Purchase means every \"deal_won\" HubSpot reports is uploaded to Meta with who the person is, the click that brought them and the amount forwarded automatically. There is nothing to map. What happens on a page or in a Form is never sent from here — the page's pixels and the Form's own side effects do that — and a send is never set on a funnel step: the step reads the sends of the events behind its ways in.\n\nStart here:\n baker analytics sends — the sends in effect, each with its outcome; the platforms and the tags that can send; the system events (events[]) that can be sent\n baker analytics sends --set --source-event page:deal_won --platform meta --tag <tagId> --event Purchase\n baker analytics sends --set --source-event page:deal_won --platform googleAds --tag <tagId> --event 987654321\n baker analytics sends --set --source-event page:deal_won --platform meta --tag <tagId> --event Purchase --parameter content_name={{properties.plan}}\n baker analytics sends --set --source-event page:lead_completed_step_2 --platform meta --tag <tagId> --event Lead — an event the pixel and/or the API send; uploaded once per event id\n baker analytics sends --set --source-event page:deal_won --platform meta --tag <tagId> --event {{properties.plan}} — a Meta event named after what each one carries\n baker analytics sends --remove s1 — stop one\n baker analytics sends --platform meta — only what goes to Meta: its sends, tags, parameters and each event's match there\n baker analytics sends --days 7 — outcomes over the last week\n baker analytics sends --uploads s1 --failed — the refused uploads, each with the event and why: the platform's own words, or Baker's code when it never left Baker\n baker analytics sends --uploads s1 --skipped — the events never uploaded, each with what the platform needed and they lacked\n baker analytics sends --history — when each send was set up, and whether the integration its event came from was removed\n\nThree things to hold on to:\n it is STAGED — a set or a remove lands when this chat is published, and from then on it SPENDS AD BUDGET on every \"<event>\" that arrives. Tell the client that plainly; never call a published send a preview.\n the tagId is COPIED — from \\`platforms[].tags\\` in the response, which lists only the tags on Tracking that hold their server credential. One typed from memory is refused; each platform says \\`canSend\\`, and one that cannot says what to add on Tracking (\\`platforms[].setupHint\\`).\n the outcome is what happened — \\`sends[].outcome\\` counts what was sent, what failed and why (\\`lastError\\`: the platform's words, or Baker's own code when Baker refused the upload before sending), and what was SKIPPED: an event carrying nothing the platform matches a person by is never uploaded (Meta: a Meta click id or cookie, an email or your own customer id; Google Ads: gclid, wbraid, gbraid, an email or a phone; LinkedIn: li_fat_id or an email; X: twclid or an email; Google Analytics: nothing), counted in \\`skipped\\` with \\`lastSkipReason\\`.\n check the MATCH before staging — \\`events[].match\\` says, for the last 30 days of each event, how many arrived, how many each platform could match, and how many it could but the cookie consent setting keeps from it (\\`withheld\\`). A send to a platform matching 0 of 14, none withheld, skips all 14: say so to the client, and ask for the click id or the email to be sent with the event instead. A withheld event already carries the identifier, so ask for the person's choice to be sent with it (\\`consent.marketing: granted\\`), or another setting — never more identifiers. \"Nothing sent yet\" means no event under that name has fired since the send was set. \\`--uploads <id>\\` lists the rows behind the count, \\`--failed\\` only the refused ones — read it before telling a client a send \"failed\".\n a Meta or GA4 event name can be WRITTEN FROM THE EVENT — \\`--event {{properties.plan}}\\` sends each event under its own plan, so one Source covers every value instead of one Source, one send and one conversion action per value. Only where the platform takes a name of your own: Google Ads, LinkedIn and X take an id they issued and refuse a template.\n extra parameters are optional — \\`--parameter <name>=<template>\\` adds what the platform receives beyond who, the click and the amount: \\`{{properties.<key>}}\\` reads a property the event carries (a HubSpot event's \\`--field properties.<key>\\` rows), \\`{{value}}\\`, \\`{{page_path}}\\`, \\`{{city}}\\`… read the event's fields. \\`parameters[]\\` in the response says what each platform takes and the names it knows; LinkedIn takes none.\n\nAn empty \\`events[]\\` means none of the client's systems sends an event yet and there is nothing to send: make a Source with \\`baker analytics sources\\` (a HubSpot event, or the server's address), then send its event.`,\n },\n args,\n run: async ({ args: raw }) => {\n try {\n const parsed = parseSendsArgs(raw as Record<string, unknown>, process.argv);\n const response = await apiPost<SendsResponse>(\"/api/analytics/sends\", sendsWrite(parsed));\n writeJsonEnvelope(sendsAnswer(response, parsed));\n } catch (err) {\n handleError(err);\n }\n },\n});\n\nfunction handleError(err: unknown): never {\n if (err instanceof ConversionArgsError) {\n writeJsonEnvelope({ ok: false, error: { code: \"VALIDATION_ERROR\", message: err.message } });\n process.exit(1);\n }\n if (err instanceof ApiError) {\n writeJsonEnvelope({ ok: false, error: { code: err.code, message: err.message } });\n process.exit(1);\n }\n writeJsonEnvelope({\n ok: false,\n error: { code: \"NETWORK_ERROR\", message: err instanceof Error ? err.message : \"Unexpected error\" },\n });\n process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,qBAAqB;AA8B9B,IAAM,YAAY,CAAC,kBAAkB,cAAc,SAAS,SAAS;AAM9D,SAAS,eAAe,KAA8B,MAAyB,MAAM,KAAK,IAAI,GAAc;AACjH,QAAM,MAAM,cAAc,KAAK,MAAM,GAAG;AACxC,QAAM,WAAW,QAAQ,SAAY,aAAa,KAAK,IAAI,IAAI;AAC/D,QAAM,SAAS,SAAS,IAAI,QAAQ,YAAY,IAAI;AACpD,MAAI,aAAa,UAAa,WAAW,QAAW;AAClD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,OAAO,IAAI,SAAS,SAAY,SAAY,OAAO,IAAI,IAAI;AACjE,MAAI,SAAS,WAAc,CAAC,OAAO,UAAU,IAAI,KAAK,QAAQ,KAAK,OAAO,MAAM;AAC9E,UAAM,IAAI,oBAAoB,uDAAuD;AAAA,EACvF;AAEA,QAAM,UAAU,kBAAkB,KAAK,IAAI;AAE3C,SAAO;AAAA,IACL,GAAI,QAAQ,SAAY,CAAC,IAAI,EAAE,IAAI;AAAA,IACnC,GAAI,WAAW,SAAY,CAAC,IAAI,EAAE,OAAO;AAAA,IACzC,GAAI,aAAa,SAAY,CAAC,IAAI,EAAE,SAAS;AAAA,IAC7C,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,KAAK;AAAA,IACrC,GAAG;AAAA,IACH,GAAI,IAAI,YAAY,OAAO,EAAE,SAAS,KAAK,IAAI,CAAC;AAAA,IAChD,MAAM,IAAI,SAAS;AAAA,EACrB;AACF;AAGA,SAAS,aAAa,KAA8B,MAAmD;AACrG,QAAM,WAAW,SAAS,IAAI,UAAU,cAAc,IAAI;AA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;AAAA,IACJ,OAAO,EAAE,MAAM,iBAAiB,SAAS,eAAe,QAAQ,IAAI,UAAU,mBAAmB;AAAA,EACnG,CAAC;AACD,UAAQ,KAAK,CAAC;AAChB;","names":["args"]}
|
|
@@ -15,12 +15,13 @@ import {
|
|
|
15
15
|
failValidation,
|
|
16
16
|
loadJsonArg,
|
|
17
17
|
loadJsonPayloads
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-DX4SRYED.js";
|
|
19
19
|
import {
|
|
20
20
|
amendDraftRefs,
|
|
21
21
|
draftRefs,
|
|
22
22
|
removeDraftRefs
|
|
23
23
|
} from "./chunk-BYYV4MJU.js";
|
|
24
|
+
import "./chunk-LVLAFUXQ.js";
|
|
24
25
|
import {
|
|
25
26
|
changeListWhereArg,
|
|
26
27
|
draftListWhere,
|
|
@@ -4030,4 +4031,4 @@ Full guide: __tooling__/docs/tools/baker/shopify.md`
|
|
|
4030
4031
|
export {
|
|
4031
4032
|
shopifyCommand
|
|
4032
4033
|
};
|
|
4033
|
-
//# sourceMappingURL=shopify-
|
|
4034
|
+
//# sourceMappingURL=shopify-IRHELCGF.js.map
|