@koda-sl/baker-cli 0.883.0 → 0.885.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/{account-assets-FJFPB7KD.js → account-assets-Q2O3FRUE.js} +6 -6
- package/dist/{account-level-CB6I4X5W.js → account-level-NBEQ6R7X.js} +3 -3
- package/dist/{account-reads-TSDWJ3A2.js → account-reads-7DPRPWBK.js} +3 -2
- package/dist/{account-reads-TSDWJ3A2.js.map → account-reads-7DPRPWBK.js.map} +1 -1
- package/dist/{ads-ZSHBQHNK.js → ads-4QBIYBPH.js} +3 -3
- package/dist/{ads-G3N76HWA.js → ads-HKPBNXWT.js} +10 -10
- package/dist/{adsets-2HV6TJJP.js → adsets-IBLZP6EM.js} +9 -9
- package/dist/{analytics-6TNLZ4LA.js → analytics-E5OPCERI.js} +6 -5
- package/dist/{analytics-6TNLZ4LA.js.map → analytics-E5OPCERI.js.map} +1 -1
- package/dist/{asset-writes-ZOVD5O5X.js → asset-writes-NTEJDVVM.js} +3 -3
- package/dist/{audience-writes-36E6ECON.js → audience-writes-DJHKIJP7.js} +2 -2
- package/dist/{audiences-65JSGH4L.js → audiences-7TGXZS3M.js} +6 -6
- package/dist/{campaigns-PP3MFPJR.js → campaigns-VD7UOTRV.js} +9 -9
- package/dist/{catalogs-UYYPZRFW.js → catalogs-H2T4Z6AS.js} +2 -2
- package/dist/{changes-7WLOTKVE.js → changes-FQ2NWBJQ.js} +3 -2
- package/dist/{changes-7WLOTKVE.js.map → changes-FQ2NWBJQ.js.map} +1 -1
- package/dist/{chunk-Z65I6WS6.js → chunk-DX4SRYED.js} +13 -5
- package/dist/chunk-DX4SRYED.js.map +1 -0
- package/dist/{chunk-J464JWY7.js → chunk-ENTB4ILS.js} +8 -4
- package/dist/chunk-ENTB4ILS.js.map +1 -0
- package/dist/{chunk-JOQBRK4E.js → chunk-FRWCTFTP.js} +9 -4
- package/dist/chunk-FRWCTFTP.js.map +1 -0
- package/dist/{chunk-BRHYK4HQ.js → chunk-G7Q43JEZ.js} +5 -4
- package/dist/{chunk-BRHYK4HQ.js.map → chunk-G7Q43JEZ.js.map} +1 -1
- package/dist/{chunk-BX5AAH7T.js → chunk-IDLSLJIM.js} +4 -2
- package/dist/{chunk-BX5AAH7T.js.map → chunk-IDLSLJIM.js.map} +1 -1
- package/dist/{chunk-ZGYIG6OM.js → chunk-LUF2VYOK.js} +2 -2
- package/dist/chunk-LVLAFUXQ.js +37 -0
- package/dist/chunk-LVLAFUXQ.js.map +1 -0
- package/dist/{chunk-3F6AXSPB.js → chunk-ZJUUAZKY.js} +2 -2
- package/dist/cli.js +6 -6
- package/dist/{config-UR3ZKS25.js → config-Z52BRC3M.js} +3 -2
- package/dist/{config-UR3ZKS25.js.map → config-Z52BRC3M.js.map} +1 -1
- package/dist/{conversion-upload-command-CWMZEFCT.js → conversion-upload-command-ZZ5JYMBL.js} +7 -4
- package/dist/conversion-upload-command-ZZ5JYMBL.js.map +1 -0
- package/dist/{copy-writes-TEJRR2W2.js → copy-writes-FGMJ7N75.js} +3 -3
- package/dist/{creatives-ZYY5OF5U.js → creatives-67CDPYL7.js} +4 -4
- package/dist/{custom-conversions-YQPOB2IR.js → custom-conversions-RZB2622Q.js} +4 -4
- package/dist/{draft-KMRFGWIO.js → draft-3L5UZ3JP.js} +7 -4
- package/dist/draft-3L5UZ3JP.js.map +1 -0
- package/dist/{draft-XWJF772C.js → draft-CZEMQHTX.js} +3 -2
- package/dist/{draft-XWJF772C.js.map → draft-CZEMQHTX.js.map} +1 -1
- package/dist/{draft-5H6MKAKW.js → draft-FOHLBTWV.js} +3 -2
- package/dist/{draft-5H6MKAKW.js.map → draft-FOHLBTWV.js.map} +1 -1
- package/dist/{draft-OHAOBGVP.js → draft-JPWMFZNZ.js} +243 -8
- package/dist/draft-JPWMFZNZ.js.map +1 -0
- package/dist/{forecast-WTVRSFFA.js → forecast-SXZBIHFB.js} +3 -2
- package/dist/{forecast-WTVRSFFA.js.map → forecast-SXZBIHFB.js.map} +1 -1
- package/dist/{ga4-K6ARTEPX.js → ga4-6J3IMDSU.js} +12 -12
- package/dist/{google-N3GW4MDV.js → google-F77XV4ZC.js} +59 -40
- package/dist/google-F77XV4ZC.js.map +1 -0
- package/dist/{hubspot-BG4BI3RU.js → hubspot-24MLH5N7.js} +2 -2
- package/dist/{instant-experiences-YXH2AHFI.js → instant-experiences-MF2X374W.js} +2 -2
- package/dist/{leads-IGOXMIEW.js → leads-IBXGNXTX.js} +2 -2
- package/dist/{media-QOGVG6CU.js → media-YPVGQ535.js} +3 -3
- package/dist/{meta-RJH5COPE.js → meta-ZQXCUKHQ.js} +30 -30
- package/dist/{page-photos-P2XMKTVF.js → page-photos-BEAMTVP5.js} +2 -2
- package/dist/{plan-C5U4U55M.js → plan-JVD6BMEO.js} +3 -2
- package/dist/{plan-C5U4U55M.js.map → plan-JVD6BMEO.js.map} +1 -1
- package/dist/{read-UXFNPEQ5.js → read-VI63RNL6.js} +3 -2
- package/dist/{read-UXFNPEQ5.js.map → read-VI63RNL6.js.map} +1 -1
- package/dist/{rule-writes-MSMVQDQO.js → rule-writes-CVP6CH2R.js} +2 -2
- package/dist/{rules-UEKJOZTV.js → rules-LZ36YNG3.js} +7 -7
- package/dist/{search-terms-WKE47TW5.js → search-terms-SWRRTKBV.js} +3 -2
- package/dist/{search-terms-WKE47TW5.js.map → search-terms-SWRRTKBV.js.map} +1 -1
- package/dist/{sends-5UCPQZ7F.js → sends-PEQJOPRM.js} +19 -4
- package/dist/sends-PEQJOPRM.js.map +1 -0
- package/dist/{shopify-NJFARTN3.js → shopify-IRHELCGF.js} +3 -2
- package/dist/{shopify-NJFARTN3.js.map → shopify-IRHELCGF.js.map} +1 -1
- package/dist/{sources-XYKENWZF.js → sources-CACBM65R.js} +38 -17
- package/dist/sources-CACBM65R.js.map +1 -0
- package/dist/{studies-TIF7PYEB.js → studies-Y6PGWT66.js} +5 -5
- package/dist/{study-writes-RGKBOOJ6.js → study-writes-6F6O6N4E.js} +2 -2
- package/dist/{tag-manager-5Q5MHQPL.js → tag-manager-QO6VW57E.js} +10 -10
- package/dist/{targeting-YWOOD6YL.js → targeting-FRMVSXXL.js} +2 -2
- package/dist/{themes-LWG3LX7O.js → themes-GMZOWC3X.js} +3 -2
- package/dist/{themes-LWG3LX7O.js.map → themes-GMZOWC3X.js.map} +1 -1
- package/dist/{write-commands-REUTFNJ3.js → write-commands-3BMPDY3K.js} +4 -4
- package/dist/{write-commands-IAMIUSK4.js → write-commands-GRBE5V34.js} +3 -2
- package/dist/{write-commands-IAMIUSK4.js.map → write-commands-GRBE5V34.js.map} +1 -1
- package/dist/{write-commands-JXP2NHRY.js → write-commands-MZUVJBGO.js} +3 -2
- package/dist/{write-commands-JXP2NHRY.js.map → write-commands-MZUVJBGO.js.map} +1 -1
- package/package.json +1 -1
- package/dist/chunk-J464JWY7.js.map +0 -1
- package/dist/chunk-JOQBRK4E.js.map +0 -1
- package/dist/chunk-Z65I6WS6.js.map +0 -1
- package/dist/conversion-upload-command-CWMZEFCT.js.map +0 -1
- package/dist/draft-KMRFGWIO.js.map +0 -1
- package/dist/draft-OHAOBGVP.js.map +0 -1
- package/dist/google-N3GW4MDV.js.map +0 -1
- package/dist/sends-5UCPQZ7F.js.map +0 -1
- package/dist/sources-XYKENWZF.js.map +0 -1
- /package/dist/{account-assets-FJFPB7KD.js.map → account-assets-Q2O3FRUE.js.map} +0 -0
- /package/dist/{account-level-CB6I4X5W.js.map → account-level-NBEQ6R7X.js.map} +0 -0
- /package/dist/{ads-ZSHBQHNK.js.map → ads-4QBIYBPH.js.map} +0 -0
- /package/dist/{ads-G3N76HWA.js.map → ads-HKPBNXWT.js.map} +0 -0
- /package/dist/{adsets-2HV6TJJP.js.map → adsets-IBLZP6EM.js.map} +0 -0
- /package/dist/{asset-writes-ZOVD5O5X.js.map → asset-writes-NTEJDVVM.js.map} +0 -0
- /package/dist/{audience-writes-36E6ECON.js.map → audience-writes-DJHKIJP7.js.map} +0 -0
- /package/dist/{audiences-65JSGH4L.js.map → audiences-7TGXZS3M.js.map} +0 -0
- /package/dist/{campaigns-PP3MFPJR.js.map → campaigns-VD7UOTRV.js.map} +0 -0
- /package/dist/{catalogs-UYYPZRFW.js.map → catalogs-H2T4Z6AS.js.map} +0 -0
- /package/dist/{chunk-ZGYIG6OM.js.map → chunk-LUF2VYOK.js.map} +0 -0
- /package/dist/{chunk-3F6AXSPB.js.map → chunk-ZJUUAZKY.js.map} +0 -0
- /package/dist/{copy-writes-TEJRR2W2.js.map → copy-writes-FGMJ7N75.js.map} +0 -0
- /package/dist/{creatives-ZYY5OF5U.js.map → creatives-67CDPYL7.js.map} +0 -0
- /package/dist/{custom-conversions-YQPOB2IR.js.map → custom-conversions-RZB2622Q.js.map} +0 -0
- /package/dist/{ga4-K6ARTEPX.js.map → ga4-6J3IMDSU.js.map} +0 -0
- /package/dist/{hubspot-BG4BI3RU.js.map → hubspot-24MLH5N7.js.map} +0 -0
- /package/dist/{instant-experiences-YXH2AHFI.js.map → instant-experiences-MF2X374W.js.map} +0 -0
- /package/dist/{leads-IGOXMIEW.js.map → leads-IBXGNXTX.js.map} +0 -0
- /package/dist/{media-QOGVG6CU.js.map → media-YPVGQ535.js.map} +0 -0
- /package/dist/{meta-RJH5COPE.js.map → meta-ZQXCUKHQ.js.map} +0 -0
- /package/dist/{page-photos-P2XMKTVF.js.map → page-photos-BEAMTVP5.js.map} +0 -0
- /package/dist/{rule-writes-MSMVQDQO.js.map → rule-writes-CVP6CH2R.js.map} +0 -0
- /package/dist/{rules-UEKJOZTV.js.map → rules-LZ36YNG3.js.map} +0 -0
- /package/dist/{studies-TIF7PYEB.js.map → studies-Y6PGWT66.js.map} +0 -0
- /package/dist/{study-writes-RGKBOOJ6.js.map → study-writes-6F6O6N4E.js.map} +0 -0
- /package/dist/{tag-manager-5Q5MHQPL.js.map → tag-manager-QO6VW57E.js.map} +0 -0
- /package/dist/{targeting-YWOOD6YL.js.map → targeting-FRMVSXXL.js.map} +0 -0
- /package/dist/{write-commands-REUTFNJ3.js.map → write-commands-3BMPDY3K.js.map} +0 -0
|
@@ -1 +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;\n }\n process.stdout.write(`${renderDraft(data)}${hintLines(response)}\\n`);\n } catch (err) {\n handleError(err);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAgBtB,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,gCAAgC;AAAA,EACnE;AACA,SAAO;AACT;AAEA,SAAS,eAAe,MAA+B,MAAiC;AACtF,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,SAAS,IAC5C,SACA;AACR,MAAI,QAAQ,QAAW;AACrB,mBAAe,UAAU,IAAI,wDAAwD;AAAA,EACvF;AACA,MAAI;AACF,WAAO,KAAK,MA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jC,MAAI;AACF,UAAM,WAAW,MAAM,QAA8B,kBAAkB;AAAA,MACrE;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/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 =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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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,qBAAqB;;;ACG9B,SAAS,gBAAgB,OAAe,MAAoB;AAC1D,MAAI,QAAQ,wBAAwB;AAClC;AAAA,MACE,GAAG,KAAK,IAAI,IAAI,+BAA+B,sBAAsB;AAAA,IACvE;AAAA,EACF;AACF;AAOO,SAAS,aACd,OACA,YACgC;AAChC,MAAI,MAAM,WAAW,GAAG;AACtB;AAAA,MACE;AAAA,IACF;AAAA,EACF;AACA,kBAAgB,MAAM,QAAQ,KAAK;AACnC,SAAO,MAAM,IAAI,CAAC,MAAM,UAAU;AAChC,QAAI,OAAO,KAAK,SAAS,UAAU;AACjC;AAAA,QACE,QAAQ,KAAK;AAAA,MACf;AAAA,IACF;AACA,WAAO,KAAK,eAAe,UAAa,aAAa,EAAE,GAAG,MAAM,WAAW,IAAI;AAAA,EACjF,CAAC;AACH;AAGO,SAAS,kBACd,OACwD;AACxD,kBAAgB,MAAM,QAAQ,QAAQ;AACtC,SAAO,MAAM,IAAI,CAAC,MAAM,UAAU;AAChC,UAAM,EAAE,KAAK,MAAM,IAAI;AACvB,QAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,GAAG;AAC/C,0BAAoB,QAAQ,KAAK,2EAAsE;AAAA,IACzG;AACA,QAAI,UAA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AU,KAAK,SAAS,IAAI;AACvD,8BAAkB,OAAO,UAAU,OAAO,CAAC,IAAI,CAAC,IAAI,KAAK;AAAA,UAC3D,SAAS,KAAK;AACZ,8BAAkB,GAAG;AAAA,UACvB;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;","names":["patch","ref"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/ads/meta/draft.ts","../src/commands/ads/meta/draft-status.ts"],"sourcesContent":["import type {\n MetaDraftClearResponse,\n MetaDraftListResponse,\n MetaDraftRemoveResponse,\n MetaDraftShowResponse,\n} from \"@baker/api/ads-meta\";\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 { draftListWhere, LIST_WHERE_ARG, requireDraftWhere, wholeDraftHints } from \"../../draft-where.ts\";\nimport { SHOW_FULL_ARG, showEnvelope } from \"../draft-show.ts\";\nimport { hintLines, withHints } from \"../hints.ts\";\nimport { writeJsonEnvelope } from \"../output.ts\";\nimport { renderDraftStatus } from \"./draft-status.ts\";\nimport { handleMetaError } from \"./shared.ts\";\n\nregisterSchema({\n command: \"ads.meta.draft\",\n routes: [\"POST /api/ads/meta/draft\"],\n effect: \"read\",\n description:\n \"Review every Meta op staged on this chat, one line each: ref · kind · summary · the ad set (or campaign) a staged ad (or ad set) goes into with the status it publishes under · what it waits on · ✗ blocked: <why> when publish would now refuse it, and after a publish ✓ applied → id or ✗ failed: <error>. `draft show <ref>` prints one op's payload (--full for lists over 50 items).\",\n args: {\n json: { type: \"boolean\", description: \"Raw JSON envelope instead of the readable list\", required: false },\n full: { type: \"boolean\", description: DRAFT_FULL_ARG.description, required: false },\n chat: { type: \"string\", description: \"Read another chat's draft instead of this one\", required: false },\n where: LIST_WHERE_ARG,\n },\n});\n\n/**\n * The readable one-line-per-op view is the default, like the Google, LinkedIn and X drafts;\n * `--json` (or `--output json`) returns the raw envelope for tools.\n */\nasync function listDraft(json: boolean, chat?: unknown, full = false, selector?: string): Promise<void> {\n const where = selector === undefined ? undefined : requireDraftWhere(selector);\n try {\n const chatId = resolveChatId(chat);\n const response = await apiPost<{ ok: boolean; data?: MetaDraftListResponse }>(\"/api/ads/meta/draft\", {\n chatId,\n ...(full || where ? { full: true } : {}),\n });\n if (where && selector !== undefined && response.ok && response.data) {\n const narrowed = draftListWhere(response.data, where, selector);\n writeJsonEnvelope(withHints({ ...response, data: narrowed.data }, narrowed.hints));\n return;\n }\n if (json || full || !response.ok || !response.data) {\n const whole = response.ok && response.data ? wholeDraftHints(response.data.ops, \"baker ads meta draft list\") : [];\n writeJsonEnvelope(withHints(response, whole));\n return;\n }\n process.stdout.write(`${renderDraftStatus(response.data)}${hintLines(response)}\\n`);\n } catch (err) {\n handleMetaError(err);\n }\n}\n\nconst listCommand = defineCommand({\n meta: {\n name: \"list\",\n description:\n \"Show every Meta write op staged in this chat, one line each (ref · kind · summary · parent ad set or campaign and its status · dependencies · post-publish result), with staged ads counted by their ad set's status; --json for the raw envelope, --full for every op's payload too. Publishing reaches the real ad account, so review this before you finish. Example: baker ads meta draft\",\n },\n args: {\n json: { type: \"boolean\", description: \"Print the raw JSON envelope instead of the readable list\" },\n full: DRAFT_FULL_ARG,\n chat: CHAT_READ_ARG,\n where: LIST_WHERE_ARG,\n },\n run: async ({ args }) => {\n await listDraft(\n args.json === true,\n args.chat,\n args.full === true,\n typeof args.where === \"string\" ? args.where : undefined,\n );\n },\n});\n\nconst showCommand = 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. Example: baker ads meta draft show meta_temp_abc123\",\n },\n args: {\n ref: { type: \"positional\", description: \"Op ref (meta_temp_* for creates, target id for updates)\", required: true },\n // `show` always prints the envelope; `--json` is the spelling `list` taught, so it is accepted here too.\n json: { type: \"boolean\", description: \"Accepted for symmetry with list; show always prints the JSON envelope\" },\n chat: CHAT_READ_ARG,\n full: SHOW_FULL_ARG,\n },\n run: async ({ args }) => {\n try {\n const chatId = resolveChatId(args.chat);\n const response = await apiPost<{ ok: true; data: MetaDraftShowResponse }>(\"/api/ads/meta/draft/show\", {\n chatId,\n ref: args.ref,\n });\n writeJsonEnvelope(showEnvelope(response, args.full === true));\n } catch (err) {\n handleMetaError(err);\n }\n },\n});\n\nconst removeCommand = defineCommand({\n meta: {\n name: \"remove\",\n description:\n \"Drop staged Meta ops — one, or many in one call. Removing a create cascades to everything that depends on it. Example: baker ads meta draft remove meta_temp_abc123 meta_temp_def456\",\n },\n args: {\n ref: {\n type: \"positional\",\n description: \"Op ref(s) (meta_temp_* for creates, target id for updates) — several, space- or comma-separated\",\n required: true,\n },\n },\n run: async ({ args }) => {\n const refs = draftRefs(args._);\n if (refs.length > 1) {\n await removeDraftRefs(\"/api/ads/meta/draft/remove\", refs);\n return;\n }\n try {\n const chatId = requireChatId();\n const response = await apiPost<{ ok: true; data: MetaDraftRemoveResponse }>(\"/api/ads/meta/draft/remove\", {\n chatId,\n ref: args.ref,\n });\n writeJsonEnvelope(response);\n } catch (err) {\n handleMetaError(err);\n }\n },\n});\n\nconst clearCommand = defineCommand({\n meta: {\n name: \"clear\",\n description:\n \"Discard ALL staged Meta ops in this chat's draft — nothing will apply on publish. Example: baker ads meta draft clear\",\n },\n run: async () => {\n try {\n const chatId = requireChatId();\n const response = await apiPost<{ ok: true; data: MetaDraftClearResponse }>(\"/api/ads/meta/draft/clear\", {\n chatId,\n });\n writeJsonEnvelope(response);\n } catch (err) {\n handleMetaError(err);\n }\n },\n});\n\nwithEffect({ effect: \"read\", routes: [\"POST /api/ads/meta/draft\"] }, listCommand);\nwithEffect({ effect: \"read\", routes: [\"POST /api/ads/meta/draft/show\"] }, showCommand);\nwithEffect({ effect: \"unstage\", routes: [\"POST /api/ads/meta/draft/remove\"] }, removeCommand);\nwithEffect({ effect: \"unstage\", routes: [\"POST /api/ads/meta/draft/clear\"] }, clearCommand);\n\nexport const metaDraftCommand = defineCommand({\n meta: {\n name: \"draft\",\n description:\n \"Review and edit the Meta write ops staged in this chat BEFORE publish. Subcommands: list (default), show, remove, clear. Ops never hit Meta until the chat is published. `list` and `show` take --chat <id> to read an earlier chat's changes instead.\",\n },\n // Declared on the parent too: `default: \"list\"` dispatches the bare `draft --chat <id>` form, and\n // citty prints help for a flag the parent does not know instead of forwarding it.\n args: {\n json: { type: \"boolean\", description: \"Print the raw JSON envelope instead of the readable list\" },\n full: DRAFT_FULL_ARG,\n chat: CHAT_READ_ARG,\n where: LIST_WHERE_ARG,\n },\n subCommands: { list: listCommand, show: showCommand, remove: removeCommand, clear: clearCommand },\n // `default` (not `run`) dispatches the bare invocation: citty falls through to `run`\n // after dispatching a subcommand, so a `run` here would list the draft a second time\n // on every `draft list` / `draft remove` / `draft clear`.\n default: \"list\",\n});\n","import type { MetaDraftListResponse, MetaDraftOpView } from \"@baker/api/ads-meta\";\n\n/**\n * Render the staged Meta draft as one line per op — ref, kind, summary, what it\n * waits on and, after a publish, what happened to it. The Google, LinkedIn and\n * X drafts already print a readable view by default; Meta printed the pretty\n * JSON envelope, and agents piped every read through python to get these same\n * columns back. Pure: takes the draft-list response, returns text.\n */\n\nconst STATUS_HEADINGS: Record<MetaDraftListResponse[\"status\"], string> = {\n active: \"staged\",\n publishing: \"publishing\",\n applied: \"published\",\n partial: \"published with failures\",\n discarded: \"discarded\",\n none: \"none\",\n};\n\nfunction plural(count: number, word: string): string {\n return `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n}\n\nfunction headingLine(draft: MetaDraftListResponse): string {\n const heading = STATUS_HEADINGS[draft.status];\n if (draft.status === \"active\" || draft.status === \"discarded\") {\n return `Meta Ads — ${plural(draft.count, \"change\")} ${heading} · ${draft.mode}`;\n }\n const counts = new Map<string, number>();\n for (const op of draft.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 return `Meta Ads — ${heading} · ${summary} · ${draft.mode}`;\n}\n\n/** A failed op: why, and what of it already reached Meta. */\nfunction failedPart(result: NonNullable<MetaDraftOpView[\"result\"]>): string {\n const landed = result.landed ? ` (${result.landed})` : \"\";\n return `✗ failed: ${result.error ?? \"no reason recorded\"}${landed}`;\n}\n\nfunction resultPart(op: MetaDraftOpView): string | undefined {\n const result = op.result;\n if (!result) {\n return undefined;\n }\n if (result.status === \"failed\") {\n return failedPart(result);\n }\n if (result.status === \"skipped\") {\n // Publish records either the dependency ref that did not apply or a plain reason; either way the op is finished.\n const because = result.skippedBecause;\n if (because && op.dependsOn.includes(because)) {\n return `✗ skipped: ${because} did not apply`;\n }\n return `✗ skipped: ${because ?? \"a change it needs did not apply\"}`;\n }\n const id = result.id ?? result.hash;\n const applied = `✓ ${result.status}${id ? ` → ${id}` : \"\"}`;\n const verification = result.verification;\n if (verification && verification.status !== \"confirmed\") {\n return `${applied} (read-back ${verification.status}${verification.note ? `: ${verification.note}` : \"\"})`;\n }\n return applied;\n}\n\nconst PARENT_WORD: Record<string, string> = {\n \"ad.create\": \"ad set\",\n \"ad.copy\": \"ad set\",\n \"adSet.create\": \"campaign\",\n \"adSet.copy\": \"campaign\",\n};\n\nconst STAGED_AD_KINDS: ReadonlySet<string> = new Set([\"ad.create\", \"ad.copy\"]);\n\n/** Where a staged ad (or ad set) goes, and the status that parent publishes with. */\nfunction parentPart(op: MetaDraftOpView): string | undefined {\n const parent = op.parent;\n if (!parent) {\n return undefined;\n }\n const word = PARENT_WORD[op.kind] ?? \"parent\";\n const named = parent.name ? `\"${parent.name}\" (${parent.ref})` : parent.ref;\n const staged = parent.staged ? \", staged here\" : \"\";\n const status = parent.status\n ? `${parent.statusBefore ? `${parent.statusBefore} → ` : \"\"}${parent.status}`\n : \"status not recorded\";\n return `in ${word} ${named}${staged} ${status}`;\n}\n\n/** \"Which staged ads will run\" in one line: ads counted by the status of the ad set they go into. */\nfunction adParentStatusLine(ops: readonly MetaDraftOpView[]): string | undefined {\n const counts = new Map<string, number>();\n for (const op of ops) {\n if (STAGED_AD_KINDS.has(op.kind) && op.parent) {\n const status = op.parent.status ?? \"not recorded\";\n counts.set(status, (counts.get(status) ?? 0) + 1);\n }\n }\n if (counts.size === 0) {\n return undefined;\n }\n return `Staged ads by ad set status: ${[...counts].map(([status, count]) => `${count} ${status}`).join(\", \")}`;\n}\n\nfunction readinessLine(ops: readonly MetaDraftOpView[]): string {\n const blocked = ops.filter((op) => op.blocked);\n if (blocked.length === 0) {\n return \"Every change passed its checks when staged — no need to re-check them.\";\n }\n // A first publish holds every change beside a refused one; only the refused ones need fixing.\n const heldBack = blocked.filter((op) => op.heldBack).length;\n const refused = blocked.length - heldBack;\n const held =\n heldBack === 0\n ? \"\"\n : `; the other ${plural(heldBack, \"change\")} ${heldBack === 1 ? \"is\" : \"are\"} held back with ${refused === 1 ? \"it\" : \"them\"} and need${heldBack === 1 ? \"s\" : \"\"} nothing`;\n return `${plural(refused, \"change\")} passed its checks when staged but would be refused now (✗ blocked below) — fix or remove ${refused === 1 ? \"it\" : \"them\"} before publishing${held}.`;\n}\n\nfunction opLine(op: MetaDraftOpView, showAccount: boolean): string {\n const parts = [op.ref, op.kind, op.summary];\n if (op.target && op.target !== op.ref) {\n parts.push(`target ${op.target}`);\n }\n if (showAccount) {\n parts.push(`account ${op.accountId}`);\n }\n const parent = parentPart(op);\n if (parent) {\n parts.push(parent);\n }\n if (op.dependsOn.length > 0) {\n parts.push(`after ${op.dependsOn.join(\", \")}`);\n }\n if (op.blocked) {\n parts.push(`✗ blocked: ${op.blocked}`);\n }\n const result = resultPart(op);\n if (result) {\n parts.push(result);\n }\n // Creative copy and provider errors can carry line breaks; one op stays one line.\n return ` ${parts.join(\" · \").replace(/[\\r\\n]+/g, \" \")}`;\n}\n\nexport function renderDraftStatus(draft: MetaDraftListResponse): string {\n if (draft.status === \"none\" || draft.count === 0) {\n return \"No staged Meta changes on this chat.\";\n }\n const lines = [headingLine(draft)];\n if (draft.status === \"active\") {\n lines.push(\"Publishing makes every change real on the ad account.\", readinessLine(draft.ops));\n }\n const adParents = adParentStatusLine(draft.ops);\n if (adParents) {\n lines.push(adParents);\n }\n lines.push(\"\");\n // A draft may span several ad accounts; the account is only noise when there is one.\n const showAccount = new Set(draft.ops.map((op) => op.accountId)).size > 1;\n for (const op of draft.ops) {\n lines.push(opLine(op, showAccount));\n }\n if (draft.advisories.length > 0) {\n lines.push(\"\", \"Advisories\");\n for (const advisory of draft.advisories) {\n lines.push(` ! ${advisory.ref}: ${advisory.message}`);\n }\n }\n lines.push(\n \"\",\n \"Staged payload for one op: baker ads meta draft show <ref> (--full for lists over 50 items) · raw envelope: --json\",\n );\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,qBAAqB;;;ACI9B,IAAM,kBAAmE;AAAA,EACvE,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW;AAAA,EACX,MAAM;AACR;AAEA,SAAS,OAAO,OAAe,MAAsB;AACnD,SAAO,GAAG,KAAK,IAAI,IAAI,GAAG,UAAU,IAAI,KAAK,GAAG;AAClD;AAEA,SAAS,YAAY,OAAsC;AACzD,QAAM,UAAU,gBAAgB,MAAM,MAAM;AAC5C,MAAI,MAAM,WAAW,YAAY,MAAM,WAAW,aAAa;AAC7D,WAAO,mBAAc,OAAO,MAAM,OAAO,QAAQ,CAAC,IAAI,OAAO,SAAM,MAAM,IAAI;AAAA,EAC/E;AACA,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,MAAM,MAAM,KAAK;AAC1B,UAAM,S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