@koda-sl/baker-cli 0.883.0 → 0.884.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +3 -1
  2. package/dist/{account-reads-TSDWJ3A2.js → account-reads-7DPRPWBK.js} +3 -2
  3. package/dist/{account-reads-TSDWJ3A2.js.map → account-reads-7DPRPWBK.js.map} +1 -1
  4. package/dist/{ads-ZSHBQHNK.js → ads-Z2YUBDUF.js} +2 -2
  5. package/dist/{analytics-6TNLZ4LA.js → analytics-E5OPCERI.js} +6 -5
  6. package/dist/{analytics-6TNLZ4LA.js.map → analytics-E5OPCERI.js.map} +1 -1
  7. package/dist/{changes-7WLOTKVE.js → changes-FQ2NWBJQ.js} +3 -2
  8. package/dist/{changes-7WLOTKVE.js.map → changes-FQ2NWBJQ.js.map} +1 -1
  9. package/dist/{chunk-Z65I6WS6.js → chunk-DX4SRYED.js} +13 -5
  10. package/dist/chunk-DX4SRYED.js.map +1 -0
  11. package/dist/{chunk-J464JWY7.js → chunk-ENTB4ILS.js} +8 -4
  12. package/dist/chunk-ENTB4ILS.js.map +1 -0
  13. package/dist/{chunk-JOQBRK4E.js → chunk-FRWCTFTP.js} +9 -4
  14. package/dist/chunk-FRWCTFTP.js.map +1 -0
  15. package/dist/{chunk-BX5AAH7T.js → chunk-IDLSLJIM.js} +4 -2
  16. package/dist/{chunk-BX5AAH7T.js.map → chunk-IDLSLJIM.js.map} +1 -1
  17. package/dist/chunk-LVLAFUXQ.js +37 -0
  18. package/dist/chunk-LVLAFUXQ.js.map +1 -0
  19. package/dist/cli.js +6 -6
  20. package/dist/{config-UR3ZKS25.js → config-Z52BRC3M.js} +3 -2
  21. package/dist/{config-UR3ZKS25.js.map → config-Z52BRC3M.js.map} +1 -1
  22. package/dist/{conversion-upload-command-CWMZEFCT.js → conversion-upload-command-ZZ5JYMBL.js} +7 -4
  23. package/dist/conversion-upload-command-ZZ5JYMBL.js.map +1 -0
  24. package/dist/{draft-KMRFGWIO.js → draft-3L5UZ3JP.js} +7 -4
  25. package/dist/draft-3L5UZ3JP.js.map +1 -0
  26. package/dist/{draft-XWJF772C.js → draft-CZEMQHTX.js} +3 -2
  27. package/dist/{draft-XWJF772C.js.map → draft-CZEMQHTX.js.map} +1 -1
  28. package/dist/{draft-5H6MKAKW.js → draft-FOHLBTWV.js} +3 -2
  29. package/dist/{draft-5H6MKAKW.js.map → draft-FOHLBTWV.js.map} +1 -1
  30. package/dist/{forecast-WTVRSFFA.js → forecast-SXZBIHFB.js} +3 -2
  31. package/dist/{forecast-WTVRSFFA.js.map → forecast-SXZBIHFB.js.map} +1 -1
  32. package/dist/{ga4-K6ARTEPX.js → ga4-6J3IMDSU.js} +12 -12
  33. package/dist/{google-N3GW4MDV.js → google-F77XV4ZC.js} +59 -40
  34. package/dist/google-F77XV4ZC.js.map +1 -0
  35. package/dist/{hubspot-BG4BI3RU.js → hubspot-24MLH5N7.js} +2 -2
  36. package/dist/{plan-C5U4U55M.js → plan-JVD6BMEO.js} +3 -2
  37. package/dist/{plan-C5U4U55M.js.map → plan-JVD6BMEO.js.map} +1 -1
  38. package/dist/{read-UXFNPEQ5.js → read-VI63RNL6.js} +3 -2
  39. package/dist/{read-UXFNPEQ5.js.map → read-VI63RNL6.js.map} +1 -1
  40. package/dist/{search-terms-WKE47TW5.js → search-terms-SWRRTKBV.js} +3 -2
  41. package/dist/{search-terms-WKE47TW5.js.map → search-terms-SWRRTKBV.js.map} +1 -1
  42. package/dist/{sends-5UCPQZ7F.js → sends-PEQJOPRM.js} +19 -4
  43. package/dist/sends-PEQJOPRM.js.map +1 -0
  44. package/dist/{shopify-NJFARTN3.js → shopify-IRHELCGF.js} +3 -2
  45. package/dist/{shopify-NJFARTN3.js.map → shopify-IRHELCGF.js.map} +1 -1
  46. package/dist/{sources-XYKENWZF.js → sources-CACBM65R.js} +38 -17
  47. package/dist/sources-CACBM65R.js.map +1 -0
  48. package/dist/{tag-manager-5Q5MHQPL.js → tag-manager-QO6VW57E.js} +10 -10
  49. package/dist/{themes-LWG3LX7O.js → themes-GMZOWC3X.js} +3 -2
  50. package/dist/{themes-LWG3LX7O.js.map → themes-GMZOWC3X.js.map} +1 -1
  51. package/dist/{write-commands-IAMIUSK4.js → write-commands-GRBE5V34.js} +3 -2
  52. package/dist/{write-commands-IAMIUSK4.js.map → write-commands-GRBE5V34.js.map} +1 -1
  53. package/dist/{write-commands-JXP2NHRY.js → write-commands-MZUVJBGO.js} +3 -2
  54. package/dist/{write-commands-JXP2NHRY.js.map → write-commands-MZUVJBGO.js.map} +1 -1
  55. package/package.json +1 -1
  56. package/dist/chunk-J464JWY7.js.map +0 -1
  57. package/dist/chunk-JOQBRK4E.js.map +0 -1
  58. package/dist/chunk-Z65I6WS6.js.map +0 -1
  59. package/dist/conversion-upload-command-CWMZEFCT.js.map +0 -1
  60. package/dist/draft-KMRFGWIO.js.map +0 -1
  61. package/dist/google-N3GW4MDV.js.map +0 -1
  62. package/dist/sends-5UCPQZ7F.js.map +0 -1
  63. package/dist/sources-XYKENWZF.js.map +0 -1
  64. /package/dist/{ads-ZSHBQHNK.js.map → ads-Z2YUBDUF.js.map} +0 -0
  65. /package/dist/{ga4-K6ARTEPX.js.map → ga4-6J3IMDSU.js.map} +0 -0
  66. /package/dist/{hubspot-BG4BI3RU.js.map → hubspot-24MLH5N7.js.map} +0 -0
  67. /package/dist/{tag-manager-5Q5MHQPL.js.map → tag-manager-QO6VW57E.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/tag-manager/write-commands.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { loadJsonArg, requireTarget, stageOp } from \"./shared.ts\";\n\n/**\n * Staged write verbs. Each stages one op onto this chat's Tag Manager draft;\n * nothing reaches Tag Manager until the chat is published, and even then it\n * lands in an unpublished container version.\n */\n\n/**\n * A company can connect several containers, and a publish applies to one of\n * them at a time. With more than one connected, a change that does not name its\n * container is refused rather than staged into whichever came first.\n */\nconst CONTAINER_ARG_DESCRIPTION =\n \"Numeric container id (optional only when one container is connected — run `baker tag-manager containers`)\";\n\nconst ENTITIES = [\n {\n entity: \"tag\",\n noun: \"tag\",\n createHint:\n 'Payload needs name + type (e.g. \"gaawe\" for a GA4 event) and usually parameter[] and firingTriggerId[]. Reference a trigger by its numeric id, or by a gtm_temp_* ref if you are staging it in this same chat.',\n example: '{\"name\":\"GA4 - Generate Lead\",\"type\":\"gaawe\",\"firingTriggerId\":[\"gtm_temp_trigger_x_0\"]}',\n },\n {\n entity: \"trigger\",\n noun: \"trigger\",\n createHint:\n 'Payload needs name + type (e.g. \"pageview\", \"click\", \"customEvent\"). Stage the trigger BEFORE the tag that fires on it, then reference it by its gtm_temp_* ref.',\n example: '{\"name\":\"Form - Submit\",\"type\":\"formSubmission\"}',\n },\n {\n entity: \"variable\",\n noun: \"variable\",\n createHint:\n 'Payload needs name + type (e.g. \"v\" for a data layer variable, \"c\" for a constant). Other entities reference a variable by NAME as {{Variable Name}}.',\n example: '{\"name\":\"DL - lead_id\",\"type\":\"v\",\"parameter\":[{\"type\":\"template\",\"key\":\"name\",\"value\":\"lead_id\"}]}',\n },\n {\n entity: \"folder\",\n noun: \"folder\",\n createHint: \"Payload needs name. Use folders to keep a large container legible.\",\n example: '{\"name\":\"Google Ads\"}',\n },\n] as const;\n\nfor (const { entity, noun, createHint } of ENTITIES) {\n registerSchema({\n command: `tagManager.${entity}.create`,\n description: `Stage the creation of a Tag Manager ${noun}. ${createHint} Staged only — applies when the chat completes.`,\n args: {\n json: { type: \"string\", description: `Inline JSON ${noun} definition`, required: false },\n file: { type: \"string\", description: `Path to a JSON file with the ${noun} definition`, required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n });\n registerSchema({\n command: `tagManager.${entity}.update`,\n description: `Stage an update to an existing Tag Manager ${noun}. Pass the ${noun} id or path as the positional argument and the changed fields as JSON. Read the container first so you send the fields you mean to change.`,\n args: {\n json: { type: \"string\", description: \"Inline JSON with the changed fields\", required: false },\n file: { type: \"string\", description: \"Path to a JSON file with the changed fields\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n });\n registerSchema({\n command: `tagManager.${entity}.delete`,\n description: `Stage the deletion of a Tag Manager ${noun}. Pass its id or path as the positional argument. Deleting is irreversible once the resulting version is published — confirm with the user first.`,\n args: {\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n });\n}\n\nfunction entityCommand(entity: (typeof ENTITIES)[number][\"entity\"], noun: string, example: string) {\n return defineCommand({\n meta: { name: entity, description: `Stage ${noun} changes on this chat's Tag Manager draft` },\n subCommands: {\n create: defineCommand({\n meta: {\n name: \"create\",\n description: `Stage a new ${noun}\n\nExamples:\n baker tag-manager ${entity} create --json '${example}'\n baker tag-manager ${entity} create --file ./${entity}.json`,\n },\n args: {\n json: { type: \"string\", description: \"Inline JSON definition\", required: false },\n file: { type: \"string\", description: \"Path to a JSON file\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: `tagManager.${entity}.create`,\n payload: loadJsonArg(args as Record<string, unknown>),\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n update: defineCommand({\n meta: {\n name: \"update\",\n description: `Stage an update to an existing ${noun} (pass its id or path)`,\n },\n args: {\n id: { type: \"positional\", description: `${noun} id or path`, required: false },\n json: { type: \"string\", description: \"Inline JSON with changed fields\", required: false },\n file: { type: \"string\", description: \"Path to a JSON file\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: `tagManager.${entity}.update`,\n target: requireTarget(args as Record<string, unknown>, noun),\n payload: loadJsonArg(args as Record<string, unknown>),\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n delete: defineCommand({\n meta: { name: \"delete\", description: `Stage the deletion of a ${noun} (pass its id or path)` },\n args: {\n id: { type: \"positional\", description: `${noun} id or path`, required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: `tagManager.${entity}.delete`,\n target: requireTarget(args as Record<string, unknown>, noun),\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n },\n });\n}\n\nconst exampleFor = (entity: string) => ENTITIES.find((e) => e.entity === entity)?.example ?? \"{}\";\n\nexport const tagCommand = entityCommand(\"tag\", \"tag\", exampleFor(\"tag\"));\nexport const triggerCommand = entityCommand(\"trigger\", \"trigger\", exampleFor(\"trigger\"));\nexport const variableCommand = entityCommand(\"variable\", \"variable\", exampleFor(\"variable\"));\nexport const folderCommand = entityCommand(\"folder\", \"folder\", exampleFor(\"folder\"));\n\nregisterSchema({\n command: \"tagManager.builtin\",\n description:\n \"Enable or disable Tag Manager built-in variables by type (e.g. clickUrl, pageUrl, formId). Built-in variables must be enabled before a trigger or tag can reference them as {{Click URL}}.\",\n args: {\n types: { type: \"string\", description: \"Comma-separated built-in variable types\", required: true },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n});\n\nfunction builtinTypes(args: Record<string, unknown>): string[] {\n const raw = args.types;\n if (typeof raw !== \"string\" || raw.length === 0) {\n process.stdout.write(\n `${JSON.stringify({ ok: false, error: { code: \"VALIDATION_ERROR\", message: \"pass --types with comma-separated built-in variable types\" } }, null, 2)}\\n`,\n );\n process.exit(1);\n }\n return raw.split(\",\").map((entry) => entry.trim());\n}\n\nexport const builtinCommand = defineCommand({\n meta: {\n name: \"builtin\",\n description: `Enable or disable built-in variables\n\nExamples:\n baker tag-manager builtin enable --types clickUrl,clickText\n baker tag-manager builtin disable --types formId`,\n },\n subCommands: {\n enable: defineCommand({\n meta: { name: \"enable\", description: \"Stage enabling built-in variables\" },\n args: {\n types: { type: \"string\", description: \"Comma-separated types\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: \"tagManager.builtInVariable.enable\",\n payload: { type: builtinTypes(args as Record<string, unknown>) },\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n disable: defineCommand({\n meta: { name: \"disable\", description: \"Stage disabling built-in variables\" },\n args: {\n types: { type: \"string\", description: \"Comma-separated types\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: \"tagManager.builtInVariable.disable\",\n payload: { type: builtinTypes(args as Record<string, unknown>) },\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAe9B,IAAM,4BACJ;AAEF,IAAM,WAAW;AAAA,EACf;AAAA,IACE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,YACE;AAAA,IACF,SAAS;AAAA,EACX;AAAA,EACA;AAAA,IACE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,YACE;AAAA,IACF,SAAS;AAAA,EACX;AAAA,EACA;AAAA,IACE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,YACE;AAAA,IACF,SAAS;AAAA,EACX;AAAA,EACA;AAAA,IACE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,SAAS;AAAA,EACX;AACF;AAEA,WAAW,EAAE,QAAQ,MAAM,WAAW,KAAK,UAAU;AACnD,iBAAe;AAAA,IACb,SAAS,cAAc,MAAM;AAAA,IAC7B,aAAa,uCAAuC,IAAI,KAAK,UAAU;AAAA,IACvE,MAAM;AAAA,MACJ,MAAM,EAAE,MAAM,UAAU,aAAa,eAAe,IAAI,eAAe,UAAU,MAAM;AAAA,MACvF,MAAM,EAAE,MAAM,UAAU,aAAa,gCAAgC,I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AAA,MACpB,MAAM,EAAE,MAAM,UAAU,aAAa,oCAAoC;AAAA,MACzE,MAAM;AAAA,QACJ,OAAO,EAAE,MAAM,UAAU,aAAa,yBAAyB,UAAU,MAAM;AAAA,QAC/E,WAAW,EAAE,MAAM,UAAU,aAAa,2BAA2B,UAAU,MAAM;AAAA,MACvF;AAAA,MACA,KAAK,OAAO,EAAE,KAAK,MAAM;AACvB,cAAM,QAAQ;AAAA,UACZ,MAAM;AAAA,UACN,SAAS,EAAE,MAAM,aAAa,IAA+B,EAAE;AAAA,UAC/D,GAAI,OAAO,KAAK,cAAc,WAAW,EAAE,aAAa,KAAK,UAAU,IAAI,CAAC;AAAA,QAC9E,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,IACD,SAAS,cAAc;AAAA,MACrB,MAAM,EAAE,MAAM,WAAW,aAAa,qCAAqC;AAAA,MAC3E,MAAM;AAAA,QACJ,OAAO,EAAE,MAAM,UAAU,aAAa,yBAAyB,UAAU,MAAM;AAAA,QAC/E,WAAW,EAAE,MAAM,UAAU,aAAa,2BAA2B,UAAU,MAAM;AAAA,MACvF;AAAA,MACA,KAAK,OAAO,EAAE,KAAK,MAAM;AACvB,cAAM,QAAQ;AAAA,UACZ,MAAM;AAAA,UACN,SAAS,EAAE,MAAM,aAAa,IAA+B,EAAE;AAAA,UAC/D,GAAI,OAAO,KAAK,cAAc,WAAW,EAAE,aAAa,KAAK,UAAU,IAAI,CAAC;AAAA,QAC9E,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AACF,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/commands/tag-manager/write-commands.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { loadJsonArg, requireTarget, stageOp } from \"./shared.ts\";\n\n/**\n * Staged write verbs. Each stages one op onto this chat's Tag Manager draft;\n * nothing reaches Tag Manager until the chat is published, and even then it\n * lands in an unpublished container version.\n */\n\n/**\n * A company can connect several containers, and a publish applies to one of\n * them at a time. With more than one connected, a change that does not name its\n * container is refused rather than staged into whichever came first.\n */\nconst CONTAINER_ARG_DESCRIPTION =\n \"Numeric container id (optional only when one container is connected — run `baker tag-manager containers`)\";\n\nconst ENTITIES = [\n {\n entity: \"tag\",\n noun: \"tag\",\n createHint:\n 'Payload needs name + type (e.g. \"gaawe\" for a GA4 event) and usually parameter[] and firingTriggerId[]. Reference a trigger by its numeric id, or by a gtm_temp_* ref if you are staging it in this same chat.',\n example: '{\"name\":\"GA4 - Generate Lead\",\"type\":\"gaawe\",\"firingTriggerId\":[\"gtm_temp_trigger_x_0\"]}',\n },\n {\n entity: \"trigger\",\n noun: \"trigger\",\n createHint:\n 'Payload needs name + type (e.g. \"pageview\", \"click\", \"customEvent\"). Stage the trigger BEFORE the tag that fires on it, then reference it by its gtm_temp_* ref.',\n example: '{\"name\":\"Form - Submit\",\"type\":\"formSubmission\"}',\n },\n {\n entity: \"variable\",\n noun: \"variable\",\n createHint:\n 'Payload needs name + type (e.g. \"v\" for a data layer variable, \"c\" for a constant). Other entities reference a variable by NAME as {{Variable Name}}.',\n example: '{\"name\":\"DL - lead_id\",\"type\":\"v\",\"parameter\":[{\"type\":\"template\",\"key\":\"name\",\"value\":\"lead_id\"}]}',\n },\n {\n entity: \"folder\",\n noun: \"folder\",\n createHint: \"Payload needs name. Use folders to keep a large container legible.\",\n example: '{\"name\":\"Google Ads\"}',\n },\n] as const;\n\nfor (const { entity, noun, createHint } of ENTITIES) {\n registerSchema({\n command: `tagManager.${entity}.create`,\n description: `Stage the creation of a Tag Manager ${noun}. ${createHint} Staged only — applies when the chat completes.`,\n args: {\n json: { type: \"string\", description: `Inline JSON ${noun} definition`, required: false },\n file: { type: \"string\", description: `Path to a JSON file with the ${noun} definition`, required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n });\n registerSchema({\n command: `tagManager.${entity}.update`,\n description: `Stage an update to an existing Tag Manager ${noun}. Pass the ${noun} id or path as the positional argument and the changed fields as JSON. Read the container first so you send the fields you mean to change.`,\n args: {\n json: { type: \"string\", description: \"Inline JSON with the changed fields\", required: false },\n file: { type: \"string\", description: \"Path to a JSON file with the changed fields\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n });\n registerSchema({\n command: `tagManager.${entity}.delete`,\n description: `Stage the deletion of a Tag Manager ${noun}. Pass its id or path as the positional argument. Deleting is irreversible once the resulting version is published — confirm with the user first.`,\n args: {\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n });\n}\n\nfunction entityCommand(entity: (typeof ENTITIES)[number][\"entity\"], noun: string, example: string) {\n return defineCommand({\n meta: { name: entity, description: `Stage ${noun} changes on this chat's Tag Manager draft` },\n subCommands: {\n create: defineCommand({\n meta: {\n name: \"create\",\n description: `Stage a new ${noun}\n\nExamples:\n baker tag-manager ${entity} create --json '${example}'\n baker tag-manager ${entity} create --file ./${entity}.json`,\n },\n args: {\n json: { type: \"string\", description: \"Inline JSON definition\", required: false },\n file: { type: \"string\", description: \"Path to a JSON file\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: `tagManager.${entity}.create`,\n payload: loadJsonArg(args as Record<string, unknown>),\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n update: defineCommand({\n meta: {\n name: \"update\",\n description: `Stage an update to an existing ${noun} (pass its id or path)`,\n },\n args: {\n id: { type: \"positional\", description: `${noun} id or path`, required: false },\n json: { type: \"string\", description: \"Inline JSON with changed fields\", required: false },\n file: { type: \"string\", description: \"Path to a JSON file\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: `tagManager.${entity}.update`,\n target: requireTarget(args as Record<string, unknown>, noun),\n payload: loadJsonArg(args as Record<string, unknown>),\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n delete: defineCommand({\n meta: { name: \"delete\", description: `Stage the deletion of a ${noun} (pass its id or path)` },\n args: {\n id: { type: \"positional\", description: `${noun} id or path`, required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: `tagManager.${entity}.delete`,\n target: requireTarget(args as Record<string, unknown>, noun),\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n },\n });\n}\n\nconst exampleFor = (entity: string) => ENTITIES.find((e) => e.entity === entity)?.example ?? \"{}\";\n\nexport const tagCommand = entityCommand(\"tag\", \"tag\", exampleFor(\"tag\"));\nexport const triggerCommand = entityCommand(\"trigger\", \"trigger\", exampleFor(\"trigger\"));\nexport const variableCommand = entityCommand(\"variable\", \"variable\", exampleFor(\"variable\"));\nexport const folderCommand = entityCommand(\"folder\", \"folder\", exampleFor(\"folder\"));\n\nregisterSchema({\n command: \"tagManager.builtin\",\n description:\n \"Enable or disable Tag Manager built-in variables by type (e.g. clickUrl, pageUrl, formId). Built-in variables must be enabled before a trigger or tag can reference them as {{Click URL}}.\",\n args: {\n types: { type: \"string\", description: \"Comma-separated built-in variable types\", required: true },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n});\n\nfunction builtinTypes(args: Record<string, unknown>): string[] {\n const raw = args.types;\n if (typeof raw !== \"string\" || raw.length === 0) {\n process.stdout.write(\n `${JSON.stringify({ ok: false, error: { code: \"VALIDATION_ERROR\", message: \"pass --types with comma-separated built-in variable types\" } }, null, 2)}\\n`,\n );\n process.exit(1);\n }\n return raw.split(\",\").map((entry) => entry.trim());\n}\n\nexport const builtinCommand = defineCommand({\n meta: {\n name: \"builtin\",\n description: `Enable or disable built-in variables\n\nExamples:\n baker tag-manager builtin enable --types clickUrl,clickText\n baker tag-manager builtin disable --types formId`,\n },\n subCommands: {\n enable: defineCommand({\n meta: { name: \"enable\", description: \"Stage enabling built-in variables\" },\n args: {\n types: { type: \"string\", description: \"Comma-separated types\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: \"tagManager.builtInVariable.enable\",\n payload: { type: builtinTypes(args as Record<string, unknown>) },\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n disable: defineCommand({\n meta: { name: \"disable\", description: \"Stage disabling built-in variables\" },\n args: {\n types: { type: \"string\", description: \"Comma-separated types\", required: false },\n container: { type: \"string\", description: CONTAINER_ARG_DESCRIPTION, required: false },\n },\n run: async ({ args }) => {\n await stageOp({\n kind: \"tagManager.builtInVariable.disable\",\n payload: { type: builtinTypes(args as Record<string, unknown>) },\n ...(typeof args.container === \"string\" ? { containerId: args.container } : {}),\n });\n },\n }),\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAe9B,IAAM,4BACJ;AAEF,IAAM,WAAW;AAAA,EACf;AAAA,IACE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,YACE;AAAA,IACF,SAAS;AAAA,EACX;AAAA,EACA;AAAA,IACE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,YACE;AAAA,IACF,SAAS;AAAA,EACX;AAAA,EACA;AAAA,IACE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,YACE;AAAA,IACF,SAAS;AAAA,EACX;AAAA,EACA;AAAA,IACE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,SAAS;AAAA,EACX;AACF;AAEA,WAAW,EAAE,QAAQ,MAAM,WAAW,KAAK,UAAU;AACnD,iBAAe;AAAA,IACb,SAAS,cAAc,MAAM;AAAA,IAC7B,aAAa,uCAAuC,IAAI,KAAK,UAAU;AAAA,IACvE,MAAM;AAAA,MACJ,MAAM,EAAE,MAAM,UAAU,aAAa,eAAe,IAAI,eAAe,UAAU,MAAM;AAAA,MACvF,MAAM,EAA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AAa;AAAA,IACX,QAAQ,cAAc;AAAA,MACpB,MAAM,EAAE,MAAM,UAAU,aAAa,oCAAoC;AAAA,MACzE,MAAM;AAAA,QACJ,OAAO,EAAE,MAAM,UAAU,aAAa,yBAAyB,UAAU,MAAM;AAAA,QAC/E,WAAW,EAAE,MAAM,UAAU,aAAa,2BAA2B,UAAU,MAAM;AAAA,MACvF;AAAA,MACA,KAAK,OAAO,EAAE,KAAK,MAAM;AACvB,cAAM,QAAQ;AAAA,UACZ,MAAM;AAAA,UACN,SAAS,EAAE,MAAM,aAAa,IAA+B,EAAE;AAAA,UAC/D,GAAI,OAAO,KAAK,cAAc,WAAW,EAAE,aAAa,KAAK,UAAU,IAAI,CAAC;AAAA,QAC9E,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,IACD,SAAS,cAAc;AAAA,MACrB,MAAM,EAAE,MAAM,WAAW,aAAa,qCAAqC;AAAA,MAC3E,MAAM;AAAA,QACJ,OAAO,EAAE,MAAM,UAAU,aAAa,yBAAyB,UAAU,MAAM;AAAA,QAC/E,WAAW,EAAE,MAAM,UAAU,aAAa,2BAA2B,UAAU,MAAM;AAAA,MACvF;AAAA,MACA,KAAK,OAAO,EAAE,KAAK,MAAM;AACvB,cAAM,QAAQ;AAAA,UACZ,MAAM;AAAA,UACN,SAAS,EAAE,MAAM,aAAa,IAA+B,EAAE;AAAA,UAC/D,GAAI,OAAO,KAAK,cAAc,WAAW,EAAE,aAAa,KAAK,UAAU,IAAI,CAAC;AAAA,QAC9E,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AACF,CAAC;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koda-sl/baker-cli",
3
- "version": "0.883.0",
3
+ "version": "0.884.0",
4
4
  "description": "AI-agent-first CLI for interacting with Baker, including the Baker creative canvas.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/tag-manager/shared.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type {\n TagManagerDraftListResponse,\n TagManagerDraftRemoveResponse,\n TagManagerDraftShowResponse,\n TagManagerDraftStageResponse,\n} from \"@baker/api/tag-manager\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { requireChatId, resolveChatId } from \"../../env.ts\";\nimport { isNotConnectedError } from \"../../error-handler.ts\";\nimport { hintLines, splitHints } from \"../ads/hints.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { draftListWhere, requireDraftWhere } from \"../draft-where.ts\";\n\n/**\n * Shared plumbing for the staged Tag Manager commands. Writes NEVER hit the\n * Tag Manager API directly: every command stages an op against this chat's\n * draft, and the whole draft applies when the chat is published — into the\n * container's working workspace, in dependency order, closing with a container\n * version that is published when every change applies cleanly.\n */\n\nexport function failValidation(message: string): never {\n writeJsonEnvelope({ ok: false, error: { code: \"VALIDATION_ERROR\", message } });\n process.exit(1);\n}\n\nexport function requireTarget(args: Record<string, unknown>, entity: string): string {\n const positional = Array.isArray(args._) ? args._[0] : undefined;\n const target = args.id ?? args.target ?? positional;\n if (typeof target !== \"string\" || target.length === 0) {\n failValidation(`pass the ${entity} id or path as the positional argument`);\n }\n return target;\n}\n\n/** `--json '<inline>'` or `--file <path>` → a parsed object. */\nexport function loadJsonArg(args: Record<string, unknown>, flag: \"patch\" | \"json\" = \"json\"): Record<string, unknown> {\n const inline = args[flag];\n const file = args.file;\n const raw =\n typeof file === \"string\" && file.length > 0\n ? readFileSync(file, \"utf8\")\n : typeof inline === \"string\" && inline.length > 0\n ? inline\n : undefined;\n if (raw === undefined) {\n failValidation(`pass --${flag} with inline JSON or --file with a path to a JSON file`);\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n failValidation(`--${flag} must be a JSON object`);\n }\n return parsed as Record<string, unknown>;\n } catch {\n return failValidation(`--${flag} is not valid JSON`);\n }\n}\n\n/**\n * Transient by nature — worth one more go. Saying so is the difference between\n * the agent retrying a blip and abandoning a multi-step job over one. Every\n * other code is a real answer that a second call returns again.\n */\nconst RETRYABLE_CODES = new Set([\"RATE_LIMITED\", \"UNAVAILABLE\", \"INTERNAL_ERROR\", \"NETWORK_ERROR\", \"TIMEOUT\"]);\n\n/**\n * The one error shape for the whole family.\n *\n * Only the 403s raised while resolving the company's container mean \"not\n * connected\", which is why the fix is keyed to the message and not just the\n * status: other 403s are real permission refusals a reconnect cannot fix.\n * `NOT_FOUND` deliberately does NOT trigger the connect form either — it is also\n * what a missing tag returns, and asking the user to reconnect a working\n * connection because a tag id was wrong wastes their time and fixes nothing.\n */\nexport function handleError(err: unknown): never {\n if (err instanceof ApiError) {\n writeJsonEnvelope({\n ok: false,\n error: {\n code: err.code,\n message: err.message,\n ...(err.code === \"UNAUTHORIZED\" || (err.code === \"FORBIDDEN\" && isNotConnectedError(err.code, err.message))\n ? {\n fix: {\n action: \"request_connection\",\n explanation:\n \"Tag Manager is not connected for this company yet, or no container has been picked. Don't send \" +\n \"the user to Settings — call the `request_connection` tool with \" +\n '{ platform: \"google-tag-manager\", reason } and they connect and pick their containers (they can ' +\n \"pick more than one) from inside the chat. `request_tag_input` is not the route: that form \" +\n \"manages the container snippet on the \" +\n \"site, not what runs inside the container, and it cannot pick a container. If the \" +\n \"`request_connection` call fails, say so plainly and give the exact route: dashboard → Brain → \" +\n \"Integrations → Platforms → Google Tag Manager, where they also pick the container. Then carry on \" +\n \"with the rest of the task.\",\n },\n }\n : {}),\n retryable: RETRYABLE_CODES.has(err.code),\n },\n });\n process.exit(1);\n }\n writeJsonEnvelope({ ok: false, error: { code: \"NETWORK_ERROR\", message: \"Unexpected error\", retryable: true } });\n process.exit(1);\n}\n\n/**\n * Tag Manager allows Baker a few requests a second across every company, so a\n * call that reads the container can queue behind another company's publish. It\n * still finishes on the server, so giving up early only invites a repeat.\n */\nexport const TAG_MANAGER_TIMEOUT_MS = 180_000;\n\n/** Nudges returned after a stage so the agent's next step is obvious. */\nconst STAGE_HINTS = [\n \"Staged only — nothing has changed in Tag Manager yet. These apply when the chat completes, in dependency \" +\n \"order, and close as a Tag Manager version that is then published, so they do go live on the user's site. \" +\n \"Say the changes are ready and go live when they publish — not that they are live already.\",\n];\n\nexport async function stageOp(op: Record<string, unknown>): Promise<void> {\n const chatId = requireChatId();\n try {\n const { data, hints } = splitHints(\n await apiPost<TagManagerDraftStageResponse>(\n \"/api/tag-manager/draft/stage\",\n { chatId, op },\n { timeoutMs: TAG_MANAGER_TIMEOUT_MS },\n ),\n );\n writeJsonEnvelope({ ok: true, data, hints: [...hints, ...STAGE_HINTS] });\n } catch (err) {\n handleError(err);\n }\n}\n\nexport async function draftAction(\n path: string,\n body: Record<string, unknown>,\n chat?: unknown,\n): Promise<TagManagerDraftRemoveResponse | TagManagerDraftShowResponse | Record<string, unknown>> {\n const chatId = resolveChatId(chat);\n try {\n const { data, hints } = splitHints(\n await apiPost<Record<string, unknown>>(path, { chatId, ...body }, { timeoutMs: TAG_MANAGER_TIMEOUT_MS }),\n );\n writeJsonEnvelope({ ok: true, data, ...(hints.length > 0 ? { hints } : {}) });\n return data;\n } catch (err) {\n handleError(err);\n }\n}\n\n/** A compact, readable view of everything staged on this chat. */\nexport function renderDraft(response: TagManagerDraftListResponse): string {\n if (response.count === 0) {\n return \"No Tag Manager changes staged on this chat.\";\n }\n const lines = [\n response.status === \"discarded\"\n ? `${response.count} Tag Manager change(s) discarded with their chat — none will apply`\n : `${response.count} staged Tag Manager change(s)`,\n ...response.ops.flatMap((op) => {\n const status = op.result ? ` [${op.result.status}]` : \"\";\n return [` ${op.ref} ${op.summary}${status}`, ...(op.warnings ?? []).map((warning) => ` ⚠ ${warning}`)];\n }),\n ];\n if (response.versionId) {\n lines.push(\n \"\",\n response.published\n ? `Applied and published as Tag Manager version ${response.versionId}. These changes are live on the site.`\n : `Applied into Tag Manager version ${response.versionId}. It is NOT published — publish it in Tag Manager to go live.`,\n );\n }\n if (response.compilerError) {\n lines.push(\"\", `Tag Manager reported a problem building the version: ${response.compilerError}`);\n }\n return lines.join(\"\\n\");\n}\n\nexport async function draftList(json: boolean, chat?: unknown, full = false, selector?: string): Promise<void> {\n const where = selector === undefined ? undefined : requireDraftWhere(selector, \"tagManager.\");\n const chatId = resolveChatId(chat);\n try {\n const response = await apiPost<TagManagerDraftListResponse>(\"/api/tag-manager/draft\", {\n chatId,\n ...(full || where ? { full: true } : {}),\n });\n const { data, hints } = splitHints(response);\n if (where && selector !== undefined) {\n const narrowed = draftListWhere(data, where, selector);\n const all = [...hints, ...narrowed.hints];\n writeJsonEnvelope({ ok: true, data: narrowed.data, ...(all.length > 0 ? { hints: all } : {}) });\n return;\n }\n if (json || full) {\n writeJsonEnvelope({ ok: true, data, ...(hints.length > 0 ? { hints } : {}) });\n return;\n }\n process.stdout.write(`${renderDraft(data)}${hintLines(response)}\\n`);\n } catch (err) {\n handleError(err);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAsBtB,SAAS,eAAe,SAAwB;AACrD,oBAAkB,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,oBAAoB,QAAQ,EAAE,CAAC;AAC7E,UAAQ,KAAK,CAAC;AAChB;AAEO,SAAS,cAAc,MAA+B,QAAwB;AACnF,QAAM,aAAa,MAAM,QAAQ,KAAK,CAAC,IAAI,KAAK,EAAE,CAAC,IAAI;AACvD,QAAM,SAAS,KAAK,MAAM,KAAK,UAAU;AACzC,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,GAAG;AACrD,mBAAe,YAAY,MAAM,wCAAwC;AAAA,EAC3E;AACA,SAAO;AACT;AAGO,SAAS,YAAY,MAA+B,OAAyB,QAAiC;AACnH,QAAM,SAAS,KAAK,IAAI;AACxB,QAAM,OAAO,KAAK;AAClB,QAAM,MACJ,OAAO,SAAS,YAAY,KAAK,SAAS,IACtC,aAAa,MAAM,MAAM,IACzB,OAAO,WAAW,YAAY,OAAO,S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SAAO,MAAM,KAAK,IAAI;AACxB;AAEA,eAAsB,UAAU,MAAe,MAAgB,OAAO,OAAO,UAAkC;AAC7G,QAAM,QAAQ,aAAa,SAAY,SAAY,kBAAkB,UAAU,aAAa;AAC5F,QAAM,SAAS,cAAc,IAAI;AACjC,MAAI;AACF,UAAM,WAAW,MAAM,QAAqC,0BAA0B;AAAA,MACpF;AAAA,MACA,GAAI,QAAQ,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;AAAA,IACxC,CAAC;AACD,UAAM,EAAE,MAAM,MAAM,IAAI,WAAW,QAAQ;AAC3C,QAAI,SAAS,aAAa,QAAW;AACnC,YAAM,WAAW,eAAe,MAAM,OAAO,QAAQ;AACrD,YAAM,MAAM,CAAC,GAAG,OAAO,GAAG,SAAS,KAAK;AACxC,wBAAkB,EAAE,IAAI,MAAM,MAAM,SAAS,MAAM,GAAI,IAAI,SAAS,IAAI,EAAE,OAAO,IAAI,IAAI,CAAC,EAAG,CAAC;AAC9F;AAAA,IACF;AACA,QAAI,QAAQ,MAAM;AAChB,wBAAkB,EAAE,IAAI,MAAM,MAAM,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC,EAAG,CAAC;AAC5E;AAAA,IACF;AACA,YAAQ,OAAO,MAAM,GAAG,YAAY,IAAI,CAAC,GAAG,UAAU,QAAQ,CAAC;AAAA,CAAI;AAAA,EACrE,SAAS,KAAK;AACZ,gBAAY,GAAG;AAAA,EACjB;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/ads/google/draft-account.ts","../src/commands/ads/google/write-shared.ts","../src/commands/ads/google/copy-list-usage.ts","../src/commands/ads/google/draft-status.ts","../src/commands/ads/google/stage-streak.ts"],"sourcesContent":["import type { GoogleDraftListResponse } from \"@baker/api/ads-google\";\n\n/**\n * `--customer-id` on the draft reads. A draft belongs to the chat, not to an account, and may span\n * several; every other Google Ads command takes the flag, so agents carry it here (BAKER-497).\n * `list` narrows to that account and says what the others still hold; `validate` and `show` keep\n * their whole answer, because publish sends every account together and a ref names one op.\n */\n\nfunction changes(n: number, staged: boolean): string {\n const noun = staged ? \"staged change\" : \"change\";\n return n === 1 ? `1 ${noun}` : `${n} ${noun}s`;\n}\n\n/**\n * The draft as one account holds it, with what the rest of the chat's draft holds. `empty` is the\n * readable line for an account holding none of it, where the whole-chat \"nothing staged\" would be false.\n * Only an active draft's other changes are still to publish; a published one's are already done.\n */\nexport function draftInAccount(\n data: GoogleDraftListResponse,\n customerId: string,\n): { data: GoogleDraftListResponse; hints: string[]; empty?: string } {\n const ops = data.ops.filter((op) => op.customerId === customerId);\n const narrowed = {\n ...data,\n count: ops.length,\n ops,\n ...(data.tree ? { tree: data.tree.filter((node) => node.customerId === customerId) } : {}),\n };\n const others = data.ops.filter((op) => op.customerId !== customerId);\n if (others.length === 0) return { data: narrowed, hints: [] };\n const staged = data.status === \"active\";\n const accounts = [...new Set(others.map((op) => op.customerId))];\n const where = `account${accounts.length === 1 ? \"\" : \"s\"} ${accounts.join(\", \")}`;\n const one = others.length === 1;\n if (ops.length === 0) {\n return {\n data: narrowed,\n empty: `No Google Ads changes in account ${customerId} on this chat.`,\n hints: [`This chat's ${changes(others.length, staged)} ${one ? \"is\" : \"are\"} in ${where}, not ${customerId}.`],\n };\n }\n const more = `${others.length} more ${staged ? \"staged \" : \"\"}change${one ? \"\" : \"s\"}`;\n const verb = staged ? (one ? \"publishes\" : \"publish\") : one ? \"is\" : \"are\";\n return {\n data: narrowed,\n hints: [\n `Showing account ${customerId} only. ${more} in ${where} ${verb} ${staged ? \"with this chat too\" : \"on this chat too\"}; \\`baker ads google draft list\\` without --customer-id shows ${one ? \"it\" : \"them\"}.`,\n ],\n };\n}\n\n/** `draft validate --customer-id`: said back, since the verdicts still cover every account. */\nexport function validateAccountHint(customerId: string): string {\n return `Validated this chat's whole draft, not only account ${customerId}: publish sends every account's changes together, so each verdict above counts.`;\n}\n\n/** `draft show --customer-id` naming another account than the op's own. */\nexport function showAccountHint(customerId: string, opCustomerId: string): string | undefined {\n return opCustomerId === customerId ? undefined : `This op is staged in account ${opCustomerId}, not ${customerId}.`;\n}\n","import { readFileSync } from \"node:fs\";\nimport {\n GOOGLE_DRAFT_BATCH_MAX,\n type GoogleDraftListResponse,\n type GoogleDraftOpKind,\n type GoogleDraftStageBatchResponse,\n type GoogleDraftStageResponse,\n googleDraftBatchOpSchema,\n googleDraftOpInputSchema,\n OP_TOO_LARGE_FIX,\n OP_TOO_LARGE_MESSAGE_START,\n toMicros,\n} from \"@baker/api/ads-google\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiPost } from \"../../../client.ts\";\nimport { requireChatId, resolveChatId } from \"../../../env.ts\";\nimport { handleConnectionError, isNotConnectedError } from \"../../../error-handler.ts\";\nimport { repeatedValues } from \"../../../lib/repeatedFlags.ts\";\nimport { type CommandEffectDeclaration, type PayloadSource, payloadArg, withEffect } from \"../../../schemas.ts\";\nimport { payloadFix } from \"../../capabilities/fix.ts\";\nimport { type DraftWhere, draftListWhere, wholeDraftHints } from \"../../draft-where.ts\";\nimport { booleanWordPositionalError } from \"../boolean-word-positional.ts\";\nimport { adCopyHints } from \"../copy-hints.ts\";\nimport { hintLines, withHints } from \"../hints.ts\";\nimport { bareCustomerId, writeJsonEnvelope } from \"../output.ts\";\nimport { termsRefusalFix } from \"../terms-output.ts\";\nimport { copyListCountFix } from \"./copy-list-usage.ts\";\nimport { draftInAccount } from \"./draft-account.ts\";\nimport { renderDraftStatus } from \"./draft-status.ts\";\nimport { recordSingleStage, recordTreeStage } from \"./stage-streak.ts\";\n\n/**\n * Shared plumbing for the staged Google Ads write commands. Writes NEVER hit\n * the Google Ads API directly: every command stages an op against this chat's\n * draft (`/api/ads/google/draft/stage`), the dashboard shows it as a pending\n * Google Ads change, and the draft applies as one `GoogleAdsService.Mutate`\n * request per advertiser account when the chat is published. `--customer-id` is\n * required on every write — a draft may span several accounts, so nothing is\n * picked for you.\n */\n\n/** What a staged Google Ads write command does: one op of these kinds onto this chat's draft. */\nexport function googleStaged(...kinds: GoogleDraftOpKind[]): CommandEffectDeclaration {\n return { effect: \"stage\", routes: [\"POST /api/ads/google/draft/stage\"], stages: kinds };\n}\n\n/** A staged write that takes one op or many: several go as one batch (`stageGoogleOps`). */\nexport function googleStagedBatch(...kinds: GoogleDraftOpKind[]): CommandEffectDeclaration {\n return {\n effect: \"stage\",\n routes: [\"POST /api/ads/google/draft/stage\", \"POST /api/ads/google/draft/stage-batch\"],\n stages: kinds,\n };\n}\n\nexport function failWriteValidation(message: string): never {\n writeJsonEnvelope({ ok: false, error: { code: \"VALIDATION_ERROR\", message } });\n process.exit(1);\n}\n\nexport function requireCustomerId(args: Record<string, unknown>): string {\n const given = (args[\"customer-id\"] ?? args.customerId) as string | undefined;\n const raw = given === undefined ? undefined : bareCustomerId(String(given));\n if (!raw || !/^\\d{10}$/.test(raw)) {\n failWriteValidation(\"pass --customer-id as the 10-digit Google Ads customer id (386-508-3115 or 3865083115)\");\n }\n return raw;\n}\n\nexport function requireTarget(args: Record<string, unknown>, entity: string): string {\n // `--flag false` is refused, not documented: citty parses it as the flag set to TRUE plus a stray\n // positional nobody consumes, so on `conversions update --primary` it silently PROMOTES an action\n // into what every Maximize Conversions campaign bids toward. Caught here because this is the only\n // place on this surface that reads positionals, and every target-taking command goes through it.\n const booleanWord = booleanWordPositionalError(args, entity);\n if (booleanWord) {\n failWriteValidation(booleanWord);\n }\n const positional = Array.isArray(args._) ? args._[0] : undefined;\n const target = args.id ?? args.target ?? args.ref ?? positional;\n if (typeof target !== \"string\" || target.length === 0) {\n failWriteValidation(`pass the ${entity} resource name or id as the positional argument`);\n }\n return target;\n}\n\n/**\n * The targets a bulk status command was given: every positional (comma-separated ones split), plus\n * `--file` with one target per line (blank lines and `#` comments skipped), deduped in order. One\n * call then stages them all as one batch instead of one command per row.\n */\nexport function targetEntries(args: Record<string, unknown>, entity: string): string[] {\n const booleanWord = booleanWordPositionalError(args, entity);\n if (booleanWord) {\n failWriteValidation(booleanWord);\n }\n const positionals = Array.isArray(args._) ? args._.filter((v): v is string => typeof v === \"string\") : [];\n const raw = [...positionals.flatMap((v) => v.split(\",\")), ...rawFileEntries(args.file)]\n .map((v) => v.trim())\n .filter(Boolean);\n const targets = [...new Set(raw)];\n if (targets.length === 0) {\n failWriteValidation(`pass the ${entity} resource name(s) as positional arguments and/or --file (one per line)`);\n }\n if (targets.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(`${targets.length} targets exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX} — split them`);\n }\n return targets;\n}\n\n/**\n * The targets an update command was given: one, or several (space- or comma-separated) that each get\n * the same payload, staged as one batch. `--file` here is the payload, never a list of targets.\n */\nexport function updateTargets(args: Record<string, unknown>, entity: string): string[] {\n return Array.isArray(args._) && args._.length > 0\n ? targetEntries({ ...args, file: undefined }, entity)\n : [requireTarget(args, entity)];\n}\n\nexport function requireStringFlag(value: unknown, flag: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n failWriteValidation(`${flag} is required`);\n }\n return value;\n}\n\n/** Money flag in major currency units → micros. */\nexport function microsFlag(value: unknown, flag: string): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const num = Number(value);\n if (Number.isNaN(num) || num <= 0) {\n failWriteValidation(`${flag} must be a positive amount (major currency units, e.g. 50 or 50.00)`);\n }\n return toMicros(num);\n}\n\n/** Split a comma-separated flag into trimmed non-empty values. */\nexport function listFlag(value: unknown): string[] | undefined {\n if (typeof value !== \"string\" || value.length === 0) {\n return undefined;\n }\n const items = value\n .split(\",\")\n .map((v) => v.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\nexport interface KeywordEntry {\n text: string;\n matchType: string;\n}\n\nconst MATCH_TYPES = new Set([\"EXACT\", \"PHRASE\", \"BROAD\"]);\n\n/**\n * One raw keyword entry → { text, matchType }. A trailing `:EXACT|:PHRASE|:BROAD`\n * suffix overrides the default match type; colons and commas aren't legal in Google\n * keyword text, so the syntax is unambiguous.\n */\nfunction parseKeywordEntry(raw: string, defaultMatch: string | undefined): KeywordEntry {\n const colon = raw.lastIndexOf(\":\");\n if (colon > 0) {\n const suffix = raw\n .slice(colon + 1)\n .trim()\n .toUpperCase();\n if (MATCH_TYPES.has(suffix)) {\n return { text: raw.slice(0, colon).trim(), matchType: suffix };\n }\n failWriteValidation(`\"${raw}\": \":${raw.slice(colon + 1)}\" is not a match type (EXACT | PHRASE | BROAD)`);\n }\n if (!defaultMatch) {\n failWriteValidation(`\"${raw}\" has no match type — add a :EXACT/:PHRASE/:BROAD suffix or pass --match-type`);\n }\n return { text: raw, matchType: defaultMatch };\n}\n\n/**\n * Raw --text value(s) → individual entries: repeated flags and comma-separated\n * both work. The repeats have to come off `rawArgs`, because citty parses a\n * repeated flag down to its last value alone.\n */\nfunction rawTextEntries(value: unknown, rawArgs: readonly string[] | undefined): string[] {\n return repeatedValues(rawArgs, \"text\", value)\n .flatMap((v) => v.split(\",\"))\n .map((v) => v.trim())\n .filter(Boolean);\n}\n\n/** Newline-separated keyword file: one `text[:MATCH_TYPE]` per line; blank lines and `#` comments skipped. */\nfunction rawFileEntries(path: unknown): string[] {\n return typeof path === \"string\" && path.length > 0 ? fileLines(path) : [];\n}\n\n/** A text file's entries: one per line, trimmed; blank lines and `#` comments skipped. */\nexport function fileLines(path: string): string[] {\n return readFileSync(path, \"utf8\")\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith(\"#\"));\n}\n\n/**\n * The keyword batch a command was invoked with: comma-separated `--text` entries\n * (optional `:MATCH_TYPE` suffix each) plus `--file` lines, deduped, each falling\n * back to `--match-type`. One entry stages exactly like before; many stage as one batch.\n */\nexport function keywordEntries(args: Record<string, unknown>, rawArgs?: readonly string[]): KeywordEntry[] {\n const defaultMatch = typeof args[\"match-type\"] === \"string\" ? args[\"match-type\"].toUpperCase() : undefined;\n const raw = [...rawTextEntries(args.text, rawArgs), ...rawFileEntries(args.file)];\n if (raw.length === 0) {\n failWriteValidation(\"pass keywords via --text (comma-separated) and/or --file (one per line)\");\n }\n if (raw.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(`${raw.length} keywords exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX}`);\n }\n const entries: KeywordEntry[] = [];\n const seen = new Set<string>();\n for (const item of raw) {\n const entry = parseKeywordEntry(item, defaultMatch);\n const key = JSON.stringify([entry.text, entry.matchType]);\n if (!seen.has(key)) {\n seen.add(key);\n entries.push(entry);\n }\n }\n return entries;\n}\n\n/**\n * The payloads behind `--file`: a path to a JSON file, or the JSON written inline. The file holds one\n * payload object, a JSON array of them, or JSON Lines (one object per line) — many payloads stage as\n * one batch, which is how a bulk change lands in one call instead of hundreds.\n *\n * Inline is here because every doc example already writes it that way — `packages/cli/README.md`\n * and the scaffold's `ads-google.md` both show `--file '{\"type\":\"image\",…}'` — while the arg only\n * ever read a path, so following the documentation answered with a raw ENOENT stack trace. Reading\n * a leading `{` or `[` as the payload makes those examples true rather than making the agent re-learn\n * the one shape that works.\n */\nexport function loadJsonPayloads(path: unknown): Array<Record<string, unknown>> {\n if (typeof path !== \"string\" || path.length === 0) {\n return [];\n }\n const inline = /^\\s*[[{]/.test(path);\n const source = inline ? \"inline JSON\" : path;\n const text = inline ? path : readFileSync(path, \"utf8\");\n return parsedPayloads(text, source).map((item, index, all) => {\n if (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n failWriteValidation(\n all.length === 1 ? `${source} must contain a JSON object` : `${source}: item ${index} must be a JSON object`,\n );\n }\n return item as Record<string, unknown>;\n });\n}\n\n/** One JSON value (an array spreads into its items), else JSON Lines; the JSON error when neither parses. */\nfunction parsedPayloads(text: string, source: string): unknown[] {\n try {\n const parsed = JSON.parse(text) as unknown;\n return Array.isArray(parsed) ? parsed : [parsed];\n } catch (err) {\n if (!(err instanceof SyntaxError)) {\n throw err;\n }\n const lines = text.split(/\\r?\\n/).filter((line) => line.trim().length > 0);\n if (lines.length > 1) {\n return lines.map((line, index) => parseJsonLine(line, index, source));\n }\n failWriteValidation(`${source} is not valid JSON: ${err.message}`);\n }\n}\n\n/** One JSON Lines entry, or the line's own error naming where it is. */\nfunction parseJsonLine(line: string, index: number, source: string): unknown {\n try {\n return JSON.parse(line) as unknown;\n } catch (err) {\n return failWriteValidation(\n `${source} line ${index + 1} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/** The ONE op payload behind `--file`, for commands that change a single entity. */\nexport function loadJsonFileArg(path: unknown): Record<string, unknown> {\n const payloads = loadJsonPayloads(path);\n if (payloads.length > 1) {\n failWriteValidation(\n `this command changes one entity, and --file holds ${payloads.length} payloads — stage many changes from one file with \\`baker ads google draft stage --file\\` (one op per item: {\"kind\",\"customerId\",\"target\"?,\"payload\"?})`,\n );\n }\n return payloads[0] ?? {};\n}\n\n/** Flags override file keys — the file is the base, flags are the overrides. */\nexport function mergePayload(file: Record<string, unknown>, flags: Record<string, unknown>): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...file };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\n/**\n * The `draft amend` patch: exactly one of `--file <path>` (JSON file) or `--patch '<json>'`\n * (inline string), and it must parse to a JSON object — RFC-7386 merge-patch needs an object to\n * merge, and a stray array/scalar would silently no-op or replace the whole payload.\n */\nexport function loadPatchArg(args: Record<string, unknown>): Record<string, unknown> {\n const file = typeof args.file === \"string\" && args.file.length > 0 ? args.file : undefined;\n const inline = typeof args.patch === \"string\" && args.patch.length > 0 ? args.patch : undefined;\n if (Boolean(file) === Boolean(inline)) {\n failWriteValidation(\"pass exactly one of --file <patch.json> or --patch '<json>'\");\n }\n if (file) {\n return loadJsonFileArg(file);\n }\n try {\n const parsed = JSON.parse(inline as string) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n failWriteValidation(\"--patch must be a JSON object\");\n }\n return parsed as Record<string, unknown>;\n } catch (err) {\n if (err instanceof SyntaxError) {\n failWriteValidation(`--patch is not valid JSON: ${err.message}`);\n }\n throw err;\n }\n}\n\nexport function handleGoogleError(err: unknown): never {\n if (err instanceof ApiError) {\n // Covers both \"no connection\" and staging's 403 for an account this company\n // never connected — same remedy either way: connect, and pick the account.\n if (isNotConnectedError(err.code, err.message)) {\n handleConnectionError(\"google_ads\", err.message);\n }\n const terms = termsRefusalFix(err.code, err.message);\n if (terms) {\n writeJsonEnvelope({\n ok: false,\n error: { code: terms.code, message: err.message, retryable: false, fix: terms.fix },\n });\n process.exit(1);\n }\n if (err.message.includes(OP_TOO_LARGE_MESSAGE_START)) {\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"OP_TOO_LARGE\",\n message: err.message,\n retryable: false,\n fix: { action: \"split_the_change\", explanation: OP_TOO_LARGE_FIX },\n },\n });\n process.exit(1);\n }\n writeJsonEnvelope({ ok: false, error: { code: err.code ?? \"API_ERROR\", message: err.message } });\n process.exit(1);\n }\n writeJsonEnvelope({\n ok: false,\n error: { code: \"UNKNOWN\", message: err instanceof Error ? err.message : String(err) },\n });\n process.exit(1);\n}\n\ninterface StageEnvelope extends Record<string, unknown> {\n ok: true;\n data: GoogleDraftStageResponse;\n}\n\n/**\n * A no-op response isn't a failure — the change was already in place, so nothing was\n * staged. Say so explicitly, otherwise the agent re-stages it or reports work it\n * didn't do.\n */\nfunction noopHints(data: GoogleDraftStageResponse): string[] {\n return data.staged\n ? []\n : [`NOT STAGED — ${data.reason}. Nothing to publish for this change; say so rather than reporting it as done.`];\n}\n\n/**\n * What to tell the agent about the ops a batch didn't stage.\n *\n * Two different things land in `skipped`: a change already in place, and a change Google refuses\n * outright (editing an experiment campaign's status, dates or budget). This hint used to assert the\n * first — \"already in the requested state\" — which read as \"done\" for a refusal the user never heard\n * about. So it leads with each op's own reason and asks for the refusals to be passed on.\n */\nexport function skippedHints(skipped: Array<{ summary: string; reason: string }>, total: number): string[] {\n if (skipped.length === 0) {\n return [];\n }\n const detail = skipped.map((s) => `${s.summary} — ${s.reason}`).join(\"; \");\n return [\n `${skipped.length} of ${total} op(s) NOT STAGED: ${detail}. Don't re-stage them; tell the user which changes couldn't be made and why, then carry on with the rest.`,\n ];\n}\n\n/**\n * Preflight-validates the op against the shared `@baker/api/ads-google`\n * contract (the same schema the backend enforces), then stages it. Prints the\n * staged envelope — ref, mode (always `live`: publishing reaches the real\n * account), summary, warnings.\n */\nexport async function stageGoogleOp(raw: Record<string, unknown>, hints?: string[]): Promise<void> {\n const preflight = googleDraftOpInputSchema.safeParse(raw);\n if (!preflight.success) {\n const fields = preflight.error.issues.map((issue) => ({ path: issue.path.join(\".\"), message: issue.message }));\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: fields.map((f) => (f.path ? `${f.path}: ${f.message}` : f.message)).join(\"; \"),\n fields,\n fix: copyListCountFix(raw, preflight.error.issues) ?? payloadFix(\"google-ads\", googleDraftOpInputSchema, raw),\n },\n });\n process.exit(1);\n }\n try {\n const chatId = requireChatId();\n const response = await apiPost<StageEnvelope>(\"/api/ads/google/draft/stage\", { chatId, op: preflight.data });\n const allHints = [\n ...noopHints(response.data),\n ...recordSingleStage(chatId, preflight.data.kind),\n ...recordTreeStage(chatId, response.data),\n ...(hints ?? []),\n ...(await adCopyHints(preflight.data)),\n ];\n writeJsonEnvelope(withHints(response, allHints));\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\n/** Stage a create op: `{ kind, customerId, payload }`. */\nexport async function stageCreate(\n kind: string,\n customerId: string,\n payload: Record<string, unknown>,\n hints?: string[],\n): Promise<void> {\n await stageGoogleOp({ kind, customerId, payload }, hints);\n}\n\ninterface StageBatchEnvelope extends Record<string, unknown> {\n ok: true;\n data: GoogleDraftStageBatchResponse;\n}\n\n/**\n * A batch reads every target's before-state and checks each op against the account, which for a few\n * hundred removals outlasts the default 60 s. Timing out early reported a batch as failed that went on\n * to stage, so a retry then collided with the ops it had already staged.\n */\nconst STAGE_BATCH_TIMEOUT_MS = 5 * 60_000;\n\n/** `--full` on every command that stages a batch: the compact result lists only the ops that need a look. */\nexport const STAGE_FULL_ARG = {\n type: \"boolean\",\n description:\n \"List every staged op with its ref and summary (default: counts, the `as` → ref names, and only the ops with warnings)\",\n} as const;\n\n/**\n * What a batch stage prints by default: counts by kind, the ref each `\"as\"` name became (later calls\n * name the ref), and only the ops that carry a warning. A batch of 384 negatives printed one object\n * per op — 85 KB of the agent's own input echoed back with `\"warnings\": []` — so agents cut it with\n * `head`, which also cuts a late op's warning and the hints (BAKER-4005, BAKER-3464).\n */\nfunction stageBatchView(\n data: GoogleDraftStageBatchResponse,\n full: boolean,\n): GoogleDraftStageBatchResponse & { byKind?: Record<string, number>; refs?: Record<string, string> } {\n if (full) {\n return data;\n }\n const { ops, ...rest } = data;\n const byKind: Record<string, number> = {};\n const refs: Record<string, string> = {};\n for (const op of ops) {\n byKind[op.kind] = (byKind[op.kind] ?? 0) + 1;\n if (op.as) refs[op.as] = op.ref;\n }\n return {\n ...rest,\n byKind,\n ...(Object.keys(refs).length > 0 ? { refs } : {}),\n ops: ops.filter((op) => op.warnings.length > 0),\n };\n}\n\n/**\n * Stage several ops as ONE request (`/stage-batch`) — all-or-nothing on the backend,\n * one rate-limit hit instead of one per keyword. A single op falls through to the\n * plain stage path so its envelope (and amend behavior) stays exactly as before.\n * Prints `stageBatchView`: compact unless `full`.\n */\nexport async function stageGoogleOps(\n rawOps: Array<Record<string, unknown>>,\n hints?: string[],\n full = false,\n): Promise<void> {\n if (rawOps.length === 1 && rawOps[0]) {\n await stageGoogleOp(rawOps[0], hints);\n return;\n }\n const ops: unknown[] = [];\n for (const [index, raw] of rawOps.entries()) {\n const preflight = googleDraftBatchOpSchema.safeParse(raw);\n if (!preflight.success) {\n const fields = preflight.error.issues.map((issue) => ({\n path: `ops[${index}].${issue.path.join(\".\")}`,\n message: issue.message,\n }));\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: fields.map((f) => `${f.path}: ${f.message}`).join(\"; \"),\n fields,\n fix: copyListCountFix(raw, preflight.error.issues) ?? payloadFix(\"google-ads\", googleDraftOpInputSchema, raw),\n },\n });\n process.exit(1);\n }\n ops.push(preflight.data);\n }\n try {\n const chatId = requireChatId();\n const response = await apiPost<StageBatchEnvelope>(\n \"/api/ads/google/draft/stage-batch\",\n { chatId, ops },\n { timeoutMs: STAGE_BATCH_TIMEOUT_MS },\n );\n const view = stageBatchView(response.data, full);\n const omitted = response.data.ops.length - view.ops.length;\n const allHints = [\n ...skippedHints(response.data.skipped ?? [], ops.length),\n ...(omitted > 0\n ? [\n `${omitted} staged ops without a warning are left out. They are already staged — do not stage them again; read their refs with \\`baker ads google draft list --json\\` (pass --full on a later stage to print every op).`,\n ]\n : []),\n ...(hints ?? []),\n ...(await adCopyHints(ops)),\n ];\n writeJsonEnvelope(withHints({ ...response, data: view }, allHints));\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\n/** Stage an update op: `{ kind, customerId, target, payload }`. */\nexport async function stageUpdate(\n kind: string,\n customerId: string,\n target: string,\n payload: Record<string, unknown>,\n hints?: string[],\n): Promise<void> {\n await stageGoogleOp({ kind, customerId, target, payload }, hints);\n}\n\n/** Stage a target-only op (pause/resume/remove/detach): `{ kind, customerId, target }`. */\nexport async function stageTarget(kind: string, customerId: string, target: string, hints?: string[]): Promise<void> {\n await stageGoogleOp({ kind, customerId, target }, hints);\n}\n\nexport async function draftAction(path: string, body: Record<string, unknown>, chat?: unknown): Promise<void> {\n try {\n const chatId = resolveChatId(chat);\n const response = await apiPost<Record<string, unknown>>(path, { chatId, ...body });\n writeJsonEnvelope(response);\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\ninterface DraftListEnvelope extends Record<string, unknown> {\n ok: boolean;\n data?: GoogleDraftListResponse;\n}\n\n/**\n * List the staged draft. By default renders a readable campaign ▸ ad group ▸ ad status tree so the\n * agent can review everything it has staged at a glance; `--json` returns the raw envelope for tools,\n * and `--full` that envelope with every op's payload.\n */\nexport async function draftListAction(\n json: boolean,\n chat?: unknown,\n full = false,\n customerId?: string,\n selected?: { where: DraftWhere; selector: string },\n): Promise<void> {\n try {\n const chatId = resolveChatId(chat);\n const listed = await apiPost<DraftListEnvelope>(\"/api/ads/google/draft\", {\n chatId,\n ...(full || selected ? { full: true } : {}),\n });\n const inAccount =\n customerId !== undefined && listed.ok && listed.data ? draftInAccount(listed.data, customerId) : undefined;\n const response = inAccount ? withHints({ ...listed, data: inAccount.data }, inAccount.hints) : listed;\n if (selected && response.ok && response.data) {\n const narrowed = draftListWhere(response.data, selected.where, selected.selector);\n writeJsonEnvelope(withHints({ ...response, data: narrowed.data }, narrowed.hints));\n return;\n }\n if (json || full || !response.ok || !response.data) {\n const whole =\n response.ok && response.data\n ? wholeDraftHints(response.data.ops, \"baker ads google draft list\", \"google.\")\n : [];\n writeJsonEnvelope(withHints(response, whole));\n return;\n }\n process.stdout.write(`${inAccount?.empty ?? renderDraftStatus(response.data)}${hintLines(response)}\\n`);\n } catch (err) {\n handleGoogleError(err);\n }\n}\n\nexport const customerIdArg = {\n \"customer-id\": { type: \"string\" as const, description: \"10-digit Google Ads customer id\" },\n};\n/** The entity a command changes, read by position the way `requireTarget` reads it — declared so --help shows it. */\nexport function targetArg(entity: string) {\n return {\n id: {\n type: \"positional\" as const,\n description: `The ${entity} to change: its id or resource name (customers/…)`,\n required: false,\n },\n };\n}\n\nconst PAYLOAD_FIELDS = \"run `baker schema` on this command for every field the payload takes\";\n\nfunction payloadShape(kind: string): () => PayloadSource {\n return () => ({ union: googleDraftOpInputSchema, kind });\n}\n\n/** `--file` for a command that stages one `kind` op; `baker schema` prints that op's payload shape. */\nexport function fileArg(kind: string) {\n return {\n file: payloadArg(\n {\n type: \"string\" as const,\n description: `The op payload: a JSON file path, or the JSON object inline (flags override it) — ${PAYLOAD_FIELDS}`,\n },\n payloadShape(kind),\n ),\n };\n}\n\n/** `--file` that stages one or many `kind` ops; `baker schema` prints that op's payload shape. */\nexport function fileBatchArg(kind: string) {\n return {\n file: payloadArg(\n {\n type: \"string\" as const,\n description: `The op payload: a JSON file path or inline JSON — one object, or a JSON array / JSON Lines of objects to stage many in one call (up to 500) — ${PAYLOAD_FIELDS}`,\n },\n payloadShape(kind),\n ),\n };\n}\n\n/** A create command whose payload is a JSON file or inline JSON — one object or an array staged as one batch. */\nexport function fileCreateCommand(\n name: string,\n kind: GoogleDraftOpKind,\n description: string,\n hints?: string[] | ((payload: Record<string, unknown>) => string[]),\n) {\n return withEffect(\n googleStagedBatch(kind),\n defineCommand({\n meta: { name, description },\n args: { ...customerIdArg, ...fileBatchArg(kind), full: STAGE_FULL_ARG },\n run: async ({ args }) => {\n const customerId = requireCustomerId(args);\n const payloads = loadJsonPayloads(args.file);\n if (payloads.length === 0 || payloads.some((payload) => Object.keys(payload).length === 0)) {\n failWriteValidation(`${kind} needs --file with the op payload (one object, or a JSON array to stage many)`);\n }\n if (payloads.length > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(\n `${payloads.length} payloads exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX} — split the file`,\n );\n }\n const payloadHints = [\n ...new Set(payloads.flatMap((payload) => (typeof hints === \"function\" ? hints(payload) : (hints ?? [])))),\n ];\n await stageGoogleOps(\n payloads.map((payload) => ({ kind, customerId, payload })),\n payloadHints,\n args.full === true,\n );\n },\n }),\n );\n}\n\n/**\n * `--bid-modifier` as a number, validated against the range Google actually accepts.\n *\n * Rejecting the (0, 0.1) gap here rather than at the backend is the point: 0 and 0.1 are a hundredth\n * apart in value and mean \"never serve\" versus \"bid a tenth\", so a typo between them is a real spend\n * decision, and the error should arrive before anything is staged.\n */\nexport function bidModifierFlag(value: unknown): number {\n if (value === undefined || value === null || value === \"\") {\n failWriteValidation(\n \"--bid-modifier is required: 1 for no adjustment, 1.25 to bid 25% more, 0.9 to bid 10% less, 0 to stop serving on a device\",\n );\n }\n const num = Number(value);\n if (Number.isNaN(num) || num < 0 || num > 10 || (num > 0 && num < 0.1)) {\n failWriteValidation(\"--bid-modifier must be 0 (stop serving on it) or between 0.1 and 10.0\");\n }\n return num;\n}\n","import type { z } from \"zod\";\n\n/** Appended to each copy flag's help, so `--help` and `baker schema` say how to pass a comma. */\nexport const AD_COPY_LIST_USAGE =\n \"repeat the flag once per item, or pass one comma-separated list and wrap an item that contains a comma in double quotes: '\\\"Fast, free quotes\\\",Book today'. A flag given once is read as a list, so a lone item with a comma needs its double quotes too: '\\\"Fast, free quotes\\\"'\";\n\n/** The op's copy-list fields, by the flag an agent passes them with. */\nconst COPY_LIST_FLAG: Readonly<Record<string, string>> = {\n headlines: \"--headlines\",\n descriptions: \"--descriptions\",\n longHeadlines: \"--long-headlines\",\n};\n\ninterface CountRefusal {\n flag: string;\n count: number | undefined;\n bound: string;\n tooMany: boolean;\n}\n\nfunction valueAt(root: unknown, path: readonly PropertyKey[]): unknown {\n let node = root;\n for (const key of path) {\n if (node === null || typeof node !== \"object\") return undefined;\n node = (node as Record<PropertyKey, unknown>)[key];\n }\n return node;\n}\n\nfunction countRefusal(op: unknown, issue: z.core.$ZodIssue): CountRefusal | undefined {\n if ((issue.code !== \"too_big\" && issue.code !== \"too_small\") || issue.origin !== \"array\") return undefined;\n const flag = COPY_LIST_FLAG[String(issue.path.at(-1))];\n if (!flag) return undefined;\n const value = valueAt(op, issue.path);\n const count = Array.isArray(value) ? value.length : undefined;\n return issue.code === \"too_big\"\n ? { flag, count, bound: `at most ${issue.maximum}`, tooMany: true }\n : { flag, count, bound: `at least ${issue.minimum}`, tooMany: false };\n}\n\n/**\n * The fix for a stage refused only for how many headlines, descriptions or long headlines it has.\n *\n * That is a limit on a field the agent named correctly, so the generic \"read `baker capabilities`,\n * do not guess another field name\" sent it through draft list, schema and --help before it saw the\n * cause. Too many items is usually copy cut at its commas — a flag given once is a comma-separated\n * list, so \"Rated 4,5/5\" becomes two items — which is why that case names the forms that keep a\n * comma. Undefined when anything else was refused too, so the capabilities pointer still covers it.\n */\nexport function copyListCountFix(\n op: unknown,\n issues: readonly z.core.$ZodIssue[],\n): { action: string; explanation: string } | undefined {\n const refusals = issues.map((issue) => countRefusal(op, issue));\n if (refusals.length === 0 || refusals.some((refusal) => refusal === undefined)) return undefined;\n const counted = refusals.filter((refusal): refusal is CountRefusal => refusal !== undefined);\n const limits = counted\n .map(({ flag, count, bound }) => `${flag} has ${count ?? \"the wrong number of\"} items; this ad takes ${bound}.`)\n .join(\" \");\n const commaCause = counted.some((refusal) => refusal.tooMany)\n ? ' If you meant fewer items, the copy was cut at its commas: a flag given once is read as a comma-separated list, so an item with a comma in it (\"Fast, free quotes\", a decimal like \"4,5/5\") becomes two. To keep a comma, ' +\n `${AD_COPY_LIST_USAGE} — or put the content in --file as JSON.`\n : \"\";\n return {\n action: \"fix_copy_list_count\",\n explanation: `${limits}${commaCause} ${commaCause ? \"Otherwise add\" : \"Add\"} or drop items to fit the limit, then stage again; the field names are right.`,\n };\n}\n","import type {\n GoogleDraftListResponse,\n GoogleDraftStatusCollection,\n GoogleDraftStatusNode,\n} from \"@baker/api/ads-google\";\n\n/**\n * Render the staged Google Ads draft as a readable campaign ▸ ad group ▸ ad tree — the CLI\n * counterpart to the dashboard's Google Ads tab, so an agent can review everything it has staged\n * with one command instead of reading raw JSON. Pure: takes the draft-list response, returns text.\n */\n\nconst OPERATION_LABELS: Record<string, string> = {\n create: \"Creating\",\n update: \"Updating\",\n pause: \"Pausing\",\n resume: \"Resuming\",\n remove: \"Removing\",\n upload: \"Uploading\",\n};\n\n/** The same verbs once the publish has run: a published draft reports what happened, not what is staged. */\nconst APPLIED_LABELS: Record<string, string> = {\n create: \"Created\",\n update: \"Updated\",\n pause: \"Paused\",\n resume: \"Resumed\",\n remove: \"Removed\",\n upload: \"Uploaded\",\n};\n\n/** Folded changes that did not land (\"1 change failed\", \"2 changes skipped\"), named beside the node's own outcome. */\nfunction notAppliedText(node: GoogleDraftStatusNode): string | undefined {\n const { failed = 0, skipped = 0 } = node.foldedNotApplied ?? {};\n const changes = (n: number) => `${n} change${n === 1 ? \"\" : \"s\"}`;\n const parts = [\n ...(failed > 0 ? [`${changes(failed)} failed`] : []),\n ...(skipped > 0 ? [`${changes(skipped)} skipped`] : []),\n ];\n return parts.length > 0 ? parts.join(\", \") : undefined;\n}\n\nfunction outcomeBadge(node: GoogleDraftStatusNode, result: NonNullable<GoogleDraftStatusNode[\"result\"]>): string {\n const verb = node.operation ?? \"update\";\n if (result === \"applied\") {\n return node.operation ? (APPLIED_LABELS[verb] ?? \"Applied\") : \"Changes applied\";\n }\n if (result === \"simulated\") {\n return `Simulated (${verb})`;\n }\n if (result === \"failed\") {\n return node.operation ? `Failed to ${verb}` : \"Failed\";\n }\n return \"Skipped\";\n}\n\nfunction badge(node: GoogleDraftStatusNode): string {\n const label = node.result\n ? outcomeBadge(node, node.result)\n : ((node.operation ? OPERATION_LABELS[node.operation] : undefined) ?? (node.existing ? \"on Google Ads\" : \"staged\"));\n const parts = [label, ...(node.status && node.status !== label ? [node.status] : [])];\n const notApplied = notAppliedText(node);\n return [...parts, ...(notApplied ? [notApplied] : [])].join(\" · \");\n}\n\nfunction collectionLine(collection: GoogleDraftStatusCollection): string | undefined {\n const parts: string[] = [];\n if (collection.added > 0) {\n parts.push(`+${collection.added}`);\n }\n if (collection.existing > 0) {\n parts.push(`${collection.existing} existing`);\n }\n if (collection.removed > 0) {\n parts.push(`-${collection.removed}`);\n }\n // Neither an add nor a remove — a member that stays in the set with a changed value (a device's\n // bid adjustment). Left out, a draft whose only criterion change is one printed no line at all.\n if ((collection.updated ?? 0) > 0) {\n parts.push(`~${collection.updated}`);\n }\n return parts.length > 0 ? `${collection.label}: ${parts.join(\", \")}` : undefined;\n}\n\n/**\n * Every advertiser account the tree touches. A draft may legitimately span\n * several, and a criterion id is derived from the keyword's text and match type\n * — so the same keyword carries the same id in every account. The account is\n * printed on each node once there is more than one, and left off when there is not.\n */\nfunction accountsInTree(nodes: readonly GoogleDraftStatusNode[]): Set<string> {\n const accounts = new Set<string>();\n const walk = (node: GoogleDraftStatusNode): void => {\n accounts.add(node.customerId);\n for (const child of node.children) {\n walk(child);\n }\n };\n for (const node of nodes) {\n walk(node);\n }\n return accounts;\n}\n\nfunction renderNode(node: GoogleDraftStatusNode, depth: number, lines: string[], showAccount: boolean): void {\n const indent = \" \".repeat(depth);\n const account = showAccount ? ` · account ${node.customerId}` : \"\";\n const ref = node.ref ? ` · ${node.ref}` : \"\";\n lines.push(`${indent}• ${node.name} · ${badge(node)}${account}${ref}`);\n for (const warning of node.warnings ?? []) {\n lines.push(`${indent} ⚠ ${warning}`);\n }\n for (const folded of node.folded ?? []) {\n lines.push(`${indent} ${folded.summary} · ${folded.ref}`);\n }\n for (const collection of node.collections) {\n const line = collectionLine(collection);\n if (line) {\n lines.push(`${indent} ${line}`);\n }\n }\n for (const child of node.children) {\n renderNode(child, depth + 1, lines, showAccount);\n }\n}\n\nconst RESOURCE_ENTITIES = new Set([\n \"sharedSet\",\n \"biddingStrategy\",\n \"audience\",\n \"customAudience\",\n \"combinedAudience\",\n \"conversionAction\",\n \"label\",\n \"budget\",\n \"asset\",\n]);\n\nfunction renderSection(title: string, nodes: GoogleDraftStatusNode[], lines: string[], showAccount: boolean): void {\n if (nodes.length === 0) {\n return;\n }\n lines.push(\"\");\n lines.push(title);\n for (const node of nodes) {\n renderNode(node, 1, lines, showAccount);\n }\n}\n\nfunction renderAdvisories(data: GoogleDraftListResponse, lines: string[]): void {\n const advisories = data.advisories ?? [];\n // Every advisory is phrased as something to settle BEFORE publishing. On a published draft there\n // is nothing left to settle here, and printing them reads as work still outstanding on this chat.\n if (advisories.length === 0 || data.status === \"applied\") {\n return;\n }\n lines.push(\"\");\n // Two kinds of finding share this block: build-out nudges (\"this ad group has one ad\") and\n // whole-draft coherence findings (\"this campaign will report zero conversions\", \"two of your\n // campaigns bid on the same keyword\"). The coherence ones come first and cost money, so the\n // heading no longer frames the block as optional polish.\n lines.push(\"Advisories (non-blocking, checked across the whole draft — settle these before you publish)\");\n for (const advisory of advisories) {\n lines.push(` • ${advisory.message}`);\n }\n}\n\n/**\n * What the publish did, once there is a publish to report.\n *\n * A published Google Ads draft rendered exactly like a staged one — same count, every op still\n * reading \"Creating\" — so the surface `.claude/rules/cli-env.md` sends an agent to for the outcome\n * could not answer, and a failed op was invisible in the human output while sitting in the JSON\n * envelope the whole time. Found by publishing a BUSINESS_LOGO link that Google refused with\n * \"Customer is not verified\": the draft still read \"4 staged changes\". LinkedIn fixed the same\n * shape first; this is its counterpart.\n */\nfunction renderOutcome(data: GoogleDraftListResponse, lines: string[]): void {\n const counts = new Map<string, number>();\n for (const op of data.ops) {\n const status = op.result?.status ?? \"pending\";\n counts.set(status, (counts.get(status) ?? 0) + 1);\n }\n const summary = [...counts].map(([status, count]) => `${count} ${status}`).join(\", \");\n lines.push(`Google Ads — published · ${summary || `${data.count} op(s)`} · ${data.mode}`);\n // A failure is the reason to read this at all, so it is named with its error rather than left as\n // a number to go and look up.\n for (const op of data.ops) {\n const status = op.result?.status;\n if (status !== \"failed\" && status !== \"skipped\") {\n continue;\n }\n const reason = op.result?.error ?? op.result?.skippedBecause ?? \"no reason recorded\";\n lines.push(` ✗ ${op.summary} — ${status}: ${reason}`);\n }\n // Google answers \"applied\" to a field it accepted and never stored (a portfolio's bid ceiling),\n // so the read-back after publish is the only thing that knows the change did not land as sent.\n for (const op of data.ops) {\n const verification = op.result?.verification;\n if (op.result?.status === \"applied\" && verification?.status === \"drifted\") {\n lines.push(` ⚠ ${op.summary} — not as sent: ${verification.note ?? \"Google Ads shows something else\"}`);\n }\n }\n}\n\nexport function renderDraftStatus(data: GoogleDraftListResponse): string {\n if (data.status === \"none\" || data.count === 0) {\n return \"No staged Google Ads changes on this chat.\";\n }\n const modeNote =\n data.mode === \"live\"\n ? \"Live — publishing writes directly to Google Ads.\"\n : \"Simulated — publishing completes the whole draft without calling Google Ads.\";\n const lines: string[] = [];\n if (data.status === \"applied\") {\n renderOutcome(data, lines);\n } else if (data.status === \"publishing\") {\n lines.push(`Google Ads — publishing ${data.count} change${data.count === 1 ? \"\" : \"s\"} · ${data.mode}`);\n } else {\n lines.push(`Google Ads — ${data.count} staged change${data.count === 1 ? \"\" : \"s\"} · ${data.mode}`);\n }\n lines.push(modeNote);\n\n const tree = data.tree ?? [];\n const showAccount = accountsInTree(tree).size > 1;\n renderSection(\n \"Shared resources\",\n tree.filter((node) => RESOURCE_ENTITIES.has(node.entity)),\n lines,\n showAccount,\n );\n renderSection(\n \"Campaigns\",\n tree.filter((node) => node.entity === \"campaign\"),\n lines,\n showAccount,\n );\n const rest = tree.filter((node) => !RESOURCE_ENTITIES.has(node.entity) && node.entity !== \"campaign\");\n renderSection(\"Other\", rest, lines, showAccount);\n renderAdvisories(data, lines);\n\n return lines.join(\"\\n\");\n}\n","import { type GoogleDraftStageResponse, isCreateKind } from \"@baker/api/ads-google\";\nimport { cacheGet, cacheSet } from \"../cache.ts\";\nimport { loopWarnings } from \"../output.ts\";\n\n/**\n * Bulk work done as a loop of single commands — one `keywords update` per keyword, one\n * `negative-keywords remove` per term — is one request, one rate-limit hit and one tool call per row;\n * production saw 1,284 of them. The CLI cannot see the loop from inside one call, so it remembers the\n * last few single stages per chat and, once the same kind repeats, says how to do the rest in one call.\n */\n\nexport interface StageStreak {\n kind: string;\n count: number;\n lastAt: number;\n}\n\n/** Singles further apart than this are separate decisions, not a loop. */\nconst STREAK_WINDOW_MS = 5 * 60_000;\n/** The streak length that reads as a loop. */\nconst STREAK_THRESHOLD = 5;\n\nexport function nextStageStreak(previous: StageStreak | undefined, kind: string, now: number): StageStreak {\n const continues = previous && previous.kind === kind && now - previous.lastAt <= STREAK_WINDOW_MS;\n return { kind, count: continues ? previous.count + 1 : 1, lastAt: now };\n}\n\n/** The one-call form of a kind, where a command has one beside `draft stage --file`. */\nconst BATCH_FORMS: Record<string, string> = {\n \"google.keyword.add\": \"`keywords add --file keywords.txt` (one term[:MATCH_TYPE] per line)\",\n \"google.keyword.update\":\n \"`keywords pause|resume <resource name> <resource name>…` (or --file, one per line) for status\",\n \"google.keyword.remove\": \"`draft stage --file` with one google.keyword.remove per target\",\n \"google.negativeKeyword.add\":\n \"`negative-keywords add --ad-group-id <id>,<id> --file terms.txt` (every term on every ad group)\",\n \"google.sharedSetMember.add\": \"`keyword-lists add --file terms.txt`\",\n \"google.sharedSetMember.remove\": '`keyword-lists remove --list-ref <id> --text \"a,b,c\"`',\n};\n\nexport function stageStreakHints(streak: StageStreak): string[] {\n if (streak.count < STREAK_THRESHOLD) {\n return [];\n }\n const form = BATCH_FORMS[streak.kind];\n return [\n `LOOP: that is ${streak.count} ${streak.kind} ops staged one command at a time. Stop looping — put every remaining change in one file and stage them in ONE call: \\`baker ads google draft stage --file ops.json --customer-id <id>\\` (a JSON array of {\"kind\",\"target\"?,\"payload\"?}, up to 500, any mix of kinds)${form ? `, or ${form}` : \"\"}. Fix staged ops together with \\`draft amend --file\\`.`,\n ];\n}\n\nconst STREAK_CACHE = \"stage-streak\";\n\n/** Record one single stage on this chat and return the nudge it earns, if any. Never throws. */\nexport function recordSingleStage(chatId: string, kind: string): string[] {\n try {\n const streak = nextStageStreak(cacheGet<StageStreak>(STREAK_CACHE, chatId)?.data, kind, Date.now());\n cacheSet(STREAK_CACHE, chatId, streak, STREAK_WINDOW_MS);\n const hints = stageStreakHints(streak);\n // Also on stderr: agents pipe each stage through a filter that keeps only `ok`, which drops the\n // hint from the JSON — 26 times in one Session. stderr reaches the agent past any such filter.\n for (const hint of hints) process.stderr.write(`${hint}\\n`);\n return hints;\n } catch {\n return [];\n }\n}\n\nconst TREE_CACHE = \"stage-tree\";\n\n/**\n * A single create (not an update merged into a staged one) that depends on a create staged earlier in this chat is a new campaign tree being\n * built one level at a time. Each level changes kind, so the LOOP streak never fires; this says once\n * per chat (per window) how to stage the rest in one call. Never throws.\n */\nexport function recordTreeStage(chatId: string, staged: GoogleDraftStageResponse): string[] {\n try {\n if (!staged.staged || staged.amended || !isCreateKind(staged.kind) || staged.dependsOn.length === 0) {\n return [];\n }\n if (cacheGet<boolean>(TREE_CACHE, chatId)?.data) {\n return [];\n }\n cacheSet(TREE_CACHE, chatId, true, STREAK_WINDOW_MS);\n return loopWarnings([\n `TREE: this ${staged.kind} hangs off a create staged earlier in this chat — a new campaign tree built one command per entity. Stage everything still to build (ad groups, keywords, ads, assets and their links) in ONE call: \\`baker ads google draft stage --file ops.json --customer-id <id>\\`, giving each create a name with \"as\": \"g_temp_<name>\" so later ops in the same file can point at it (refs staged earlier still work).`,\n ]);\n } catch {\n return [];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,SAAS,QAAQ,GAAW,QAAyB;AACnD,QAAM,OAAO,SAAS,kBAAkB;AACxC,SAAO,MAAM,IAAI,KAAK,IAAI,KAAK,GAAG,CAAC,IAAI,IAAI;AAC7C;AAOO,SAAS,eACd,MACA,YACoE;AACpE,QAAM,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,GAAG,eAAe,UAAU;AAChE,QAAM,WAAW;AAAA,IACf,GAAG;AAAA,IACH,OAAO,IAAI;AAAA,IACX;AAAA,IACA,GAAI,KAAK,OAAO,EAAE,MAAM,KAAK,KAAK,OAAO,CAAC,SAAS,KAAK,eAAe,UAAU,EAAE,IAAI,CAAC;AAAA,EAC1F;AACA,QAAM,SAAS,KAAK,IAAI,OAAO,CAAC,OAAO,GAAG,eAAe,UAAU;AACnE,MAAI,OAAO,WAAW,EAAG,QAAO,EAAE,MAAM,UAAU,OAAO,CAAC,EAAE;AAC5D,QAAM,SAAS,KAAK,WAAW;AAC/B,QAAM,WAAW,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,CAAC;AAC/D,QAAM,QAAQ,UAAU,SAAS,WAAW,IAAI,KAAK,GAAG,IAAI,SAAS,KAAK,IAAI,CAAC;AAC/E,QAAM,MAAM,OAAO,WAAW;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AM;AACvB,cAAM,aAAa,kBAAkB,IAAI;AACzC,cAAM,WAAW,iBAAiB,KAAK,IAAI;AAC3C,YAAI,SAAS,WAAW,KAAK,SAAS,KAAK,CAAC,YAAY,OAAO,KAAK,OAAO,EAAE,WAAW,CAAC,GAAG;AAC1F,8BAAoB,GAAG,IAAI,+EAA+E;AAAA,QAC5G;AACA,YAAI,SAAS,SAAS,wBAAwB;AAC5C;AAAA,YACE,GAAG,SAAS,MAAM,wCAAwC,sBAAsB;AAAA,UAClF;AAAA,QACF;AACA,cAAM,eAAe;AAAA,UACnB,GAAG,IAAI,IAAI,SAAS,QAAQ,CAAC,YAAa,OAAO,UAAU,aAAa,MAAM,OAAO,IAAK,SAAS,CAAC,CAAG,CAAC;AAAA,QAC1G;AACA,cAAM;AAAA,UACJ,SAAS,IAAI,CAAC,aAAa,EAAE,MAAM,YAAY,QAAQ,EAAE;AAAA,UACzD;AAAA,UACA,KAAK,SAAS;AAAA,QAChB;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;AASO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,IAAI;AACzD;AAAA,MACE;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,OAAO,KAAK;AACxB,MAAI,OAAO,MAAM,GAAG,KAAK,MAAM,KAAK,MAAM,MAAO,MAAM,KAAK,MAAM,KAAM;AACtE,wBAAoB,uEAAuE;AAAA,EAC7F;AACA,SAAO;AACT;","names":["changes"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/ga4/shared.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type { Ga4DraftListResponse, Ga4DraftStageBatchResponse, Ga4DraftStageResponse } from \"@baker/api/ga4\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { requireChatId, resolveChatId } from \"../../env.ts\";\nimport { isNotConnectedError } from \"../../error-handler.ts\";\nimport { hintLines, splitHints } from \"../ads/hints.ts\";\nimport { writeJsonEnvelope } from \"../ads/output.ts\";\nimport { draftListWhere, requireDraftWhere } from \"../draft-where.ts\";\n\n/**\n * Shared plumbing for the staged Google Analytics write commands. These NEVER\n * change the property directly: each stages a change onto this chat's draft, the\n * user reviews the whole set in the Analytics tab, and it applies when the chat\n * completes.\n */\n\nexport function failValidation(message: string): never {\n writeJsonEnvelope({ ok: false, error: { code: \"VALIDATION_ERROR\", message } });\n process.exit(1);\n}\n\nexport function requireTarget(args: Record<string, unknown>, entity: string): string {\n const positional = Array.isArray(args._) ? args._[0] : undefined;\n const target = args.id ?? args.target ?? positional;\n if (typeof target !== \"string\" || target.length === 0) {\n failValidation(`pass the ${entity} id as the positional argument`);\n }\n return target;\n}\n\nfunction readJsonSource(args: Record<string, unknown>, flag: \"patch\" | \"json\"): unknown {\n const inline = args[flag];\n const file = args.file;\n const raw =\n typeof file === \"string\" && file.length > 0\n ? readFileSync(file, \"utf8\")\n : typeof inline === \"string\" && inline.length > 0\n ? inline\n : undefined;\n if (raw === undefined) {\n failValidation(`pass --${flag} with inline JSON or --file with a path to a JSON file`);\n }\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return failValidation(`--${flag} is not valid JSON`);\n }\n}\n\nfunction asObject(value: unknown, flag: string, index?: number): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n failValidation(\n index === undefined ? `--${flag} must be a JSON object` : `--${flag}[${index}] must be a JSON object`,\n );\n }\n return value as Record<string, unknown>;\n}\n\n/** `--json '<inline>'` or `--file <path>` → a parsed object. */\nexport function loadJsonArg(args: Record<string, unknown>, flag: \"patch\" | \"json\" = \"json\"): Record<string, unknown> {\n return asObject(readJsonSource(args, flag), flag);\n}\n\n/**\n * The same, but a JSON **array** is allowed and means \"stage all of these\n * together\".\n *\n * This is the only way to keep a bulk job cheap. Every stage call reads the\n * whole property first — the property, its data streams, its key events, its\n * custom definitions and its retention window — because that read is what the\n * duplicate and immutability refusals are derived from. One call per definition\n * therefore multiplies a routine \"make these eight parameters reportable\" into\n * roughly fifty Admin API reads against a quota Google counts per project.\n */\nexport function loadJsonPayloads(args: Record<string, unknown>): Record<string, unknown>[] {\n const parsed = readJsonSource(args, \"json\");\n if (!Array.isArray(parsed)) {\n return [asObject(parsed, \"json\")];\n }\n if (parsed.length === 0) {\n failValidation(\"--json is an empty list — pass at least one definition\");\n }\n return parsed.map((entry, index) => asObject(entry, \"json\", index));\n}\n\nconst RETRYABLE_CODES = new Set([\n \"RATE_LIMITED\",\n \"UNAVAILABLE\",\n \"INTERNAL_ERROR\",\n \"BUDGET_EXCEEDED\",\n \"NETWORK_ERROR\",\n \"TIMEOUT\",\n]);\n\n/**\n * The one error shape for the whole family.\n *\n * Two different 403s reach here and they need opposite responses, which is why\n * the fix is keyed to the message and not just the status:\n * - \"no Google Analytics connection / no property picked\" → the in-chat connect\n * form, same as every other family.\n * - \"this connection can read but not change the property\" → a RECONNECT, which\n * is what every connection made before Baker could configure GA4 needs. The\n * backend's message already says so, so it is passed through as the fix\n * explanation rather than being replaced with the connect-form wording, which\n * would send the user to set up a connection they already have.\n */\nexport function handleError(err: unknown): never {\n if (err instanceof ApiError) {\n const readOnly = err.code === \"FORBIDDEN\" && /read the property but not change it/i.test(err.message);\n writeJsonEnvelope({\n ok: false,\n error: {\n code: err.code,\n message: err.message,\n ...(readOnly\n ? {\n fix: {\n action: \"reconnect\",\n explanation:\n \"The Google Analytics connection is read-only. Ask the user to reconnect Google Analytics — in the \" +\n \"dashboard, Brain → Integrations → Platforms → Google Analytics — which grants the permission to change \" +\n \"the property. Reporting (`baker ga4 query`, `baker ga4 audit`) keeps working meanwhile, so carry \" +\n \"on with the rest of the job and tell them what you will set up once they have reconnected. Don't \" +\n \"claim anything was configured.\",\n },\n }\n : err.code === \"UNAUTHORIZED\" || (err.code === \"FORBIDDEN\" && isNotConnectedError(err.code, err.message))\n ? {\n fix: {\n action: \"request_connection\",\n explanation:\n \"Google Analytics is not connected for this company yet, or no property has been picked. Don't \" +\n 'send the user to Settings — call the `request_connection` tool with { platform: \"google-analytics\", ' +\n \"reason } and they connect and pick their property from inside the chat. If the \" +\n \"`request_connection` call fails, say so plainly and give the exact route: dashboard → Brain → \" +\n \"Integrations → Platforms → Google Analytics. Then carry on with the rest of the task.\",\n },\n }\n : {}),\n retryable: RETRYABLE_CODES.has(err.code),\n },\n });\n process.exit(1);\n }\n writeJsonEnvelope({ ok: false, error: { code: \"NETWORK_ERROR\", message: \"Unexpected error\", retryable: true } });\n process.exit(1);\n}\n\n/** Nudges returned after a stage so the agent's next step is obvious. */\nconst STAGE_HINTS = [\n \"Staged only — nothing has changed in Google Analytics yet. These apply when the chat completes, and an applied \" +\n \"change takes effect on the property immediately: there is no version to publish afterwards and no undo. Say \" +\n \"the changes are ready and take effect when the user completes the chat — not that they are done already.\",\n];\n\nconst WARNING_HINT = \"Read the warnings above before telling the user this is ready.\";\n\nexport async function stageOp(op: Record<string, unknown>): Promise<void> {\n const chatId = requireChatId();\n try {\n const { data, hints } = splitHints(await apiPost<Ga4DraftStageResponse>(\"/api/ga4/draft/stage\", { chatId, op }));\n writeJsonEnvelope({\n ok: true,\n data,\n hints: [...hints, ...STAGE_HINTS, ...(data.warnings.length > 0 ? [WARNING_HINT] : [])],\n });\n } catch (err) {\n handleError(err);\n }\n}\n\n/**\n * Stage several changes as ONE request against ONE read of the property.\n *\n * All-or-nothing: if any one of them is refused, none of them stage — which is\n * the honest outcome, since the refusals are things like \"two of these claim the\n * same parameter name\" that only mean anything about the set as a whole. A\n * single op falls through to the plain path so its envelope is unchanged.\n */\nexport async function stageOps(ops: Record<string, unknown>[]): Promise<void> {\n const [only] = ops;\n if (ops.length === 1 && only) {\n await stageOp(only);\n return;\n }\n const chatId = requireChatId();\n try {\n const { data, hints } = splitHints(\n await apiPost<Ga4DraftStageBatchResponse>(\"/api/ga4/draft/stage-batch\", { chatId, ops }),\n );\n writeJsonEnvelope({\n ok: true,\n data,\n hints: [...hints, ...STAGE_HINTS, ...(data.ops.some((op) => op.warnings.length > 0) ? [WARNING_HINT] : [])],\n });\n } catch (err) {\n handleError(err);\n }\n}\n\nexport async function draftAction(\n path: string,\n body: Record<string, unknown>,\n chat?: unknown,\n): Promise<Record<string, unknown>> {\n const chatId = resolveChatId(chat);\n try {\n const { data, hints } = splitHints(await apiPost<Record<string, unknown>>(path, { chatId, ...body }));\n writeJsonEnvelope({ ok: true, data, ...(hints.length > 0 ? { hints } : {}) });\n return data;\n } catch (err) {\n handleError(err);\n }\n}\n\n/** A compact, readable view of everything staged on this chat. */\nexport function renderDraft(response: Ga4DraftListResponse): string {\n if (response.count === 0) {\n return \"No Google Analytics changes staged on this chat.\";\n }\n const lines = [\n response.status === \"discarded\"\n ? `${response.count} Google Analytics change(s) discarded with their chat — none will apply`\n : `${response.count} staged Google Analytics change(s)`,\n ...response.ops.map((op) => {\n const status = op.result ? ` [${op.result.status}]` : \"\";\n return ` ${op.ref} ${op.summary}${status}`;\n }),\n ];\n if (response.status === \"applied\") {\n const failed = response.ops.filter((op) => op.result?.status !== \"applied\");\n lines.push(\n \"\",\n failed.length === 0\n ? \"All applied — these are in effect on the property now.\"\n : `${failed.length} of ${response.count} did not apply. The rest are in effect on the property.`,\n );\n }\n if (response.publishError) {\n lines.push(\"\", response.publishError);\n }\n return lines.join(\"\\n\");\n}\n\nexport async function draftList(json: boolean, chat?: unknown, full = false, selector?: string): Promise<void> {\n const where = selector === undefined ? undefined : requireDraftWhere(selector, \"ga4.\");\n const chatId = resolveChatId(chat);\n try {\n const response = await apiPost<Ga4DraftListResponse>(\"/api/ga4/draft\", {\n chatId,\n ...(full || where ? { full: true } : {}),\n });\n const { data, hints } = splitHints(response);\n if (where && selector !== undefined) {\n const narrowed = draftListWhere(data, where, selector);\n const all = [...hints, ...narrowed.hints];\n writeJsonEnvelope({ ok: true, data: narrowed.data, ...(all.length > 0 ? { hints: all } : {}) });\n return;\n }\n if (json || full) {\n writeJsonEnvelope({ ok: true, data, ...(hints.length > 0 ? { hints } : {}) });\n return;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AAO,IAAI,IAAI,CAAC,EAAG,CAAC;AAC9F;AAAA,IACF;AACA,QAAI,QAAQ,MAAM;AAChB,wBAAkB,EAAE,IAAI,MAAM,MAAM,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC,EAAG,CAAC;AAC5E;AAAA,IACF;AACA,YAAQ,OAAO,MAAM,GAAG,YAAY,IAAI,CAAC,GAAG,UAAU,QAAQ,CAAC;AAAA,CAAI;AAAA,EACrE,SAAS,KAAK;AACZ,gBAAY,GAAG;AAAA,EACjB;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/ads/google/conversion-upload-command.ts","../src/commands/ads/google/conversion-rows.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { CONVERSION_UPLOAD_MAX_ROWS } from \"@baker/api/ads-google\";\nimport { defineCommand } from \"citty\";\nimport { withEffect } from \"../../../schemas.ts\";\nimport { chunkConversionRows, parseConversionRowsText } from \"./conversion-rows.ts\";\nimport {\n failWriteValidation,\n googleStagedBatch,\n requireCustomerId,\n STAGE_FULL_ARG,\n stageGoogleOps,\n} from \"./write-shared.ts\";\n\n/**\n * `baker ads google conversions upload` — file conversions Google never received.\n *\n * This is a repair command, not a measurement one. The normal path for a conversion is the tag on\n * the page and the server-side send behind it; this exists for the days that path was broken — a\n * Google connection that had lost its permission, an outage, a tag pointed at the wrong action —\n * where the conversions really happened and the account has no record of them.\n *\n * It stages like every other Google change: nothing reaches Google until the chat is published, and\n * the change list shows how many conversions, into which action, worth how much, and how many of\n * them can be matched by click id rather than by customer details.\n */\n\nconst UPLOAD_HINTS = [\n \"Nothing has been uploaded yet — the conversions are staged and go to Google when this chat is published.\",\n \"Reuse each conversion's ORIGINAL order id (the Form submission id, the order number the site issued). Google recognises an upload it already holds by that id, which is what makes a re-send a correction instead of a second conversion — a made-up id cannot be taken back.\",\n \"Say plainly what was uploaded and what it was for. A conversion upload changes what automated bidding optimises toward, so the client should hear the count and the action, not just that it worked.\",\n];\n\n/**\n * The command's own hints about what did not make it into the staged rows. A dropped column is\n * stated because the alternative — a value the user believed they sent, silently absent — is\n * indistinguishable from a working upload right up until the numbers are wrong.\n */\nfunction ignoredColumnHints(columns: readonly string[]): string[] {\n if (columns.length === 0) {\n return [];\n }\n return [\n `Ignored ${columns.length} column(s) that are not part of a conversion: ${columns.join(\", \")}. A conversion carries an order id, a date, and something to match on: a click id (gclid / gbraid / wbraid), an email, a phone, or all four of givenName + familyName + country + postalCode. Optionally a value + currency, conversionCount, and eventSource (WEB / APP / IN_STORE / PHONE / OTHER). A column named just \\`Name\\` is ignored on purpose — Google needs the first and last name separately, so split it before re-running.`,\n ];\n}\n\nfunction readRowsFile(path: string): { rows: Record<string, unknown>[]; ignoredColumns: string[] } {\n // Inline content is read the same way `--file` is everywhere else on this surface: a leading `[`\n // or `{` is the data itself, anything else is a path.\n const inline = path.trimStart().startsWith(\"[\") || path.trimStart().startsWith(\"{\");\n let text: string;\n try {\n text = inline ? path : readFileSync(path, \"utf8\");\n } catch (err) {\n failWriteValidation(`could not read ${path}: ${err instanceof Error ? err.message : String(err)}`);\n }\n const parsed = parseConversionRowsText(text);\n if (!parsed.ok) {\n failWriteValidation(`${inline ? \"the conversions passed inline\" : path}: ${parsed.error}`);\n }\n return { rows: parsed.rows, ignoredColumns: parsed.ignoredColumns };\n}\n\n/** The single conversion described by flags, or undefined when none of them were used. */\nfunction rowFromFlags(args: Record<string, unknown>): Record<string, unknown> | undefined {\n const entries: Array<[string, unknown]> = [\n [\"orderId\", args[\"order-id\"]],\n [\"conversionDateTime\", args.date],\n [\"gclid\", args.gclid],\n [\"gbraid\", args.gbraid],\n [\"wbraid\", args.wbraid],\n [\"email\", args.email],\n [\"phone\", args.phone],\n [\"currency\", args.currency],\n [\"eventSource\", args[\"event-source\"]],\n [\"givenName\", args[\"given-name\"]],\n [\"familyName\", args[\"family-name\"]],\n [\"regionCode\", args.country],\n [\"postalCode\", args[\"postal-code\"]],\n ];\n const row: Record<string, unknown> = {};\n for (const [key, value] of entries) {\n if (typeof value === \"string\" && value.trim() !== \"\") {\n row[key] = value.trim();\n }\n }\n nestAddressFlags(row);\n readNumericFlags(args, row);\n return Object.keys(row).length > 0 ? row : undefined;\n}\n\n/**\n * The four address parts travel together into the nested identifier. A partial one is kept nested so\n * the contract refuses it by name — dropping it here would turn a fixable mistake into conversions\n * that match nobody.\n */\nfunction nestAddressFlags(row: Record<string, unknown>): void {\n const address: Record<string, unknown> = {};\n for (const key of [\"givenName\", \"familyName\", \"regionCode\", \"postalCode\"]) {\n if (row[key] !== undefined) {\n address[key] = row[key];\n delete row[key];\n }\n }\n if (Object.keys(address).length > 0) {\n row.address = address;\n }\n}\n\nfunction readNumericFlags(args: Record<string, unknown>, row: Record<string, unknown>): void {\n if (args[\"conversion-count\"] !== undefined && args[\"conversion-count\"] !== \"\") {\n const count = Number(args[\"conversion-count\"]);\n if (!Number.isInteger(count) || count < 1) {\n failWriteValidation(\"--conversion-count must be a whole number of conversions, e.g. 3\");\n }\n row.conversionCount = count;\n }\n if (args.value !== undefined && args.value !== \"\") {\n const numeric = Number(args.value);\n if (!Number.isFinite(numeric)) {\n failWriteValidation(\"--value must be a number in major currency units, e.g. 49.90\");\n }\n row.value = numeric;\n }\n}\n\nexport const conversionsUploadCommand = withEffect(\n googleStagedBatch(\"google.conversion.upload\"),\n defineCommand({\n meta: {\n name: \"upload\",\n description:\n \"Upload conversions Google never received — a backfill for a period where the tracking was broken. Start here: `conversions upload --customer-id 1234567890 --conversion-action 987654321 --file missing.csv`, where the file carries one conversion per row with an order id, a date, and a gclid and/or an email. Nothing reaches Google until the chat is published. Reuse each conversion's ORIGINAL order id so a re-send is treated as a correction rather than a second conversion. Read the account's actions first with: baker ads google query \\\"SELECT conversion_action.id, conversion_action.name, conversion_action.status FROM conversion_action\\\"\",\n },\n args: {\n \"customer-id\": { type: \"string\", description: \"10-digit Google Ads customer id\" },\n \"conversion-action\": {\n type: \"string\",\n description: \"The conversion action to record these against — its numeric id or resource name\",\n },\n file: {\n type: \"string\",\n description:\n \"The conversions: a path to a CSV / JSON / JSONL file, or the JSON array written inline. Columns: orderId, conversionDateTime, gclid | gbraid | wbraid, email, phone, givenName + familyName + country + postalCode (advanced matching), value, currency, conversionCount, eventSource\",\n },\n \"order-id\": { type: \"string\", description: \"Single conversion: its original order / submission id\" },\n date: {\n type: \"string\",\n description:\n \"Single conversion: when it happened, as an ISO-8601 instant WITH a timezone (2026-08-01T10:00:00Z or 2026-08-01T12:00:00+02:00)\",\n },\n gclid: { type: \"string\", description: \"Single conversion: the Google click id it came from\" },\n gbraid: { type: \"string\", description: \"Single conversion: the gbraid click id (app-to-web)\" },\n wbraid: { type: \"string\", description: \"Single conversion: the wbraid click id (web-to-app)\" },\n email: { type: \"string\", description: \"Single conversion: the customer's email — hashed before it is stored\" },\n phone: {\n type: \"string\",\n description: \"Single conversion: the customer's phone in E.164 — hashed before it is stored\",\n },\n value: { type: \"string\", description: \"Single conversion: what it was worth, in major currency units\" },\n currency: { type: \"string\", description: \"Single conversion: the value's 3-letter currency code, e.g. EUR\" },\n \"conversion-count\": {\n type: \"string\",\n description:\n \"Single conversion: how many conversions this row stands for. Only read on an EVERY-counting conversion action; defaults to 1\",\n },\n \"event-source\": {\n type: \"string\",\n description: \"Single conversion: where it happened — WEB (default), APP, IN_STORE, PHONE or OTHER\",\n },\n \"given-name\": {\n type: \"string\",\n description: \"Single conversion: the customer's first name — advanced matching, hashed before it is stored\",\n },\n \"family-name\": {\n type: \"string\",\n description: \"Single conversion: the customer's last name — advanced matching, hashed before it is stored\",\n },\n country: {\n type: \"string\",\n description:\n \"Single conversion: the customer's 2-letter country code, e.g. ES — required with a name/address match\",\n },\n \"postal-code\": {\n type: \"string\",\n description: \"Single conversion: the customer's postcode — required with a name/address match\",\n },\n full: STAGE_FULL_ARG,\n },\n run: async ({ args }) => {\n const customerId = requireCustomerId(args);\n const conversionAction = typeof args[\"conversion-action\"] === \"string\" ? args[\"conversion-action\"].trim() : \"\";\n if (conversionAction === \"\") {\n failWriteValidation(\n '--conversion-action is required: the action these conversions are recorded against. List them with: baker ads google query \"SELECT conversion_action.id, conversion_action.name, conversion_action.status FROM conversion_action\"',\n );\n }\n\n const fromFile = typeof args.file === \"string\" && args.file.length > 0 ? readRowsFile(args.file) : undefined;\n const fromFlags = rowFromFlags(args);\n if (fromFile && fromFlags) {\n failWriteValidation(\n \"pass either --file (a list of conversions) or the single-conversion flags, not both — otherwise it is ambiguous which row the flags belong to\",\n );\n }\n const rows = fromFile?.rows ?? (fromFlags ? [fromFlags] : []);\n if (rows.length === 0) {\n failWriteValidation(\n \"no conversions to upload — pass --file with the conversions, or describe one with --order-id, --date and a --gclid / --email\",\n );\n }\n\n // Chunked rather than refused: a month of lost conversions is routinely more rows than one\n // staged change should carry, and splitting it here means the reviewer sees several readable\n // cards instead of one they cannot check. Each chunk stages as its own op and succeeds or fails\n // on its own at publish.\n const chunks = chunkConversionRows(rows, CONVERSION_UPLOAD_MAX_ROWS);\n const ops = chunks.map((conversions) => ({\n kind: \"google.conversion.upload\",\n customerId,\n payload: { conversionAction, conversions },\n }));\n const chunkHint =\n chunks.length > 1\n ? [\n `${rows.length} conversions staged as ${chunks.length} uploads of up to ${CONVERSION_UPLOAD_MAX_ROWS} each. They publish independently — report the result of all ${chunks.length}, not just the first.`,\n ]\n : [];\n await stageGoogleOps(\n ops,\n [...chunkHint, ...ignoredColumnHints(fromFile?.ignoredColumns ?? []), ...UPLOAD_HINTS],\n args.full === true,\n );\n },\n }),\n);\n","/**\n * Reading the conversions a manual upload is built from.\n *\n * A backfill arrives as whatever the client could export — a CSV out of a spreadsheet or their CRM,\n * a JSON dump, one row pasted on the command line. All three land here and leave as the same row\n * shape the `@baker/api` contract validates, so the schema stays the single source of truth about\n * what a conversion is and this module only has to answer \"which column was that\".\n *\n * Two decisions worth keeping:\n *\n * - **Column names are matched loosely, values never are.** `Order ID`, `order_id` and\n * `transaction_id` are the same column; what is inside it is passed through untouched, because a\n * click id that has been \"helpfully\" trimmed is a click id that matches nothing.\n * - **Unknown columns are dropped and named.** A real CRM export carries twenty columns we have no\n * use for, so refusing the file would make the command unusable — but a column that vanishes\n * without being mentioned is how a value the user believed they sent turns out never to have\n * been sent. They are dropped and listed back.\n */\n\n/** Payload keys a row can carry, and the column names each is recognised by. */\nconst COLUMN_ALIASES: Record<string, readonly string[]> = {\n orderId: [\"orderid\", \"order\", \"ordernumber\", \"transactionid\", \"transaction\", \"submissionid\", \"conversionid\", \"id\"],\n conversionDateTime: [\n \"conversiondatetime\",\n \"conversiontime\",\n \"conversiondate\",\n \"datetime\",\n \"date\",\n \"time\",\n \"timestamp\",\n \"occurredat\",\n \"createdat\",\n ],\n gclid: [\"gclid\"],\n gbraid: [\"gbraid\"],\n wbraid: [\"wbraid\"],\n email: [\"email\", \"emailaddress\", \"useremail\", \"mail\"],\n phone: [\"phone\", \"phonenumber\", \"telephone\", \"mobile\", \"tel\"],\n value: [\"value\", \"conversionvalue\", \"amount\", \"revenue\", \"price\", \"total\"],\n currency: [\"currency\", \"currencycode\", \"conversioncurrency\"],\n conversionCount: [\"conversioncount\", \"quantity\", \"count\", \"units\"],\n // Deliberately only the exact spelling: a `Source` or `Channel` column in a CRM export almost\n // always holds an attribution channel, not one of Google's five event sources, and mapping it\n // would refuse the whole file on a column an upload has no use for. Unmapped, it is dropped and\n // named back in the hints, which is what those columns should get.\n eventSource: [\"eventsource\"],\n // Advanced matching. Each maps to one part of Google's address identifier; a row that carries the\n // four required parts is matched on name + address as well as on whatever else it has.\n // `name` is left out for the same reason: alone it produces a one-part `address`, and the\n // contract requires all four parts, so a lone `Name` column would refuse the file.\n givenName: [\"givenname\", \"firstname\", \"forename\"],\n familyName: [\"familyname\", \"lastname\", \"surname\"],\n regionCode: [\"regioncode\", \"country\", \"countrycode\"],\n postalCode: [\"postalcode\", \"postcode\", \"zip\", \"zipcode\"],\n addressLine: [\"addressline\", \"address\", \"street\", \"streetaddress\", \"addressline1\"],\n city: [\"city\", \"town\", \"locality\"],\n administrativeArea: [\"administrativearea\", \"state\", \"province\", \"region\"],\n};\n\n/** Numeric payload keys — everything else stays the string it arrived as. */\nconst NUMERIC_KEYS = new Set([\"value\", \"conversionCount\"]);\n\nfunction normalizeColumn(raw: string): string {\n return raw\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]/g, \"\");\n}\n\n/** The payload key a column name means, or undefined when it means nothing to an upload. */\nexport function payloadKeyForColumn(column: string): string | undefined {\n const normalized = normalizeColumn(column);\n for (const [key, aliases] of Object.entries(COLUMN_ALIASES)) {\n if (normalizeColumn(key) === normalized || aliases.includes(normalized)) {\n return key;\n }\n }\n return undefined;\n}\n\nexport interface ParsedConversionRows {\n rows: Record<string, unknown>[];\n /** Column names that were present and carried nothing an upload uses. */\n ignoredColumns: string[];\n}\n\nexport type ParseConversionRowsResult = ({ ok: true } & ParsedConversionRows) | { ok: false; error: string };\n\n/**\n * One raw record → the payload row shape. A blank cell is dropped rather than sent as `\"\"`: an empty\n * `gclid` column on a row matched by email would otherwise fail validation for carrying a click id\n * that is not one, which describes the spreadsheet rather than the conversion.\n */\n/** The address parts, in the flat column names a spreadsheet uses. */\nconst ADDRESS_KEYS = [\n \"givenName\",\n \"familyName\",\n \"regionCode\",\n \"postalCode\",\n \"addressLine\",\n \"city\",\n \"administrativeArea\",\n] as const;\n\n/**\n * Fold the flat address columns into the nested `address` the contract takes.\n *\n * A row with none of them is left alone. A row with SOME of them keeps them nested and lets the\n * contract refuse it by name — Google needs all four of given name, family name, country and postal\n * code together, and quietly dropping a half-filled address would turn a fixable export mistake into\n * conversions that match nobody.\n */\nfunction nestAddress(row: Record<string, unknown>): Record<string, unknown> {\n const address: Record<string, unknown> = {};\n for (const key of ADDRESS_KEYS) {\n if (row[key] !== undefined) {\n address[key] = row[key];\n delete row[key];\n }\n }\n return Object.keys(address).length > 0 ? { ...row, address } : row;\n}\n\nfunction toRow(record: Record<string, unknown>): { row: Record<string, unknown>; ignored: string[] } {\n const row: Record<string, unknown> = {};\n const ignored: string[] = [];\n for (const [column, raw] of Object.entries(record)) {\n const key = payloadKeyForColumn(column);\n if (!key) {\n if (column.trim() !== \"\") {\n ignored.push(column.trim());\n }\n continue;\n }\n const value = cellValue(key, raw);\n if (value !== undefined) {\n row[key] = value;\n }\n }\n return { row: nestAddress(row), ignored };\n}\n\n/** One cell's payload value, or undefined when the cell is blank and the key should stay absent. */\nfunction cellValue(key: string, raw: unknown): unknown {\n const value = typeof raw === \"string\" ? raw.trim() : raw;\n if (value === \"\" || value === null || value === undefined) {\n return undefined;\n }\n if (!NUMERIC_KEYS.has(key)) {\n return typeof value === \"number\" ? String(value) : value;\n }\n // A spreadsheet writes money as \"€ 1234.50\" as readily as 1234.5, and a NaN here would reach the\n // contract as \"expected a number\" with no hint of which cell. Read what is parseable and leave the\n // rest for validation to name.\n const numeric = typeof value === \"number\" ? value : Number(String(value).replace(/[^\\d.-]/g, \"\"));\n return Number.isFinite(numeric) ? numeric : value;\n}\n\n/**\n * RFC-4180 fields of one CSV line, honouring `\"\"` escapes inside quotes. Deliberately line-based:\n * an embedded newline inside a quoted field is not something a conversion export produces, and\n * supporting it would mean a parser nobody can read for a case nobody has.\n */\nconst CSV_SEPARATORS = new Set([\",\", \";\", \"\\t\"]);\n\nfunction splitCsvLine(line: string): string[] {\n const fields: string[] = [];\n let current = \"\";\n let quoted = false;\n for (let i = 0; i < line.length; i++) {\n const char = line[i];\n if (quoted && char !== '\"') {\n current += char;\n } else if (quoted) {\n // A doubled quote inside a quoted field is one literal quote; a single one closes the field.\n quoted = line[i + 1] === '\"';\n if (quoted) {\n current += '\"';\n i += 1;\n }\n } else if (char === '\"') {\n quoted = true;\n } else if (CSV_SEPARATORS.has(char ?? \"\")) {\n fields.push(current);\n current = \"\";\n } else {\n current += char;\n }\n }\n fields.push(current);\n return fields.map((field) => field.trim());\n}\n\nfunction parseCsv(text: string): ParseConversionRowsResult {\n const lines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n const header = lines.shift();\n if (!header) {\n return { ok: false, error: \"the file is empty\" };\n }\n const columns = splitCsvLine(header);\n if (!columns.some((column) => payloadKeyForColumn(column))) {\n return {\n ok: false,\n error: `no column in \"${columns.join(\", \")}\" is a conversion field — the file needs at least an order id, a date and something to match on (gclid / email / phone)`,\n };\n }\n const rows: Record<string, unknown>[] = [];\n const ignored = new Set<string>();\n for (const line of lines) {\n const fields = splitCsvLine(line);\n const record: Record<string, unknown> = {};\n columns.forEach((column, index) => {\n record[column] = fields[index] ?? \"\";\n });\n const parsed = toRow(record);\n for (const column of parsed.ignored) {\n ignored.add(column);\n }\n rows.push(parsed.row);\n }\n return { ok: true, rows, ignoredColumns: [...ignored] };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The record list inside a JSON document: a bare array, or the `conversions` / `rows` / `data` key of an object. */\nfunction recordsOfJson(parsed: unknown): unknown[] | undefined {\n if (Array.isArray(parsed)) {\n return parsed;\n }\n if (!isRecord(parsed)) {\n return undefined;\n }\n for (const key of [\"conversions\", \"rows\", \"data\", \"results\"]) {\n const value = parsed[key];\n if (Array.isArray(value)) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction parseJsonRecords(records: unknown[]): ParseConversionRowsResult {\n const rows: Record<string, unknown>[] = [];\n const ignored = new Set<string>();\n for (const [index, record] of records.entries()) {\n if (!isRecord(record)) {\n return { ok: false, error: `conversion ${index + 1} is not an object` };\n }\n const parsed = toRow(record);\n for (const column of parsed.ignored) {\n ignored.add(column);\n }\n rows.push(parsed.row);\n }\n return { ok: true, rows, ignoredColumns: [...ignored] };\n}\n\n/**\n * A JSON document's conversions. JSONL is tried first: a file of one object per line also starts\n * with `{`, and `JSON.parse` over the whole of it fails with a message that says nothing about what\n * the file actually is.\n */\nfunction parseJsonText(trimmed: string): ParseConversionRowsResult {\n const lines = trimmed.split(/\\r?\\n/).filter((line) => line.trim().length > 0);\n if (lines.length > 1 && lines.every((line) => line.trim().startsWith(\"{\"))) {\n const records: unknown[] = [];\n for (const [index, line] of lines.entries()) {\n try {\n records.push(JSON.parse(line));\n } catch {\n return { ok: false, error: `line ${index + 1} is not valid JSON` };\n }\n }\n return parseJsonRecords(records);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch (err) {\n return { ok: false, error: `not valid JSON: ${err instanceof Error ? err.message : String(err)}` };\n }\n const records = recordsOfJson(parsed);\n if (!records) {\n return { ok: false, error: \"expected a JSON array of conversions, or an object with a `conversions` array\" };\n }\n return parseJsonRecords(records);\n}\n\n/**\n * The conversions in a file's text, whatever shape it arrived in: JSON (an array or an object with a\n * `conversions` key), newline-delimited JSON, or CSV / TSV / semicolon-separated with a header row.\n * The format is read off the content, not off the extension — an export saved as `.txt` is the same\n * data.\n */\nexport function parseConversionRowsText(text: string): ParseConversionRowsResult {\n const trimmed = text.trim();\n if (trimmed === \"\") {\n return { ok: false, error: \"the file is empty\" };\n }\n if (trimmed.startsWith(\"[\") || trimmed.startsWith(\"{\")) {\n return parseJsonText(trimmed);\n }\n return parseCsv(trimmed);\n}\n\n/** Split a row list into staging-sized batches — one staged op per chunk. */\nexport function chunkConversionRows<T>(rows: readonly T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < rows.length; i += size) {\n chunks.push(rows.slice(i, i + size));\n }\n return chunks;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAE7B,SAAS,qBAAqB;;;ACkB9B,IAAM,iBAAoD;AAAA,EACxD,SAAS,CAAC,WAAW,SAAS,eAAe,iBAAiB,eAAe,gBAAgB,gBAAgB,IAAI;AAAA,EACjH,oBAAoB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,OAAO,CAAC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AAK,mBAAmB,EAAE,KAAK,IAAI;AAC5G,UAAI,qBAAqB,IAAI;AAC3B;AAAA,UACE;AAAA,QACF;AAAA,MACF;AAEA,YAAM,WAAW,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,SAAS,IAAI,aAAa,KAAK,IAAI,IAAI;AACnG,YAAM,YAAY,aAAa,IAAI;AACnC,UAAI,YAAY,WAAW;AACzB;AAAA,UACE;AAAA,QACF;AAAA,MACF;AACA,YAAM,OAAO,UAAU,SAAS,YAAY,CAAC,SAAS,IAAI,CAAC;AAC3D,UAAI,KAAK,WAAW,GAAG;AACrB;AAAA,UACE;AAAA,QACF;AAAA,MACF;AAMA,YAAM,SAAS,oBAAoB,MAAM,0BAA0B;AACnE,YAAM,MAAM,OAAO,IAAI,CAAC,iBAAiB;AAAA,QACvC,MAAM;AAAA,QACN;AAAA,QACA,SAAS,EAAE,kBAAkB,YAAY;AAAA,MAC3C,EAAE;AACF,YAAM,YACJ,OAAO,SAAS,IACZ;AAAA,QACE,GAAG,KAAK,MAAM,0BAA0B,OAAO,MAAM,qBAAqB,0BAA0B,qEAAgE,OAAO,MAAM;AAAA,MACnL,IACA,CAAC;AACP,YAAM;AAAA,QACJ;AAAA,QACA,CAAC,GAAG,WAAW,GAAG,mBAAmB,UAAU,kBAAkB,CAAC,CAAC,GAAG,GAAG,YAAY;AAAA,QACrF,KAAK,SAAS;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["records"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/ads/google/draft.ts","../src/commands/ads/google/draft-batch.ts","../src/commands/ads/google/draft-validate.ts"],"sourcesContent":["import type {\n GoogleDraftListResponse,\n GoogleDraftShowResponse,\n GoogleDraftValidateResponse,\n} from \"@baker/api/ads-google\";\nimport type { GoogleDraftImportResponse } from \"@baker/api/ads-google/wire\";\nimport { defineCommand } from \"citty\";\nimport { apiPost } from \"../../../client.ts\";\nimport { requireChatId, resolveChatId } from \"../../../env.ts\";\nimport { registerSchema, withEffect } from \"../../../schemas.ts\";\nimport { CHAT_READ_ARG, DRAFT_FULL_ARG } from \"../../chat-arg.ts\";\nimport { draftRefs, removeDraftRefs } from \"../../draft-refs.ts\";\nimport {\n LIST_WHERE_ARG,\n parseDraftWhere,\n requireDraftWhere,\n selectDraftRefs,\n WHERE_DESCRIPTION,\n} from \"../../draft-where.ts\";\nimport { SHOW_FULL_ARG, showEnvelope } from \"../draft-show.ts\";\nimport { withHints } from \"../hints.ts\";\nimport { bareCustomerId, writeJsonEnvelope } from \"../output.ts\";\nimport { showAccountHint, validateAccountHint } from \"./draft-account.ts\";\nimport { amendBatchEntries, stageFileOps } from \"./draft-batch.ts\";\nimport { validationEnvelope } from \"./draft-validate.ts\";\nimport {\n draftAction,\n draftListAction,\n failWriteValidation,\n handleGoogleError,\n loadJsonPayloads,\n loadPatchArg,\n requireCustomerId,\n requireTarget,\n STAGE_FULL_ARG,\n stageGoogleOps,\n} from \"./write-shared.ts\";\n\n/** Accepted on the draft reads, as on every other Google Ads command; the draft itself is the chat's. */\nconst DRAFT_ACCOUNT_ARG = {\n type: \"string\",\n description:\n \"10-digit customer id. A draft is per chat and may span accounts: `list` narrows to this one; `validate` and `show` still answer for the whole draft\",\n required: false,\n} as const;\n\nconst VALIDATE_DESCRIPTION = `Ask Google whether the whole staged draft would publish — without applying anything.\n\nStart here, after the last staged change and before telling the user the draft is ready:\n baker ads google draft validate\n\nEvery staged op is built, batched and sent exactly as publish sends it, with Google's validateOnly\nflag, so each verdict is the answer publish would get: accepted | refused | blocked (a change it\ndepends on was refused) | unchecked (only publish can check it) | applied (an earlier publish did).\nCompact by default — counts, plus only the ops that need attention, each with Google's reason.\nFix refused ops with \\`draft amend <ref>\\` and validate again.\n\nIt also reads Baker's day of Google Ads changes, shared by every company. When the draft does\nnot all fit in what is left, the answer carries dailyLimit: operations, room and fitsAt (ISO, when\nall of it should have gone). Publish still works: Baker sends what Google Ads takes and the rest\nagain on its own. Never mention the limit, a quota or operation counts to the user, and never ask\nthem to cut down or split their work for it; say only that some changes go live over the next\nhours, and by when.\n\nExamples:\n baker ads google draft validate\n baker ads google draft validate --full # every op, with its built request and Google's raw answer`;\n\nregisterSchema({\n command: \"ads.google.draft.validate\",\n routes: [\"POST /api/ads/google/draft/validate\"],\n effect: \"read_live\",\n description: VALIDATE_DESCRIPTION,\n args: {\n full: {\n type: \"boolean\",\n description: \"List every op with its built request and Google's raw answer\",\n required: false,\n },\n \"customer-id\": DRAFT_ACCOUNT_ARG,\n },\n});\n\nconst STAGE_DESCRIPTION = `Stage many Google Ads changes from ONE file, in one call — any mix of kinds, up to 500 ops.\n\nStart here whenever a change touches more than a few rows (a keyword cleanup, bid changes, pausing\nads, a list of negatives): write the ops to a file and stage them together instead of running one\ncommand per row.\n baker ads google draft stage --file changes.json --customer-id 1234567890\n\nThe file is a JSON array (or JSON Lines, one op per line). Each op is what the single commands\nbuild — kind, customerId (or --customer-id for all), target for a change to something that exists,\npayload. Read the shape for a kind with \\`baker capabilities google-ads --op <kind>\\`.\n [\n {\"kind\":\"google.keyword.add\",\"payload\":{\"adGroup\":\"customers/1234567890/adGroups/111\",\"text\":\"solar panels\",\"matchType\":\"PHRASE\"}},\n {\"kind\":\"google.keyword.update\",\"target\":\"customers/1234567890/adGroupCriteria/111~222\",\"payload\":{\"status\":\"PAUSED\"}},\n {\"kind\":\"google.negativeKeyword.add\",\"payload\":{\"level\":\"campaign\",\"parent\":\"222333\",\"text\":\"free\",\"matchType\":\"BROAD\"}}\n ]\nA whole new campaign is ONE file: give a create a name with \"as\" (g_temp_<anything>) and later ops\nin the same file name it where a ref goes — budget → campaign → ad groups → keywords, ads, assets and\ntheir links, parents before children:\n {\"kind\":\"google.budget.create\",\"as\":\"g_temp_b1\",\"payload\":{…}}\n {\"kind\":\"google.campaign.create\",\"as\":\"g_temp_c1\",\"payload\":{\"budget\":\"g_temp_b1\",…}}\n {\"kind\":\"google.adGroup.create\",\"as\":\"g_temp_ag1\",\"payload\":{\"campaign\":\"g_temp_c1\",…}}\nThe result is compact: count, byKind, refs (each \"as\" → its real ref; later calls use the real\nref) and only the ops that carry a warning. --full lists every op with its ref. One asset linked\nto many campaigns is one link op per campaign in the same file.\nAn op may also name a g_temp_* ref an EARLIER call returned.\nAll-or-nothing: one invalid op stages nothing. Ops already in effect come back as skipped.\nThen: baker ads google draft validate`;\n\nregisterSchema({\n command: \"ads.google.draft.stage\",\n routes: [\"POST /api/ads/google/draft/stage\", \"POST /api/ads/google/draft/stage-batch\"],\n effect: \"stage\",\n description: STAGE_DESCRIPTION,\n args: {\n file: {\n type: \"string\",\n description: \"JSON array or JSON Lines of ops ({kind, customerId?, target?, payload?, as?}), path or inline\",\n required: true,\n },\n \"customer-id\": {\n type: \"string\",\n description: \"10-digit customer id for every op that does not name its own\",\n required: false,\n },\n full: { type: \"boolean\", description: STAGE_FULL_ARG.description, required: false },\n },\n});\n\nconst IMPORT_DESCRIPTION = `Move another unpublished chat's staged Google Ads changes into this chat, in one call — and out of that chat, so the two can never publish the same change twice.\n\nStart here when the user wants another chat's changes brought into this one (\"bring over\", \"merge\",\n\"include what the other chat prepared\", \"all of them except …\"):\n baker ads google draft import --from-chat <chat-id>\n baker ads google draft import --from-chat <chat-id> --exclude g_temp_a,customers/123/adGroupAds/4~5\n baker ads google draft import --from-chat <chat-id> --refs g_temp_b\n\nEvery op moves exactly as it was staged — same ref, same payload, nothing retyped — so never copy\nanother chat's changes with \\`draft show --chat\\` and re-stage them. An op moves with the creates it\ndepends on and the ops that depend on it (an asset and the link that attaches it go together).\nThe other chat must be unpublished — still open, or its publish failed (a discarded chat's Google Ads\nchanges are gone with it); its other work (Knowledge, Tasks) stays where it is. A published chat's changes its publish could not apply come\nwith \\`baker chats import --from-chat <chat-id> --failed\\` instead. Find chat ids\nwith \\`baker chats list\\`, and refs with \\`baker ads google draft list --chat <chat-id> --json\\`.\nThen: baker ads google draft validate`;\n\nregisterSchema({\n command: \"ads.google.draft.import\",\n routes: [\"POST /api/ads/google/draft/import\"],\n effect: \"stage\",\n description: IMPORT_DESCRIPTION,\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other unpublished chat (open, or its publish failed) whose staged changes move here\",\n required: true,\n },\n refs: {\n type: \"string\",\n description: \"Comma-separated refs to move (default: all); what they depend on comes too\",\n required: false,\n },\n exclude: {\n type: \"string\",\n description: \"Comma-separated refs to leave in the other chat, with the ops that depend on them\",\n required: false,\n },\n },\n});\n\nconst LIST_DESCRIPTION = `Review everything staged as a campaign ▸ ad group ▸ ad tree, each line with its status and the ref that changes it; after publish each line says what Google did (Created · Paused, Failed to create), and a new asset riding on a line listed under it with its ref (--json for the raw envelope with every ref, keywords and links included; --full for every op's payload too).\n\nStart here to read part of a large draft — one kind, or what sits under one campaign — in one call, never the whole draft through a script:\n baker ads google draft list --where kind=asset.create --fields ref,summary,payload.finalUrls\n baker ads google draft list --where 'kind=keyword.add,matchType=EXACT,under=<campaign ref>'`;\n\nconst LIST_ARGS = {\n json: { type: \"boolean\", description: \"Print the raw JSON envelope instead of the readable tree\" },\n full: DRAFT_FULL_ARG,\n chat: CHAT_READ_ARG,\n \"customer-id\": DRAFT_ACCOUNT_ARG,\n where: LIST_WHERE_ARG,\n} as const;\n\nregisterSchema({\n command: \"ads.google.draft.list\",\n routes: [\"POST /api/ads/google/draft\"],\n effect: \"read\",\n description: LIST_DESCRIPTION,\n args: {\n json: { type: \"boolean\", description: \"Print the raw JSON envelope instead of the readable tree\", required: false },\n full: { type: \"boolean\", description: DRAFT_FULL_ARG.description, required: false },\n chat: { type: \"string\", description: CHAT_READ_ARG.description, required: false },\n \"customer-id\": DRAFT_ACCOUNT_ARG,\n where: LIST_WHERE_ARG,\n },\n});\n\nconst WHERE_ARGS = {\n where: {\n type: \"string\",\n description: WHERE_DESCRIPTION,\n required: false,\n },\n \"dry-run\": { type: \"boolean\", description: \"Print the refs that would change, and change nothing\", required: false },\n} as const;\n\nconst REMOVE_DESCRIPTION = `Remove staged ops — one, many, or every op a selector matches, in one call. Each removal cascades to the ops that depend on it.\n\n baker ads google draft remove g_temp_a\n baker ads google draft remove g_temp_a g_temp_b g_temp_c # or g_temp_a,g_temp_b,g_temp_c\n baker ads google draft remove --where 'kind=google.negativeKeyword.add,text=twilio|baileys'\n baker ads google draft remove --where kind=google.keyword.add,under=g_temp_c1 --dry-run\n\nPrints one summary: every op removed (cascades listed once), and any ref the draft did not hold.`;\n\nconst REMOVE_ARGS = {\n ref: {\n type: \"positional\",\n description: \"Staged op ref(s) (g_temp_* or target) — several, space- or comma-separated\",\n required: false,\n },\n ...WHERE_ARGS,\n} as const;\n\nregisterSchema({\n command: \"ads.google.draft.remove\",\n // `--where` reads the staged draft to pick the refs it removes.\n routes: [\"POST /api/ads/google/draft/remove\", \"POST /api/ads/google/draft\"],\n effect: \"unstage\",\n description: REMOVE_DESCRIPTION,\n args: REMOVE_ARGS,\n});\n\nconst AMEND_DESCRIPTION = `Update staged ops in place — merges a JSON patch into each payload (RFC-7386: objects deep-merge, null deletes a key, arrays/scalars replace) and re-validates. Use this instead of remove + re-create.\n\n baker ads google draft amend g_temp_a --patch '{\"cpcBidMicros\":1500000}'\n baker ads google draft amend g_temp_a g_temp_b --patch '{\"status\":\"ENABLED\"}' # same patch, many refs\n baker ads google draft amend --where kind=google.keyword.add,under=g_temp_c1,matchType=EXACT --patch '{\"matchType\":\"BROAD\"}'\n baker ads google draft amend --file amends.json # [{\"ref\":\"g_temp_…\",\"patch\":{…}}, …] — a patch per ref\n\nMany refs are amended in one call, all or none: one refused amend changes nothing.`;\n\nconst AMEND_ARGS = {\n ref: {\n type: \"positional\",\n description:\n \"Staged op ref(s) (g_temp_*) or target id/resource name — several, space- or comma-separated, take the same patch; leave out to amend many from --file\",\n required: false,\n },\n file: {\n type: \"string\",\n description: 'JSON file with the patch object — or, with no ref, a JSON array of {\"ref\",\"patch\"} amends',\n required: false,\n },\n patch: { type: \"string\", description: \"Inline JSON patch object\", required: false },\n ...WHERE_ARGS,\n} as const;\n\nregisterSchema({\n command: \"ads.google.draft.amend\",\n // `--where` reads the staged draft to pick the refs it amends.\n routes: [\"POST /api/ads/google/draft/amend\", \"POST /api/ads/google/draft/amend-batch\", \"POST /api/ads/google/draft\"],\n effect: \"stage\",\n description: AMEND_DESCRIPTION,\n args: AMEND_ARGS,\n});\n\n/**\n * The refs `--where` selects from the staged draft, or undefined without it. Exits with the reason\n * when it cannot select: a malformed selector, refs passed too, or nothing staged that matches.\n */\nasync function refsWhere(args: Record<string, unknown>): Promise<string[] | undefined> {\n if (typeof args.where !== \"string\") return undefined;\n const where = parseDraftWhere(args.where, \"google.\");\n if (\"error\" in where) failWriteValidation(where.error);\n if (draftRefs(args._).length > 0) failWriteValidation(\"pass refs or --where, not both\");\n let ops: GoogleDraftListResponse[\"ops\"] = [];\n try {\n const response = await apiPost<{ ok: boolean; data?: GoogleDraftListResponse }>(\"/api/ads/google/draft\", {\n chatId: requireChatId(),\n full: true,\n });\n ops = response.data?.ops ?? [];\n } catch (err) {\n handleGoogleError(err);\n }\n const refs = selectDraftRefs(ops, where);\n if (refs.length === 0) {\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"NOT_FOUND\",\n message: `--where ${args.where} matches no staged op`,\n fix: \"Read the staged ops' kinds and payload fields with `baker ads google draft list --full`, then adjust the selector.\",\n },\n });\n process.exit(1);\n }\n return refs;\n}\n\n/** `--dry-run`: the refs the command would change, printed instead of changing them. */\nfunction printDryRun(refs: string[]): void {\n writeJsonEnvelope({\n ok: true,\n data: { matched: refs.length, refs },\n hints: [\"Nothing changed. Run it again without --dry-run to apply it.\"],\n });\n}\n\n/** The refs a comma-separated flag names: undefined when the flag is absent, null when it names none. */\nfunction refList(value: unknown): string[] | undefined | null {\n if (typeof value !== \"string\") return undefined;\n const refs = value\n .split(\",\")\n .map((ref) => ref.trim())\n .filter((ref) => ref.length > 0);\n return refs.length > 0 ? refs : null;\n}\n\n/** What the agent needs after a move: the next step, and what the other chat now holds. */\nexport function importHints(fromChatId: string, data: GoogleDraftImportResponse): string[] {\n const source =\n data.sourceRemaining > 0\n ? `Chat ${fromChatId} still has ${data.sourceRemaining} Google Ads change(s) staged, which publish with that chat.`\n : `Chat ${fromChatId} has no Google Ads changes staged any more, so publishing it cannot apply these twice. Its other work stays there — never tell the user to discard it for this.`;\n return [source, \"Run `baker ads google draft validate` next.\"];\n}\n\n/** After a bulk stage: what to do next, and the reminder that the file — not a loop — is the tool. */\nexport const BULK_STAGE_HINTS = [\n \"Run `baker ads google draft validate` next: it asks Google about every staged op at once and lists only the ones it would refuse.\",\n 'To fix several staged ops, amend them together: `baker ads google draft amend --file amends.json` with [{\"ref\":\"…\",\"patch\":{…}}, …].',\n];\n\n/** Review and undo staged Google Ads ops on this chat's draft; `list`/`show` can also read another chat's. */\nexport const draftCommand = defineCommand({\n meta: {\n name: \"draft\",\n description:\n \"Stage many ops from one file, or list (default), validate, remove, clear, amend, or show staged Google Ads write ops for this chat. `list` and `show` take --chat <id> to read an earlier chat's changes instead; `import --from-chat <id>` moves another unpublished chat's staged changes here (open, or its publish failed).\",\n },\n // Declared on the parent too: `default: \"list\"` dispatches the bare `draft --chat <id>` form, and\n // citty reads a value the parent does not know as a subcommand name.\n args: LIST_ARGS,\n // `default`, never `run`: citty falls through to a parent's `run` after the matched subcommand.\n default: \"list\",\n subCommands: {\n stage: defineCommand({\n meta: { name: \"stage\", description: STAGE_DESCRIPTION },\n args: {\n file: {\n type: \"string\",\n description: \"JSON array or JSON Lines of ops ({kind, customerId?, target?, payload?, as?}), path or inline\",\n },\n \"customer-id\": { type: \"string\", description: \"10-digit customer id for every op that does not name its own\" },\n full: STAGE_FULL_ARG,\n },\n run: async ({ args }) => {\n const customerId = typeof args[\"customer-id\"] === \"string\" ? bareCustomerId(args[\"customer-id\"]) : undefined;\n await stageGoogleOps(\n stageFileOps(loadJsonPayloads(args.file), customerId),\n BULK_STAGE_HINTS,\n args.full === true,\n );\n },\n }),\n import: defineCommand({\n meta: { name: \"import\", description: IMPORT_DESCRIPTION },\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other unpublished chat (open, or its publish failed) whose staged changes move here\",\n },\n refs: { type: \"string\", description: \"Comma-separated refs to move (default: all)\" },\n exclude: { type: \"string\", description: \"Comma-separated refs to leave in the other chat\" },\n },\n run: async ({ args }) => {\n const fromChatId = typeof args[\"from-chat\"] === \"string\" ? args[\"from-chat\"].trim() : \"\";\n if (!fromChatId) {\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: \"--from-chat is required\",\n fix: \"Name the other chat: baker ads google draft import --from-chat <chat-id> (ids from `baker chats list`).\",\n },\n });\n process.exit(1);\n }\n const refs = refList(args.refs);\n const exclude = refList(args.exclude);\n const empty = refs === null ? \"--refs\" : exclude === null ? \"--exclude\" : undefined;\n if (empty) {\n // An empty selection must never widen to \"every change\": the move takes them out of the other chat.\n writeJsonEnvelope({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `${empty} names no change`,\n fix: `Pass the refs, comma-separated (from \\`baker ads google draft list --chat ${fromChatId} --json\\`), or leave ${empty} off to move every change.`,\n },\n });\n process.exit(1);\n }\n try {\n const response = await apiPost<{ ok: boolean; data?: GoogleDraftImportResponse }>(\n \"/api/ads/google/draft/import\",\n { chatId: requireChatId(), fromChatId, refs: refs ?? undefined, exclude: exclude ?? undefined },\n );\n writeJsonEnvelope(\n response.ok && response.data ? { ...response, hints: importHints(fromChatId, response.data) } : response,\n );\n } catch (err) {\n handleGoogleError(err);\n }\n },\n }),\n list: defineCommand({\n meta: {\n name: \"list\",\n description: LIST_DESCRIPTION,\n },\n args: LIST_ARGS,\n run: async ({ args }) => {\n const customerId = args[\"customer-id\"] === undefined ? undefined : requireCustomerId(args);\n const selector = typeof args.where === \"string\" ? args.where : undefined;\n const where = selector === undefined ? undefined : { where: requireDraftWhere(selector, \"google.\"), selector };\n await draftListAction(args.json === true, args.chat, args.full === true, customerId, where);\n },\n }),\n remove: defineCommand({\n meta: { name: \"remove\", description: REMOVE_DESCRIPTION },\n args: REMOVE_ARGS,\n run: async ({ args }) => {\n const selected = await refsWhere(args);\n const refs = selected ?? draftRefs(args._);\n if (args[\"dry-run\"] === true) {\n printDryRun(refs);\n return;\n }\n if (selected || refs.length > 1) {\n await removeDraftRefs(\"/api/ads/google/draft/remove\", refs);\n return;\n }\n await draftAction(\"/api/ads/google/draft/remove\", { ref: requireTarget(args, \"op\") });\n },\n }),\n clear: withEffect(\n { effect: \"unstage\", routes: [\"POST /api/ads/google/draft/clear\"] },\n defineCommand({\n meta: { name: \"clear\", description: \"Discard all staged ops on this chat\" },\n run: async () => {\n await draftAction(\"/api/ads/google/draft/clear\", {});\n },\n }),\n ),\n amend: defineCommand({\n meta: { name: \"amend\", description: AMEND_DESCRIPTION },\n args: AMEND_ARGS,\n run: async ({ args }) => {\n const selected = await refsWhere(args);\n const positional = Array.isArray(args._) ? args._[0] : undefined;\n if (!selected && !(args.ref ?? positional) && typeof args.file === \"string\" && args.file.length > 0) {\n const amends = amendBatchEntries(loadJsonPayloads(args.file));\n if (args[\"dry-run\"] === true) {\n printDryRun(amends.map((amend) => amend.ref));\n return;\n }\n await draftAction(\"/api/ads/google/draft/amend-batch\", { amends });\n return;\n }\n const refs = selected ?? draftRefs(args._);\n if (args[\"dry-run\"] === true) {\n printDryRun(refs);\n return;\n }\n if (selected || refs.length > 1) {\n const patch = loadPatchArg(args);\n await draftAction(\"/api/ads/google/draft/amend-batch\", { amends: refs.map((ref) => ({ ref, patch })) });\n return;\n }\n const ref = requireTarget(args, \"op\");\n const patch = loadPatchArg(args);\n await draftAction(\"/api/ads/google/draft/amend\", { ref, patch });\n },\n }),\n validate: defineCommand({\n meta: { name: \"validate\", description: VALIDATE_DESCRIPTION },\n args: {\n full: { type: \"boolean\", description: \"List every op with its built request and Google's raw answer\" },\n \"customer-id\": DRAFT_ACCOUNT_ARG,\n },\n run: async ({ args }) => {\n try {\n const full = args.full === true;\n const response = await apiPost<{ ok: boolean; data?: GoogleDraftValidateResponse }>(\n \"/api/ads/google/draft/validate\",\n { chatId: requireChatId(), full },\n );\n if (!response.ok || !response.data) {\n writeJsonEnvelope(response);\n return;\n }\n const envelope = validationEnvelope(response.data, full);\n const customerId = args[\"customer-id\"];\n writeJsonEnvelope(\n typeof customerId === \"string\"\n ? { ...envelope, hints: [...envelope.hints, validateAccountHint(bareCustomerId(customerId))] }\n : envelope,\n );\n } catch (err) {\n handleGoogleError(err);\n }\n },\n }),\n show: withEffect(\n { effect: \"read\", routes: [\"POST /api/ads/google/draft/show\"] },\n defineCommand({\n meta: {\n name: \"show\",\n description:\n \"Print the staged payload for one op — the receipt to verify a change looks right before publish. A list longer than 50 items (a customer list's members) prints as its count; --full prints every item.\",\n },\n args: {\n ref: {\n type: \"positional\",\n description: \"Staged op ref (g_temp_*) or target id/resource name\",\n required: false,\n },\n chat: CHAT_READ_ARG,\n full: SHOW_FULL_ARG,\n \"customer-id\": DRAFT_ACCOUNT_ARG,\n },\n run: async ({ args }) => {\n const ref = requireTarget(args, \"op\");\n const customerId = args[\"customer-id\"];\n try {\n const response = await apiPost<{ ok: boolean; data?: GoogleDraftShowResponse }>(\n \"/api/ads/google/draft/show\",\n { chatId: resolveChatId(args.chat), ref },\n );\n const hint =\n typeof customerId === \"string\" && response.data\n ? showAccountHint(bareCustomerId(customerId), response.data.op.customerId)\n : undefined;\n const shown = showEnvelope(response, args.full === true);\n writeJsonEnvelope(hint ? withHints(shown, [hint]) : shown);\n } catch (err) {\n handleGoogleError(err);\n }\n },\n }),\n ),\n },\n});\n","import { GOOGLE_DRAFT_BATCH_MAX } from \"@baker/api/ads-google\";\nimport { failWriteValidation } from \"./write-shared.ts\";\n\n/**\n * The bulk halves of `draft`: one file of many changes, staged or amended in ONE request. A bulk\n * change done as a loop of single commands is one request, one rate-limit hit and one tool call per\n * row — production saw 1,284 such calls — while a file is one of each for up to 500 rows.\n */\n\nfunction refuseOversized(count: number, what: string): void {\n if (count > GOOGLE_DRAFT_BATCH_MAX) {\n failWriteValidation(\n `${count} ${what} exceeds the batch limit of ${GOOGLE_DRAFT_BATCH_MAX} — split the file and run the command once per part`,\n );\n }\n}\n\n/**\n * `draft stage --file` items → ops: each item is a whole op (`kind`, `customerId`, `target` for a\n * change to something that exists, `payload`); `--customer-id` fills the account on items that leave\n * it out, so a one-account file need not repeat it. The ops are preflighted by `stageGoogleOps`.\n */\nexport function stageFileOps(\n items: ReadonlyArray<Record<string, unknown>>,\n customerId: string | undefined,\n): Array<Record<string, unknown>> {\n if (items.length === 0) {\n failWriteValidation(\n 'pass --file with the ops to stage: a JSON array (or JSON Lines) of {\"kind\",\"customerId\",\"target\"?,\"payload\"?}',\n );\n }\n refuseOversized(items.length, \"ops\");\n return items.map((item, index) => {\n if (typeof item.kind !== \"string\") {\n failWriteValidation(\n `item ${index} has no \"kind\" — every item is a whole op, e.g. {\"kind\":\"google.keyword.add\",…}`,\n );\n }\n return item.customerId === undefined && customerId ? { ...item, customerId } : item;\n });\n}\n\n/** `draft amend --file` items → the amend batch: each `{ ref, patch }` exactly as `draft amend <ref>` takes it. */\nexport function amendBatchEntries(\n items: ReadonlyArray<Record<string, unknown>>,\n): Array<{ ref: string; patch: Record<string, unknown> }> {\n refuseOversized(items.length, \"amends\");\n return items.map((item, index) => {\n const { ref, patch } = item;\n if (typeof ref !== \"string\" || ref.length === 0) {\n failWriteValidation(`item ${index} has no \"ref\" — name the staged op (g_temp_* or its target) to amend`);\n }\n if (patch === null || typeof patch !== \"object\" || Array.isArray(patch)) {\n failWriteValidation(`item ${index} has no \"patch\" object — {\"ref\":\"…\",\"patch\":{…fields to change…}}`);\n }\n return { ref, patch: patch as Record<string, unknown> };\n });\n}\n","import type { GoogleDraftOpVerdict, GoogleDraftValidateResponse } from \"@baker/api/ads-google\";\n\n/** Verdicts that need nothing from the agent — counted, never listed in the compact view. */\nconst QUIET: ReadonlySet<GoogleDraftOpVerdict[\"verdict\"]> = new Set([\"accepted\", \"applied\"]);\n\nfunction changes(n: number): string {\n return n === 1 ? \"1 change\" : `${n} changes`;\n}\n\n/** What to do next, read off the counts — the agent decides from these without re-reading every op. */\nfunction validationHints(data: GoogleDraftValidateResponse): string[] {\n const { refused, blocked, unchecked } = data.counts;\n const hints: string[] = [];\n if (refused > 0) {\n hints.push(\n `${changes(refused)} would fail at publish. Fix each refused op in place with \\`draft amend <ref>\\` (or \\`draft remove <ref>\\` if it should not exist), then run \\`draft validate\\` again before asking the user to publish. Never tell the user a refused change will go live.`,\n );\n }\n if (blocked > 0) {\n hints.push(\n `${changes(blocked)} would not apply only because a refused change they depend on fails — fixing the refused one clears them.`,\n );\n }\n if (data.publishHeld) {\n hints.push(\n \"Baker would hold this whole publish: a refused change stops a first publish from sending anything. Fix it first.\",\n );\n }\n if (unchecked > 0) {\n hints.push(\n `${changes(unchecked)} can only be checked by Google at publish (the reason is on each one). Nothing here says they will fail.`,\n );\n }\n if (refused + blocked === 0 && !data.publishHeld && data.ops.length > 0) {\n hints.push(\n \"Google accepted every change it was asked about. The draft is ready for the user to review and publish.\",\n );\n }\n if (data.dailyLimit) {\n hints.push(\n `Not every change may go live the moment the user publishes: Baker sends what Google Ads takes then and the rest again on its own, all by about ${data.dailyLimit.fitsAt}, with nothing for the user to do. If you tell the user anything, say only that some changes will go live over the next hours and by when, in their time zone. Never mention a daily limit, quota, allowance or number of operations, and never ask them to cut down or split their work for it.`,\n );\n }\n return hints;\n}\n\n/**\n * The `draft validate` envelope. Compact by default: counts for everything, and only the ops that\n * need attention listed — a 300-keyword draft that Google accepts reads as one line, not 300.\n * `full` keeps every op with its built request and Google's raw answer.\n */\nexport function validationEnvelope(\n data: GoogleDraftValidateResponse,\n full = false,\n): { ok: true; data: GoogleDraftValidateResponse; hints: string[] } {\n const ops = full ? data.ops : data.ops.filter((op) => !QUIET.has(op.verdict));\n return { ok: true, data: { ...data, ops }, hints: validationHints(data) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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