siluzan-tso-cli 1.1.54-beta.2 → 1.1.54-beta.4

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/dist/index.js CHANGED
@@ -2582,6 +2582,27 @@ async function parseApiResponse(status, text2, verbose) {
2582
2582
  return text2;
2583
2583
  }
2584
2584
  }
2585
+ function isTransientNetworkError(err) {
2586
+ const msg = err instanceof Error ? err.message : String(err);
2587
+ const code = err?.code;
2588
+ if (typeof code === "string" && ["ECONNRESET", "EPIPE", "ETIMEDOUT", "ECONNABORTED"].includes(code)) {
2589
+ return true;
2590
+ }
2591
+ return /响应解压失败|aborted|socket hang up|ECONNRESET|unexpected end of file/i.test(msg);
2592
+ }
2593
+ async function requestWithReadRetry(url, options) {
2594
+ const method = (options.method ?? "GET").toUpperCase();
2595
+ for (let attempt = 0; ; attempt++) {
2596
+ try {
2597
+ return await rawRequest(url, options);
2598
+ } catch (err) {
2599
+ if (method !== "GET" || attempt >= GET_RETRY_DELAYS_MS.length || !isTransientNetworkError(err)) {
2600
+ throw err;
2601
+ }
2602
+ await new Promise((r) => setTimeout(r, GET_RETRY_DELAYS_MS[attempt]));
2603
+ }
2604
+ }
2605
+ }
2585
2606
  async function apiFetch(url, config, options = {}, verbose = false) {
2586
2607
  const method = options.method ?? "GET";
2587
2608
  const reqHeaders = {
@@ -2595,7 +2616,7 @@ async function apiFetch(url, config, options = {}, verbose = false) {
2595
2616
  ...options.headers ?? {}
2596
2617
  };
2597
2618
  const body = typeof options.body === "string" ? options.body : void 0;
2598
- const res = await rawRequest(url, {
2619
+ const res = await requestWithReadRetry(url, {
2599
2620
  method,
2600
2621
  headers: reqHeaders,
2601
2622
  body
@@ -2613,7 +2634,7 @@ async function apiFetchWithHeaders(url, config, options = {}, verbose = false) {
2613
2634
  ...options.headers ?? {}
2614
2635
  };
2615
2636
  const body = typeof options.body === "string" ? options.body : void 0;
2616
- const res = await rawRequest(url, { method, headers: reqHeaders, body });
2637
+ const res = await requestWithReadRetry(url, { method, headers: reqHeaders, body });
2617
2638
  const text2 = res.text;
2618
2639
  if (res.status < 200 || res.status >= 300) {
2619
2640
  throw new Error(formatHttpError(res.status, text2, { verbose }));
@@ -3901,7 +3922,7 @@ async function issueApiKeyWithPhoneCode(opts) {
3901
3922
  });
3902
3923
  return apiKey;
3903
3924
  }
3904
- var import_semver, SILUZAN_DIR, CONFIG_FILE, inProcessLockChain, ALLOWED_HOSTNAME_SUFFIXES, EXACT_ID_FIELD_NAMES, SILUZAN_AGENT_COMPANY_SOURCE_TYPE, DEERFLOW_AGENT_ENV, _clientProduct, _resolveVersion, DEFAULT_TIMEOUT_MS, MAX_RESPONSE_BYTES, httpsAgent, httpAgent, PERF_PREFIX, DEFAULT_DETAIL_MAX, VERBOSE_DETAIL_MAX, TABLE_CELL_PIPE, ASCII_TABLE_CHARS, CLI_SNAPSHOT_MANIFEST_FILE, SCHEMA_VERSION, FALLBACK_FIELD_GUIDE_REFS, _cliPackage, _resolveCliVersion, _fieldGuideRefs, OUTLINE_AGENT_HINT, TS_LIKE_ARRAY_SAMPLE_MAX, MAX_INVOCATION_CHARS, currentInvocation, MAX_COMMIT_CHARS, WRITE_AUDIT_AGENT_AUTO_COMMIT, cliCommitOverride, WRITE_AUDIT_SCHEMA_VERSION, MUTATING, BEIJING_TZ, AUDIT_LOG_FILENAME_RE, DEFAULT_MAX_FILE_MB, MIN_SEGMENT_BYTES, MAX_SEGMENT_BYTES, DEFAULT_RETENTION_DAYS, MIN_RETENTION_DAYS, MAX_RETENTION_DAYS, PRUNE_THROTTLE_MS, lastPruneAtMs, MAX_BODY_CHARS, MAX_ERROR_CHARS, DEFAULT_FIND_AUDIT_MAX_DAYS, MAX_SNAPSHOT_FILE_BYTES, API_KEY_SERVICE_VALUES;
3925
+ var import_semver, SILUZAN_DIR, CONFIG_FILE, inProcessLockChain, ALLOWED_HOSTNAME_SUFFIXES, EXACT_ID_FIELD_NAMES, SILUZAN_AGENT_COMPANY_SOURCE_TYPE, DEERFLOW_AGENT_ENV, _clientProduct, _resolveVersion, DEFAULT_TIMEOUT_MS, MAX_RESPONSE_BYTES, httpsAgent, httpAgent, PERF_PREFIX, DEFAULT_DETAIL_MAX, VERBOSE_DETAIL_MAX, GET_RETRY_DELAYS_MS, TABLE_CELL_PIPE, ASCII_TABLE_CHARS, CLI_SNAPSHOT_MANIFEST_FILE, SCHEMA_VERSION, FALLBACK_FIELD_GUIDE_REFS, _cliPackage, _resolveCliVersion, _fieldGuideRefs, OUTLINE_AGENT_HINT, TS_LIKE_ARRAY_SAMPLE_MAX, MAX_INVOCATION_CHARS, currentInvocation, MAX_COMMIT_CHARS, WRITE_AUDIT_AGENT_AUTO_COMMIT, cliCommitOverride, WRITE_AUDIT_SCHEMA_VERSION, MUTATING, BEIJING_TZ, AUDIT_LOG_FILENAME_RE, DEFAULT_MAX_FILE_MB, MIN_SEGMENT_BYTES, MAX_SEGMENT_BYTES, DEFAULT_RETENTION_DAYS, MIN_RETENTION_DAYS, MAX_RETENTION_DAYS, PRUNE_THROTTLE_MS, lastPruneAtMs, MAX_BODY_CHARS, MAX_ERROR_CHARS, DEFAULT_FIND_AUDIT_MAX_DAYS, MAX_SNAPSHOT_FILE_BYTES, API_KEY_SERVICE_VALUES;
3905
3926
  var init_dist = __esm({
3906
3927
  "../common/dist/index.js"() {
3907
3928
  "use strict";
@@ -3969,6 +3990,7 @@ var init_dist = __esm({
3969
3990
  PERF_PREFIX = "[SILUZAN_HTTP_PERF]";
3970
3991
  DEFAULT_DETAIL_MAX = 400;
3971
3992
  VERBOSE_DETAIL_MAX = 800;
3993
+ GET_RETRY_DELAYS_MS = [1e3, 3e3];
3972
3994
  TABLE_CELL_PIPE = "\uFF5C";
3973
3995
  ASCII_TABLE_CHARS = {
3974
3996
  top: "-",
@@ -4612,6 +4634,13 @@ function resolveDailyMetricsQueryTimes(startDate, endDate, now = /* @__PURE__ */
4612
4634
  const endInstant = endOfDay.getTime() > now.getTime() ? formatChinaOffsetDateTime(now) : formatChinaOffsetDateTime(endOfDay);
4613
4635
  return { startInstant, endInstant };
4614
4636
  }
4637
+ function clampRowsToCalendarRange(rows, startDate, endDate) {
4638
+ return rows.filter((r) => {
4639
+ if (typeof r.date !== "string" || r.date.length < 10) return true;
4640
+ const day = r.date.slice(0, 10);
4641
+ return day >= startDate && day <= endDate;
4642
+ });
4643
+ }
4615
4644
  function resolveChinaQueryTimes(startDate, endDate, _now = /* @__PURE__ */ new Date()) {
4616
4645
  return { startInstant: startDate, endInstant: endDate };
4617
4646
  }
@@ -102868,7 +102897,7 @@ async function fetchSectionPayload(def, opts, config, id, http2) {
102868
102897
  }
102869
102898
  if (def.name === "daily-metrics") {
102870
102899
  const { startDate, endDate } = resolveDateRange(opts.start, opts.end);
102871
- const { startInstant, endInstant } = resolveChinaQueryTimes(startDate, endDate);
102900
+ const { startInstant, endInstant } = resolveDailyMetricsQueryTimes(startDate, endDate);
102872
102901
  const params = new URLSearchParams({
102873
102902
  mediaCustomerIds: id,
102874
102903
  startDate: startInstant,
@@ -102882,7 +102911,11 @@ async function fetchSectionPayload(def, opts, config, id, http2) {
102882
102911
  `daily-metrics/${id}`,
102883
102912
  http2
102884
102913
  );
102885
- const rows = rowsFromAccountDailyReportsEnvelope(raw, id);
102914
+ const rows = clampRowsToCalendarRange(
102915
+ rowsFromAccountDailyReportsEnvelope(raw, id),
102916
+ startDate,
102917
+ endDate
102918
+ );
102886
102919
  return annotateZhFields(
102887
102920
  normalizeMoneyScales(
102888
102921
  normalizeRateScales(stripLegacyGoogleFieldsIfV2Present(rows), "daily-metrics"),
@@ -103057,7 +103090,7 @@ function narrativeClaimsMobileSpendLeads(text2) {
103057
103090
  if (!t.includes("\u79FB\u52A8")) return false;
103058
103091
  return /移动(?:端|设备)?(?:为|是)主要消耗/.test(t) || /移动(?:端|设备)?为主要(?:消耗)?设备/.test(t) || /移动(?:端|设备)?(?:消耗|花费|费用|流量)?占比高/.test(t);
103059
103092
  }
103060
- function asRecord15(value) {
103093
+ function asRecord16(value) {
103061
103094
  if (value && typeof value === "object" && !Array.isArray(value)) return value;
103062
103095
  return null;
103063
103096
  }
@@ -103065,16 +103098,16 @@ function stringList(value) {
103065
103098
  return (Array.isArray(value) ? value : []).map((item) => typeof item === "string" ? item.trim() : "").filter(Boolean);
103066
103099
  }
103067
103100
  function collectOkkiNarrativeText(data) {
103068
- const narrative = asRecord15(data.narrative) ?? {};
103101
+ const narrative = asRecord16(data.narrative) ?? {};
103069
103102
  const parts = [];
103070
- const sheetAnalysis = asRecord15(narrative.sheetAnalysis) ?? {};
103103
+ const sheetAnalysis = asRecord16(narrative.sheetAnalysis) ?? {};
103071
103104
  for (const block of Object.values(sheetAnalysis)) {
103072
- const rec = asRecord15(block);
103105
+ const rec = asRecord16(block);
103073
103106
  parts.push(...stringList(rec?.summary), ...stringList(rec?.suggestions));
103074
103107
  }
103075
- const review = asRecord15(narrative.review) ?? {};
103108
+ const review = asRecord16(narrative.review) ?? {};
103076
103109
  for (const block of Object.values(review)) {
103077
- const rec = asRecord15(block);
103110
+ const rec = asRecord16(block);
103078
103111
  for (const key of ["overview", "summary", "suggestion"]) {
103079
103112
  const value = rec?.[key];
103080
103113
  if (typeof value === "string" && value.trim()) parts.push(value.trim());
@@ -103091,7 +103124,7 @@ var init_okki_display = __esm({
103091
103124
  // src/commands/google-analysis/merge-snapshot.ts
103092
103125
  import * as fs27 from "fs/promises";
103093
103126
  import * as path32 from "path";
103094
- function asRecord16(value) {
103127
+ function asRecord17(value) {
103095
103128
  if (value && typeof value === "object" && !Array.isArray(value)) {
103096
103129
  return value;
103097
103130
  }
@@ -103187,7 +103220,7 @@ function periodMetricsFromRow(row) {
103187
103220
  }
103188
103221
  function items(envelope) {
103189
103222
  if (!envelope || !Array.isArray(envelope.items)) return [];
103190
- return envelope.items.filter((row) => asRecord16(row) !== null);
103223
+ return envelope.items.filter((row) => asRecord17(row) !== null);
103191
103224
  }
103192
103225
  function record(envelope) {
103193
103226
  return envelope?.record ?? null;
@@ -103234,14 +103267,14 @@ function sumCampaignRowsToPeriodKpis(rows) {
103234
103267
  }
103235
103268
  async function mergeGoogleAnalysisSnapshotIntoReport(payload, snapshotDir) {
103236
103269
  const absDir = path32.resolve(snapshotDir);
103237
- const metaAccountId = typeof asRecord16(payload.meta)?.accountId === "string" ? asRecord16(payload.meta)?.accountId : void 0;
103270
+ const metaAccountId = typeof asRecord17(payload.meta)?.accountId === "string" ? asRecord17(payload.meta)?.accountId : void 0;
103238
103271
  const manifest = await readManifest(snapshotDir, metaAccountId);
103239
103272
  if (!manifest) {
103240
103273
  throw new Error(`\u672A\u5728 ${absDir} \u627E\u5230 manifest*.json\uFF0C\u8BF7\u5148\u6267\u884C google-analysis --json-out`);
103241
103274
  }
103242
103275
  const accountId = manifest.googleAnalysis?.accountId ?? metaAccountId;
103243
103276
  const dateRange = manifest.googleAnalysis?.dateRange;
103244
- const preferredDateTag = dateTagFromRange(dateRange) ?? dateTagFromMeta(asRecord16(payload.meta) ?? void 0);
103277
+ const preferredDateTag = dateTagFromRange(dateRange) ?? dateTagFromMeta(asRecord17(payload.meta) ?? void 0);
103245
103278
  const sectionMap = /* @__PURE__ */ new Map();
103246
103279
  for (const art of manifest.artifacts ?? []) {
103247
103280
  const data = await loadSectionFile(absDir, art.file);
@@ -103249,8 +103282,8 @@ async function mergeGoogleAnalysisSnapshotIntoReport(payload, snapshotDir) {
103249
103282
  }
103250
103283
  await recoverMissingReportSections(sectionMap, absDir, accountId, preferredDateTag);
103251
103284
  const overviewRecord = record(sectionMap.get("overview"));
103252
- const currentPeriod = asRecord16(overviewRecord?.currentPeriod);
103253
- const previousPeriod = asRecord16(overviewRecord?.previousPeriod);
103285
+ const currentPeriod = asRecord17(overviewRecord?.currentPeriod);
103286
+ const previousPeriod = asRecord17(overviewRecord?.previousPeriod);
103254
103287
  const meta = { ...payload.meta ?? {} };
103255
103288
  if (!meta.accountId && accountId) meta.accountId = accountId;
103256
103289
  if (!meta.currency) {
@@ -103396,7 +103429,7 @@ function textLen(value) {
103396
103429
  function asArray(value) {
103397
103430
  return Array.isArray(value) ? value : [];
103398
103431
  }
103399
- function asRecord17(value) {
103432
+ function asRecord18(value) {
103400
103433
  if (value && typeof value === "object" && !Array.isArray(value)) {
103401
103434
  return value;
103402
103435
  }
@@ -103410,7 +103443,7 @@ function pushMissing(missing, id, chapter, dimension, hint) {
103410
103443
  }
103411
103444
  function validateOkkiWeeklyReportContent(data) {
103412
103445
  const missing = [];
103413
- const meta = asRecord17(data.meta) ?? {};
103446
+ const meta = asRecord18(data.meta) ?? {};
103414
103447
  if (!textLen(meta.accountId)) {
103415
103448
  pushMissing(
103416
103449
  missing,
@@ -103420,7 +103453,7 @@ function validateOkkiWeeklyReportContent(data) {
103420
103453
  "meta.accountId \u5FC5\u586B\uFF1B\u53EF\u7531 --snapshot-dir \u5408\u5E76 overview/manifest"
103421
103454
  );
103422
103455
  }
103423
- const snapshotSections = asRecord17(data.snapshot?.sections) ?? {};
103456
+ const snapshotSections = asRecord18(data.snapshot?.sections) ?? {};
103424
103457
  const snapshotPresent = {};
103425
103458
  for (const section of OKKI_SNAPSHOT_SECTIONS) {
103426
103459
  const present = snapshotSections[section] === true;
@@ -103435,12 +103468,12 @@ function validateOkkiWeeklyReportContent(data) {
103435
103468
  );
103436
103469
  }
103437
103470
  }
103438
- const narrative = asRecord17(data.narrative) ?? {};
103439
- const sheetAnalysis = asRecord17(narrative.sheetAnalysis) ?? {};
103440
- const review = asRecord17(narrative.review) ?? {};
103471
+ const narrative = asRecord18(data.narrative) ?? {};
103472
+ const sheetAnalysis = asRecord18(narrative.sheetAnalysis) ?? {};
103473
+ const review = asRecord18(narrative.review) ?? {};
103441
103474
  const sheetAnalysisCounts = {};
103442
103475
  for (const key of OKKI_SHEET_KEYS) {
103443
- const block = asRecord17(sheetAnalysis[key]);
103476
+ const block = asRecord18(sheetAnalysis[key]);
103444
103477
  const summary = stringList2(block?.summary);
103445
103478
  const suggestions = stringList2(block?.suggestions);
103446
103479
  sheetAnalysisCounts[key] = { summary: summary.length, suggestions: suggestions.length };
@@ -103466,7 +103499,7 @@ function validateOkkiWeeklyReportContent(data) {
103466
103499
  }
103467
103500
  const reviewFilled = {};
103468
103501
  for (const key of OKKI_REVIEW_KEYS) {
103469
- const block = asRecord17(review[key]);
103502
+ const block = asRecord18(review[key]);
103470
103503
  const overview = textLen(block?.overview);
103471
103504
  const summary = textLen(block?.summary);
103472
103505
  const suggestion = textLen(block?.suggestion);
@@ -103501,7 +103534,7 @@ function validateOkkiWeeklyReportContent(data) {
103501
103534
  }
103502
103535
  }
103503
103536
  const deviceRows2 = Array.isArray(data.tables?.devices) ? data.tables.devices : [];
103504
- const deviceSpend = summarizeOkkiDeviceSpend(deviceRows2.filter((row) => asRecord17(row) !== null));
103537
+ const deviceSpend = summarizeOkkiDeviceSpend(deviceRows2.filter((row) => asRecord18(row) !== null));
103505
103538
  if (deviceSpend.total > 0 && deviceSpend.desktop >= deviceSpend.mobile && narrativeClaimsMobileSpendLeads(collectOkkiNarrativeText(data))) {
103506
103539
  pushMissing(
103507
103540
  missing,
@@ -103590,7 +103623,7 @@ function round25(value) {
103590
103623
  }
103591
103624
  function items2(envelope) {
103592
103625
  if (!envelope || !Array.isArray(envelope.items)) return [];
103593
- return envelope.items.filter((row) => asRecord17(row) !== null);
103626
+ return envelope.items.filter((row) => asRecord18(row) !== null);
103594
103627
  }
103595
103628
  function dateTagFromRange2(dateRange) {
103596
103629
  if (!dateRange || dateRange.mode !== "range") return void 0;
@@ -103634,14 +103667,14 @@ async function loadSectionFile2(snapshotDir, file) {
103634
103667
  }
103635
103668
  async function mergeOkkiSnapshotIntoReport(payload, snapshotDir) {
103636
103669
  const absDir = path33.resolve(snapshotDir);
103637
- const metaAccountId = typeof asRecord17(payload.meta)?.accountId === "string" ? asRecord17(payload.meta)?.accountId : void 0;
103670
+ const metaAccountId = typeof asRecord18(payload.meta)?.accountId === "string" ? asRecord18(payload.meta)?.accountId : void 0;
103638
103671
  const manifest = await readManifest2(absDir, metaAccountId);
103639
103672
  if (!manifest) {
103640
103673
  throw new Error(`\u672A\u5728 ${absDir} \u627E\u5230 manifest*.json\uFF0C\u8BF7\u5148\u6267\u884C google-analysis --json-out`);
103641
103674
  }
103642
103675
  const accountId = manifest.googleAnalysis?.accountId ?? metaAccountId;
103643
103676
  const dateRange = manifest.googleAnalysis?.dateRange;
103644
- const preferredDateTag = dateTagFromRange2(dateRange) ?? dateTagFromMeta2(asRecord17(payload.meta) ?? void 0);
103677
+ const preferredDateTag = dateTagFromRange2(dateRange) ?? dateTagFromMeta2(asRecord18(payload.meta) ?? void 0);
103645
103678
  const sectionMap = /* @__PURE__ */ new Map();
103646
103679
  for (const art of manifest.artifacts ?? []) {
103647
103680
  const data = await loadSectionFile2(absDir, art.file);
@@ -103667,7 +103700,7 @@ async function mergeOkkiSnapshotIntoReport(payload, snapshotDir) {
103667
103700
  snapshotPresent[section] = sectionMap.has(section);
103668
103701
  }
103669
103702
  const overviewRecord = sectionMap.get("overview")?.record ?? null;
103670
- const currentPeriod = asRecord17(overviewRecord?.currentPeriod);
103703
+ const currentPeriod = asRecord18(overviewRecord?.currentPeriod);
103671
103704
  const meta = { ...payload.meta ?? {} };
103672
103705
  if (!meta.accountId && accountId) meta.accountId = accountId;
103673
103706
  if (!meta.currency) {
@@ -103810,18 +103843,18 @@ function prefixLines(items3, firstPrefix) {
103810
103843
  });
103811
103844
  }
103812
103845
  function analysisLines(data, key) {
103813
- const block = asRecord17(asRecord17(data.narrative)?.sheetAnalysis)?.[key];
103814
- const rec = asRecord17(block);
103846
+ const block = asRecord18(asRecord18(data.narrative)?.sheetAnalysis)?.[key];
103847
+ const rec = asRecord18(block);
103815
103848
  return [
103816
103849
  ...prefixLines(stringList2(rec?.summary), "\u603B\u7ED3\uFF1A"),
103817
103850
  ...prefixLines(stringList2(rec?.suggestions), "\u5EFA\u8BAE\uFF1A")
103818
103851
  ];
103819
103852
  }
103820
103853
  function reviewLines(data) {
103821
- const review = asRecord17(asRecord17(data.narrative)?.review) ?? {};
103854
+ const review = asRecord18(asRecord18(data.narrative)?.review) ?? {};
103822
103855
  const lines = [];
103823
103856
  OKKI_REVIEW_KEYS.forEach((key, idx) => {
103824
- const block = asRecord17(review[key]) ?? {};
103857
+ const block = asRecord18(review[key]) ?? {};
103825
103858
  lines.push(`${idx + 1}\u3001${REVIEW_LABELS2[key]}\uFF1A${str(block.overview, "")}`);
103826
103859
  lines.push(` \u603B\u7ED3\uFF1A${str(block.summary, "")}`);
103827
103860
  lines.push(` \u5EFA\u8BAE\uFF1A${str(block.suggestion, "")}`);
@@ -103953,7 +103986,7 @@ function geoRows(data) {
103953
103986
  });
103954
103987
  }
103955
103988
  function buildOkkiWeeklySheetDrafts(data) {
103956
- const meta = asRecord17(data.meta) ?? {};
103989
+ const meta = asRecord18(data.meta) ?? {};
103957
103990
  const period = formatOkkiZhDateRange(str(meta.startDate, ""), str(meta.endDate, ""));
103958
103991
  const campaigns = campaignRows(data);
103959
103992
  const drafts = {
@@ -104214,7 +104247,7 @@ function textLen2(value) {
104214
104247
  function asArray2(value) {
104215
104248
  return Array.isArray(value) ? value : [];
104216
104249
  }
104217
- function asRecord18(value) {
104250
+ function asRecord19(value) {
104218
104251
  if (value && typeof value === "object" && !Array.isArray(value)) {
104219
104252
  return value;
104220
104253
  }
@@ -104225,9 +104258,9 @@ function pushMissing2(missing, id, chapter, dimension, hint) {
104225
104258
  }
104226
104259
  function validateGooglePeriodReportContent(data) {
104227
104260
  const missing = [];
104228
- const meta = asRecord18(data.meta) ?? {};
104229
- const narrative = asRecord18(data.narrative) ?? {};
104230
- const sections = asRecord18(narrative.sections) ?? {};
104261
+ const meta = asRecord19(data.meta) ?? {};
104262
+ const narrative = asRecord19(data.narrative) ?? {};
104263
+ const sections = asRecord19(narrative.sections) ?? {};
104231
104264
  if (!textLen2(meta.accountId)) {
104232
104265
  pushMissing2(
104233
104266
  missing,
@@ -104247,7 +104280,7 @@ function validateGooglePeriodReportContent(data) {
104247
104280
  "\u22651 \u6BB5\u6267\u884C\u6458\u8981\uFF0C\u6982\u8FF0\u672C\u671F\u6D88\u8017/\u8F6C\u5316/CTR/CPA \u8D70\u52BF"
104248
104281
  );
104249
104282
  }
104250
- const kpis = asRecord18(data.kpis);
104283
+ const kpis = asRecord19(data.kpis);
104251
104284
  const hasCoreKpi = ["cost", "impressions", "clicks"].some(
104252
104285
  (key) => Number.isFinite(Number(kpis?.[key]))
104253
104286
  );
@@ -104263,7 +104296,7 @@ function validateGooglePeriodReportContent(data) {
104263
104296
  const sectionAnalysisCounts = {};
104264
104297
  const sectionSuggestionCounts = {};
104265
104298
  for (const key of SECTION_KEYS) {
104266
- const section = asRecord18(sections[key]);
104299
+ const section = asRecord19(sections[key]);
104267
104300
  const analysis = asArray2(section?.analysis).filter((s) => textLen2(s) > 0);
104268
104301
  const suggestions = asArray2(section?.suggestions).filter((s) => textLen2(s) > 0);
104269
104302
  sectionAnalysisCounts[key] = analysis.length;
@@ -104289,7 +104322,7 @@ function validateGooglePeriodReportContent(data) {
104289
104322
  }
104290
104323
  const recommendations = asArray2(narrative.recommendations).filter((r) => {
104291
104324
  if (typeof r === "string") return textLen2(r) > 0;
104292
- const rec = asRecord18(r);
104325
+ const rec = asRecord19(r);
104293
104326
  return textLen2(rec?.content) > 0;
104294
104327
  });
104295
104328
  if (recommendations.length < 3) {
@@ -104378,7 +104411,7 @@ async function readJsonFile3(filePath) {
104378
104411
  throw new Error(`\u65E0\u6CD5\u89E3\u6790 JSON\uFF1A${filePath}`);
104379
104412
  }
104380
104413
  }
104381
- function asRecord19(value) {
104414
+ function asRecord20(value) {
104382
104415
  if (value && typeof value === "object" && !Array.isArray(value)) {
104383
104416
  return value;
104384
104417
  }
@@ -104393,7 +104426,7 @@ function injectReportData2(html, payload) {
104393
104426
  }
104394
104427
  async function runGoogleAnalysisRender(opts) {
104395
104428
  const dataPath = path35.resolve(opts.dataFile);
104396
- let data = asRecord19(await readJsonFile3(dataPath));
104429
+ let data = asRecord20(await readJsonFile3(dataPath));
104397
104430
  if (opts.snapshotDir?.trim()) {
104398
104431
  data = await mergeGoogleAnalysisSnapshotIntoReport(data, path35.resolve(opts.snapshotDir));
104399
104432
  }
@@ -113044,6 +113077,19 @@ init_cli_json_snapshot();
113044
113077
  init_strip_legacy_google_fields();
113045
113078
  init_cli_table();
113046
113079
 
113080
+ // src/utils/destructive-confirm.ts
113081
+ function ensureIConfirm(opts) {
113082
+ if (opts.iConfirm) return;
113083
+ console.error(
113084
+ `
113085
+ \u274C \u62D2\u7EDD\u6267\u884C\uFF1A${opts.actionLabel} \u4E3A\u7834\u574F\u6027\u64CD\u4F5C\uFF0C\u987B\u5148\u5411\u7528\u6237\u8BF4\u660E\u98CE\u9669\u5E76\u83B7\u5F97\u660E\u786E\u786E\u8BA4\u3002
113086
+ \u7528\u6237\u540C\u610F\u540E\uFF0C\u8BF7\u9644\u52A0 --i-confirm\uFF0C\u5E76\u4F7F\u7528 --commit "\u2026" \u8BF4\u660E\u539F\u56E0\u540E\u518D\u6267\u884C\u3002
113087
+ \u793A\u4F8B\uFF1Asiluzan-tso \u2026 --i-confirm --commit "\u7528\u6237\u786E\u8BA4\u89E3\u7ED1 entityId=\u2026"
113088
+ `
113089
+ );
113090
+ process.exit(1);
113091
+ }
113092
+
113047
113093
  // src/commands/ad/campaign-create-validate.ts
113048
113094
  init_media_customer_id();
113049
113095
 
@@ -113834,7 +113880,10 @@ async function runAdKeywordEdit(opts) {
113834
113880
  if (opts.maxCpc !== void 0) body["maxCPC"] = toCentAmount(opts.maxCpc);
113835
113881
  if (opts.finalUrl !== void 0) body["finalURL"] = opts.finalUrl;
113836
113882
  if (opts.status !== void 0) body["userStatusV2"] = opts.status;
113883
+ const notAppliedHint = ` \u8BF7\u52FF\u6539\u7528\u300C\u5220\u9664\u540E\u91CD\u5EFA\u300D\u7ED5\u8FC7\uFF08\u4F1A\u4E22\u5931\u5173\u952E\u8BCD id \u4E0E\u5386\u53F2\u6570\u636E\uFF09\uFF0C\u8BF7\u53CD\u9988\u5E73\u53F0\u6392\u67E5\u3002
113884
+ `;
113837
113885
  const url = `${googleApiUrl}/keywordmanagement/Keyword/${opts.account}/batch`;
113886
+ let currentId = opts.id;
113838
113887
  try {
113839
113888
  const raw = await apiFetch2(
113840
113889
  url,
@@ -113845,6 +113894,7 @@ async function runAdKeywordEdit(opts) {
113845
113894
  const first = Array.isArray(raw) && raw.length > 0 && raw[0] && typeof raw[0] === "object" ? raw[0] : null;
113846
113895
  const returnedId = first && typeof first["id"] === "string" ? first["id"] : void 0;
113847
113896
  if (returnedId && returnedId !== opts.id) {
113897
+ currentId = returnedId;
113848
113898
  console.log(
113849
113899
  `
113850
113900
  \u2139\uFE0F \u7F51\u5173\u8FD4\u56DE\u7684\u5173\u952E\u8BCD id \u5DF2\u53D8\u66F4\u4E3A ${returnedId}\uFF08\u8BF7\u6C42\u65F6 id \u4E3A ${opts.id}\uFF09\uFF0C\u540E\u7EED\u67E5\u8BE2\u8BF7\u4F7F\u7528\u65B0 id\u3002
@@ -113857,8 +113907,7 @@ async function runAdKeywordEdit(opts) {
113857
113907
  `
113858
113908
  \u274C \u7F51\u5173\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u4EE5\u4E0B\u5B57\u6BB5\u672A\u751F\u6548\uFF1A
113859
113909
  ${mismatches.map((m) => ` - ${m}`).join("\n")}
113860
- \u8BF7\u52FF\u6539\u7528\u300C\u5220\u9664\u540E\u91CD\u5EFA\u300D\u7ED5\u8FC7\uFF08\u4F1A\u4E22\u5931\u5173\u952E\u8BCD id \u4E0E\u5386\u53F2\u6570\u636E\uFF09\uFF0C\u8BF7\u53CD\u9988\u5E73\u53F0\u6392\u67E5\u3002
113861
- `
113910
+ ` + notAppliedHint
113862
113911
  );
113863
113912
  process.exit(1);
113864
113913
  }
@@ -113868,6 +113917,35 @@ ${mismatches.map((m) => ` - ${m}`).join("\n")}
113868
113917
  `);
113869
113918
  process.exit(1);
113870
113919
  }
113920
+ if (opts.finalUrl !== void 0 || opts.maxCpc !== void 0 || opts.status !== void 0) {
113921
+ let fresh;
113922
+ try {
113923
+ fresh = await findItemInList(
113924
+ listUrl,
113925
+ config,
113926
+ currentId,
113927
+ opts.verbose
113928
+ );
113929
+ } catch (err) {
113930
+ console.error(
113931
+ `
113932
+ \u274C \u5199\u5165\u8BF7\u6C42\u5DF2\u53D1\u9001\uFF0C\u4F46\u56DE\u8BFB\u6821\u9A8C\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}
113933
+ \u7A0D\u540E\u7528 ad keywords \u6838\u5BF9 id=${currentId} \u7684\u5B9E\u9645\u503C\uFF1B\u672A\u751F\u6548\u65F6\u91CD\u8DD1 keyword-edit \u5373\u53EF\uFF08\u5E42\u7B49\uFF09\u3002
113934
+ ` + notAppliedHint
113935
+ );
113936
+ process.exit(1);
113937
+ }
113938
+ const mismatches = findKeywordEditMismatches(body, fresh, opts);
113939
+ if (mismatches.length > 0) {
113940
+ console.error(
113941
+ `
113942
+ \u274C \u7F51\u5173\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u56DE\u8BFB\u540E\u4EE5\u4E0B\u5B57\u6BB5\u672A\u751F\u6548\uFF1A
113943
+ ${mismatches.map((m) => ` - ${m}`).join("\n")}
113944
+ ` + notAppliedHint
113945
+ );
113946
+ process.exit(1);
113947
+ }
113948
+ }
113871
113949
  console.log(`
113872
113950
  \u2705 \u5173\u952E\u8BCD\u5DF2\u66F4\u65B0
113873
113951
  `);
@@ -114191,23 +114269,28 @@ function pushKeywordAutoFixWarning(warnings, path55, fieldLabel, trimmedRaw, for
114191
114269
  warnings.push(
114192
114270
  `${path55}.${fieldLabel} \u672A\u6307\u5B9A MatchTypeV2\uFF0C\u5DF2\u6309\u8BCD\u9762\u63A8\u65AD\u4E3A ${matchTypeUiToV2(matchType)}`
114193
114271
  );
114194
- return;
114272
+ return false;
114273
+ }
114274
+ if (declaredUi && declaredUi !== "Broad" && beforeUi === "Broad" && unwrapKeywordDisplayTextForEdit(formatted) === trimmedRaw) {
114275
+ return true;
114195
114276
  }
114196
114277
  if (declaredUi && beforeUi !== declaredUi) {
114197
114278
  warnings.push(
114198
114279
  `${path55}.${fieldLabel} MatchTypeV2=${matchTypeUiToV2(declaredUi)} \u4E0E\u8BCD\u9762\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u81EA\u52A8\u4FEE\u590D\u4E3A\uFF1A${formatted}`
114199
114280
  );
114200
- return;
114281
+ return false;
114201
114282
  }
114202
114283
  if (formatted !== trimmedRaw) {
114203
114284
  warnings.push(`${path55}.${fieldLabel} \u5DF2\u81EA\u52A8\u4FEE\u590D\u8BCD\u9762\uFF1A${trimmedRaw} \u2192 ${formatted}`);
114204
114285
  }
114286
+ return false;
114205
114287
  }
114206
114288
  function normalizeKeywordTextList(texts, matchTypeRaw, path55, fieldLabel, errors, warnings, lengthViolations) {
114207
114289
  const declaredUi = matchTypeV2ToUi(matchTypeRaw);
114208
114290
  const normalized = [];
114209
114291
  const seen = /* @__PURE__ */ new Set();
114210
114292
  let resolvedUi = declaredUi;
114293
+ let bareWrapped = 0;
114211
114294
  for (let k = 0; k < texts.length; k++) {
114212
114295
  const raw = texts[k];
114213
114296
  if (typeof raw !== "string" || !raw.trim()) {
@@ -114220,7 +114303,7 @@ function normalizeKeywordTextList(texts, matchTypeRaw, path55, fieldLabel, error
114220
114303
  trimmedRaw,
114221
114304
  matchTypeRaw
114222
114305
  );
114223
- pushKeywordAutoFixWarning(
114306
+ if (pushKeywordAutoFixWarning(
114224
114307
  warnings,
114225
114308
  path55,
114226
114309
  fieldLabel,
@@ -114230,7 +114313,9 @@ function normalizeKeywordTextList(texts, matchTypeRaw, path55, fieldLabel, error
114230
114313
  beforeUi,
114231
114314
  matchType,
114232
114315
  inferredMatchType
114233
- );
114316
+ )) {
114317
+ bareWrapped++;
114318
+ }
114234
114319
  const core = unwrapKeywordDisplayTextForEdit(formatted);
114235
114320
  if (!validateKeywordCore(core, `${path55}.${fieldLabel}[${k}]`, errors, lengthViolations))
114236
114321
  continue;
@@ -114243,6 +114328,11 @@ function normalizeKeywordTextList(texts, matchTypeRaw, path55, fieldLabel, error
114243
114328
  normalized.push(formatted);
114244
114329
  if (!resolvedUi) resolvedUi = matchType;
114245
114330
  }
114331
+ if (bareWrapped > 0 && declaredUi) {
114332
+ warnings.push(
114333
+ `${path55}.${fieldLabel}\uFF1A${bareWrapped} \u4E2A\u88F8\u8BCD\u5DF2\u6309 MatchTypeV2=${matchTypeUiToV2(declaredUi)} \u81EA\u52A8\u4FEE\u590D\uFF08\u8865\u5168${declaredUi === "Exact" ? " [ ]" : "\u5F15\u53F7"}\uFF0C\u9884\u671F\u884C\u4E3A\uFF09`
114334
+ );
114335
+ }
114246
114336
  return { normalized, resolvedUi };
114247
114337
  }
114248
114338
  function normalizeKeywordsForBatchJobBlock(block, path55, errors, warnings, lengthViolations) {
@@ -114296,7 +114386,7 @@ function normalizeKeywordsForBatchJobBlock(block, path55, errors, warnings, leng
114296
114386
  trimmedRaw,
114297
114387
  matchTypeRaw
114298
114388
  );
114299
- pushKeywordAutoFixWarning(
114389
+ if (pushKeywordAutoFixWarning(
114300
114390
  warnings,
114301
114391
  path55,
114302
114392
  `Items[${k}].Text`,
@@ -114306,7 +114396,9 @@ function normalizeKeywordsForBatchJobBlock(block, path55, errors, warnings, leng
114306
114396
  beforeUi,
114307
114397
  matchType,
114308
114398
  inferredMatchType
114309
- );
114399
+ )) {
114400
+ warnings.push(`${path55}.Items[${k}].Text \u5DF2\u6309\u5757\u7EA7\u5339\u914D\u7C7B\u578B\u81EA\u52A8\u4FEE\u590D\u4E3A\uFF1A${formatted}`);
114401
+ }
114310
114402
  const core = unwrapKeywordDisplayTextForEdit(formatted);
114311
114403
  if (!validateKeywordCore(core, `${path55}.Items[${k}].Text`, errors, lengthViolations))
114312
114404
  continue;
@@ -114375,6 +114467,7 @@ function normalizeCampaignKeywordTrees(campaign, errors, warnings, lengthViolati
114375
114467
  }
114376
114468
  }
114377
114469
  warnIfNegativeKeywordsInPositiveKeywords(campaign, warnings);
114470
+ warnIfNegativeKeywordsBlockPositive(campaign, warnings);
114378
114471
  }
114379
114472
  var COMMON_NEGATIVE_KEYWORD_STEMS = /* @__PURE__ */ new Set([
114380
114473
  "free",
@@ -114473,6 +114566,142 @@ function warnIfNegativeKeywordsInPositiveKeywords(campaign, warnings) {
114473
114566
  }
114474
114567
  }
114475
114568
  }
114569
+ function keywordTokens(core) {
114570
+ return core.toLowerCase().split(/\s+/).map((t) => t.trim()).filter(Boolean);
114571
+ }
114572
+ function negativeBlocksKeyword(negativeCore, negativeMatch, positiveCore) {
114573
+ const neg = keywordTokens(negativeCore);
114574
+ const pos = keywordTokens(positiveCore);
114575
+ if (neg.length === 0 || pos.length === 0) return false;
114576
+ if (negativeMatch === "EXACT") return neg.join(" ") === pos.join(" ");
114577
+ if (negativeMatch === "PHRASE") {
114578
+ for (let i = 0; i + neg.length <= pos.length; i++) {
114579
+ if (neg.every((t, j) => pos[i + j] === t)) return true;
114580
+ }
114581
+ return false;
114582
+ }
114583
+ const posSet = new Set(pos);
114584
+ return neg.every((t) => posSet.has(t));
114585
+ }
114586
+ function warnIfNegativeKeywordsBlockPositive(campaign, warnings) {
114587
+ const negBlocks = campaign["NegativeKeywordsForBatchJob"];
114588
+ const groups = campaign["AdGroupsForBatchJob"];
114589
+ if (!Array.isArray(negBlocks) || !Array.isArray(groups)) return;
114590
+ const positives = [];
114591
+ for (const g of groups) {
114592
+ const gr = g;
114593
+ const groupName = String(gr?.["Name"] ?? "");
114594
+ const kws = gr?.["KeywordsForBatchJob"];
114595
+ if (!Array.isArray(kws)) continue;
114596
+ for (const b of kws) {
114597
+ const texts = b?.["KeywordText"];
114598
+ if (!Array.isArray(texts)) continue;
114599
+ for (const t of texts) {
114600
+ if (typeof t === "string" && t.trim()) {
114601
+ positives.push({ core: normalizeKeywordCoreForNegativeCheck(t), group: groupName });
114602
+ }
114603
+ }
114604
+ }
114605
+ }
114606
+ if (positives.length === 0) return;
114607
+ for (let bi = 0; bi < negBlocks.length; bi++) {
114608
+ const block = negBlocks[bi];
114609
+ const texts = block?.["KeywordText"];
114610
+ if (!Array.isArray(texts)) continue;
114611
+ const matchUi = matchTypeV2ToUi(block["MatchTypeV2"] ?? block["matchTypeV2"]);
114612
+ for (let ki = 0; ki < texts.length; ki++) {
114613
+ const raw = texts[ki];
114614
+ if (typeof raw !== "string" || !raw.trim()) continue;
114615
+ const match = matchTypeUiToV2(matchUi ?? inferMatchTypeFromDisplayText(raw.trim()));
114616
+ const negCore = normalizeKeywordCoreForNegativeCheck(raw);
114617
+ const hits = positives.filter((p) => negativeBlocksKeyword(negCore, match, p.core));
114618
+ if (hits.length === 0) continue;
114619
+ const sample = hits.slice(0, 5).map((h) => `\u300C${h.core}\u300D(${h.group})`).join("\u3001");
114620
+ warnings.push(
114621
+ `campaign.NegativeKeywordsForBatchJob[${bi}].KeywordText[${ki}] \u5426\u8BCD\u300C${negCore}\u300D(${match}) \u4F1A\u5C4F\u853D ${hits.length} \u4E2A\u6B63\u5411\u5173\u952E\u8BCD\uFF1A${sample}${hits.length > 5 ? " \u2026" : ""}\uFF1B\u65B9\u6848\u81EA\u76F8\u77DB\u76FE\uFF0C\u987B\u95EE\u7528\u6237\u5220\u5426\u8BCD\u8FD8\u662F\u5220\u5173\u952E\u8BCD`
114622
+ );
114623
+ }
114624
+ }
114625
+ }
114626
+
114627
+ // src/commands/ad/campaign-policy-risk.ts
114628
+ var POLICY_RISK_RULES = [
114629
+ { re: /\bguarantee(d|s)?\b/i, label: "\u4FDD\u8BC1\u7ED3\u679C\uFF08Misrepresentation\uFF09" },
114630
+ { re: /\b(cure|cures|cured|heal|heals)\b/i, label: "\u533B\u7597\u529F\u6548\u58F0\u660E\uFF08Healthcare\uFF09" },
114631
+ { re: /\b(replica|counterfeit|fake|knockoff|knock-off)\b/i, label: "\u4EFF\u5192\u54C1\uFF08Counterfeit goods\uFF09" },
114632
+ { re: /\b(casino|betting|gambling|poker)\b/i, label: "\u8D4C\u535A\uFF08\u987B Google \u8BA4\u8BC1\uFF09" },
114633
+ { re: /\b(cbd|thc|cannabis|marijuana|kratom)\b/i, label: "\u53D7\u7BA1\u5236\u836F\u7269/\u5927\u9EBB" },
114634
+ { re: /\b(viagra|steroids?|anabolic|prescription drugs?)\b/i, label: "\u5904\u65B9\u836F/\u7C7B\u56FA\u9187" },
114635
+ { re: /\b(firearms?|ammo|ammunition|rifles?|pistols?|handguns?)\b/i, label: "\u6B66\u5668\uFF08Dangerous products\uFF09" },
114636
+ { re: /\b(crypto|bitcoin|nft|ico)\b/i, label: "\u52A0\u5BC6\u8D27\u5E01\uFF08\u987B Google \u8BA4\u8BC1\uFF09" },
114637
+ { re: /\b(loan|loans|payday|forex)\b/i, label: "\u91D1\u878D\u670D\u52A1\uFF08\u90E8\u5206\u5730\u533A\u987B\u8BA4\u8BC1\uFF09" },
114638
+ { re: /\b(escort|hookup|porn|xxx|sexy)\b/i, label: "\u6210\u4EBA\u5185\u5BB9" },
114639
+ { re: /\b(e-?cig(arette)?s?|vape|vaping|tobacco|cigars?)\b/i, label: "\u70DF\u8349/\u7535\u5B50\u70DF" },
114640
+ { re: /\b(alcohol|whisk(e)?y|vodka|liquor)\b/i, label: "\u9152\u7CBE\uFF08\u5730\u57DF\u9650\u5236\uFF09" },
114641
+ { re: /(最好|第一|国家级|绝对|100%)/, label: "\u5E7F\u544A\u6CD5\u7EDD\u5BF9\u5316\u7528\u8BED" }
114642
+ ];
114643
+ function matchRisk(text2) {
114644
+ for (const r of POLICY_RISK_RULES) {
114645
+ if (r.re.test(text2)) return r.label;
114646
+ }
114647
+ return void 0;
114648
+ }
114649
+ function collectRsaTexts(ad) {
114650
+ const keys = ["headlinePart1", "headlinePart2", "headlinePart3", "adDescription", "adDescription2"];
114651
+ const out = [];
114652
+ for (const k of keys) {
114653
+ const v = ad[k];
114654
+ if (typeof v === "string" && v.trim()) out.push(v);
114655
+ }
114656
+ for (const k of ["AddtionalHeadlines", "AddtionalAdDescriptions"]) {
114657
+ const arr = ad[k];
114658
+ if (Array.isArray(arr)) {
114659
+ for (const v of arr) if (typeof v === "string" && v.trim()) out.push(v);
114660
+ }
114661
+ }
114662
+ return out;
114663
+ }
114664
+ function warnPolicyRiskTerms(campaign, warnings) {
114665
+ const groups = campaign["AdGroupsForBatchJob"];
114666
+ if (!Array.isArray(groups)) return;
114667
+ const hitsByLabel = /* @__PURE__ */ new Map();
114668
+ const add = (label, text2) => {
114669
+ let set = hitsByLabel.get(label);
114670
+ if (!set) hitsByLabel.set(label, set = /* @__PURE__ */ new Set());
114671
+ set.add(text2.trim());
114672
+ };
114673
+ for (const g of groups) {
114674
+ const gr = g;
114675
+ const kws = gr?.["KeywordsForBatchJob"];
114676
+ if (Array.isArray(kws)) {
114677
+ for (const b of kws) {
114678
+ const texts = b?.["KeywordText"];
114679
+ if (!Array.isArray(texts)) continue;
114680
+ for (const t of texts) {
114681
+ if (typeof t !== "string") continue;
114682
+ const label = matchRisk(t);
114683
+ if (label) add(label, t);
114684
+ }
114685
+ }
114686
+ }
114687
+ const ads = gr?.["AdsForBatchJob"];
114688
+ if (Array.isArray(ads)) {
114689
+ for (const ad of ads) {
114690
+ if (!ad || typeof ad !== "object") continue;
114691
+ for (const t of collectRsaTexts(ad)) {
114692
+ const label = matchRisk(t);
114693
+ if (label) add(label, t);
114694
+ }
114695
+ }
114696
+ }
114697
+ }
114698
+ for (const [label, set] of hitsByLabel) {
114699
+ const sample = [...set].slice(0, 5).map((s) => `\u300C${s}\u300D`).join("\u3001");
114700
+ warnings.push(
114701
+ `\u653F\u7B56\u98CE\u9669\u8BCD\u9762\uFF08${label}\uFF09\uFF1A${sample}${set.size > 5 ? ` \u7B49 ${set.size} \u6761` : ""}\uFF1B\u7F51\u5173\u65E0\u653F\u7B56\u9884\u68C0\uFF0C\u521B\u5EFA\u540E\u53EF\u80FD\u88AB PolicyViolation \u62D2\u7EDD\u2014\u2014\u521B\u5EFA\u524D\u5411\u7528\u6237\u8BF4\u660E\u98CE\u9669\uFF0C\u5FC5\u8981\u65F6\u6539\u5199\u6216\u5220\u9664`
114702
+ );
114703
+ }
114704
+ }
114476
114705
 
114477
114706
  // src/commands/ad/campaign-rsa.ts
114478
114707
  function normalizeRsaAssetKey(text2) {
@@ -114608,6 +114837,27 @@ function validateLocationsFidelity(cfg, campaign, errors) {
114608
114837
  );
114609
114838
  }
114610
114839
  }
114840
+ const excludedLocations = campaign["excludedLocations"];
114841
+ if (Array.isArray(excludedLocations) && excludedLocations.length > 0) {
114842
+ const targetedIdx = /* @__PURE__ */ new Map();
114843
+ targetedLocations.forEach((loc, i) => {
114844
+ const id = loc && typeof loc === "object" ? readLocationId(loc) : void 0;
114845
+ if (id !== void 0 && id !== null) targetedIdx.set(String(id).trim(), i);
114846
+ });
114847
+ const names = Array.isArray(cfg.locations) ? cfg.locations : [];
114848
+ for (let i = 0; i < excludedLocations.length; i++) {
114849
+ const loc = excludedLocations[i];
114850
+ const id = loc && typeof loc === "object" ? readLocationId(loc) : void 0;
114851
+ if (id === void 0 || id === null) continue;
114852
+ const ti = targetedIdx.get(String(id).trim());
114853
+ if (ti === void 0) continue;
114854
+ const label = typeof names[ti] === "string" ? `\u300C${names[ti]}\u300D` : "";
114855
+ pushErr2(
114856
+ errors,
114857
+ `campaign.excludedLocations[${i}].id=${String(id)} \u540C\u65F6\u51FA\u73B0\u5728 targetedLocations[${ti}]${label}\uFF1B\u540C\u4E00\u5730\u57DF\u65E2\u6295\u653E\u53C8\u6392\u9664\u4F1A\u4F7F BatchJob \u62A5 campaign_criterion \u2026negative immutable\u3002\u591A\u4E3A geo resolve \u628A\u6B67\u4E49\u5730\u540D\uFF08\u5982\u300C\u521A\u679C\u300Dvs\u300C\u521A\u679C\u6C11\u4E3B\u5171\u548C\u56FD\u300D\uFF09\u89E3\u6790\u6210\u540C\u4E00 ID\uFF1A\u7528 ad geo search \u6838\u5BF9\u540E\u4FEE\u6B63\u8BE5\u6761\uFF0C\u52FF\u6574\u6279\u5220\u9664\u6392\u9664\u5730\u57DF`
114858
+ );
114859
+ }
114860
+ }
114611
114861
  const locations = cfg.locations;
114612
114862
  if (Array.isArray(locations) && locations.length > 0) {
114613
114863
  if (locations.length !== targetedLocations.length) {
@@ -114787,6 +115037,56 @@ function validateRsaAd(prefix, ad, errors, warnings, lengthViolations) {
114787
115037
  }
114788
115038
  validateRsaHeadlinesWithinAd(prefix, ad, errors);
114789
115039
  }
115040
+ var DEVICE_PLATFORM_IDS = {
115041
+ "30000": "Desktop",
115042
+ "30001": "Mobile",
115043
+ "30002": "Tablet",
115044
+ "30004": "ConnectedTv"
115045
+ };
115046
+ function validateTargetedPlatforms(campaign, errors, warnings) {
115047
+ const platforms = campaign["targetedPlatforms"];
115048
+ if (platforms === void 0 || platforms === null) return;
115049
+ if (!Array.isArray(platforms)) {
115050
+ pushErr2(errors, "campaign.targetedPlatforms \u5FC5\u987B\u662F\u6570\u7EC4");
115051
+ return;
115052
+ }
115053
+ const seen = /* @__PURE__ */ new Set();
115054
+ for (let i = 0; i < platforms.length; i++) {
115055
+ const p = platforms[i];
115056
+ const prefix = `campaign.targetedPlatforms[${i}]`;
115057
+ const id = String(p?.["id"] ?? p?.["Id"] ?? "");
115058
+ if (!DEVICE_PLATFORM_IDS[id]) {
115059
+ pushErr2(
115060
+ errors,
115061
+ `${prefix}.id \u65E0\u6548\uFF08${id || "\u7A7A"}\uFF09\uFF0C\u5408\u6CD5\u503C\uFF1A30000 Desktop / 30001 Mobile / 30002 Tablet / 30004 ConnectedTv`
115062
+ );
115063
+ continue;
115064
+ }
115065
+ if (seen.has(id)) pushErr2(errors, `${prefix}.id=${id} \u91CD\u590D`);
115066
+ seen.add(id);
115067
+ const bm = p["bidModifier"] ?? p["BidModifier"];
115068
+ if (bm === void 0 || bm === null) continue;
115069
+ if (typeof bm !== "number" || !Number.isFinite(bm)) {
115070
+ pushErr2(errors, `${prefix}.bidModifier \u5FC5\u987B\u662F\u6570\u5B57\uFF08\u767E\u5206\u6BD4\uFF1A0 \u4E0D\u8C03\u6574\uFF0C-100 \u6392\u9664\uFF0C20 = +20%\uFF09`);
115071
+ } else if (bm < -100 || bm > 900) {
115072
+ pushErr2(errors, `${prefix}.bidModifier=${bm} \u8D85\u51FA\u8303\u56F4 [-100, 900]\uFF08\u767E\u5206\u6BD4\u53E3\u5F84\uFF09`);
115073
+ } else if (bm !== 0 && Math.abs(bm) < 2 && !Number.isInteger(bm)) {
115074
+ pushWarn2(
115075
+ warnings,
115076
+ `${prefix}.bidModifier=${bm} \u7591\u4F3C\u500D\u7387\u53E3\u5F84\uFF1Bcampaign-create \u7528\u767E\u5206\u6BD4\uFF08-20 = \u964D 20%\uFF0C-100 = \u6392\u9664\uFF09\uFF0C\u4E0E ad device-bid set \u7684\u500D\u7387\u4E0D\u540C`
115077
+ );
115078
+ }
115079
+ }
115080
+ if (platforms.length > 0) {
115081
+ const missing = ["30000", "30001", "30002"].filter((id) => !seen.has(id));
115082
+ if (missing.length > 0) {
115083
+ pushWarn2(
115084
+ warnings,
115085
+ `campaign.targetedPlatforms \u672A\u5217\u51FA ${missing.map((id) => `${id} ${DEVICE_PLATFORM_IDS[id]}`).join("\u3001")}\uFF1A\u7701\u7565\u4E0D\u7B49\u4E8E\u6392\u9664\uFF0CGoogle \u4ECD\u4F1A\u6295\u653E\uFF1B\u8981\u6392\u9664\u8BF7\u5199 { "id": ${missing[0]}, "bidModifier": -100 }`
115086
+ );
115087
+ }
115088
+ }
115089
+ }
114790
115090
  function validateCampaignCreateConfigCore(cfg) {
114791
115091
  const errors = [];
114792
115092
  const warnings = [];
@@ -114900,6 +115200,11 @@ function validateCampaignCreateConfigCore(cfg) {
114900
115200
  errors,
114901
115201
  "TARGET_SPEND \u51FA\u4EF7\u7B56\u7565\u4E0B campaign.TargetSpend_BidCeilingAmount\uFF08CPC \u4E0A\u9650\uFF0C\u5143\uFF09\u5FC5\u987B\u4E3A\u6B63\u6570"
114902
115202
  );
115203
+ } else if (typeof budget === "number" && budget > 0 && ceiling >= budget) {
115204
+ pushWarn2(
115205
+ warnings,
115206
+ `campaign.TargetSpend_BidCeilingAmount\uFF08${ceiling} \u5143\uFF09\u2265 \u65E5\u9884\u7B97\uFF08${budget} \u5143\uFF09\uFF0C\u7B49\u4E8E\u4E0D\u8BBE CPC \u4E0A\u9650\uFF1B\u5E38\u89C1\u4E8E\u65B9\u6848\u628A\u300C\u7CFB\u5217\u51FA\u4EF7\u300D\u8BEF\u586B\u6210\u9884\u7B97\uFF0C\u521B\u5EFA\u524D\u987B\u5411\u7528\u6237\u786E\u8BA4`
115207
+ );
114903
115208
  }
114904
115209
  }
114905
115210
  if (biddingStr === "TARGET_CPA") {
@@ -114918,6 +115223,7 @@ function validateCampaignCreateConfigCore(cfg) {
114918
115223
  }
114919
115224
  }
114920
115225
  validateLocationsFidelity(cfg, campaign, errors);
115226
+ validateTargetedPlatforms(campaign, errors, warnings);
114921
115227
  const targetedLanguages = campaign["targetedLanguages"];
114922
115228
  if (!Array.isArray(targetedLanguages) || targetedLanguages.length === 0) {
114923
115229
  pushErr2(errors, "campaign.targetedLanguages \u4E0D\u80FD\u4E3A\u7A7A\uFF08\u82F1\u8BED id=1000\uFF0C\u4E2D\u6587 id=1017\uFF09");
@@ -115023,13 +115329,16 @@ function validateCampaignCreateConfigCore(cfg) {
115023
115329
  pushErr2(errors, `${gPrefix}.TypeV2 \u4E0D\u80FD\u4E3A "${gTypeV2}"\uFF08\u4F1A\u5BFC\u81F4 Google \u62D2\u7EDD\u5E7F\u544A\u7EC4\uFF09`);
115024
115330
  }
115025
115331
  const mc = g["MaxCPCAmount"];
115026
- if (mc !== void 0 && (typeof mc !== "number" || !Number.isFinite(mc) || mc < 0)) {
115027
- pushErr2(errors, `${gPrefix}.MaxCPCAmount \u5FC5\u987B\u4E3A\u975E\u8D1F\u6570\u5B57\uFF08\u5355\u4F4D\u300C\u5143\u300D\uFF09`);
115028
- }
115029
- if (biddingStr === "MANUAL_CPC") {
115030
- if (typeof mc !== "number" || mc <= 0) {
115031
- pushErr2(errors, `MANUAL_CPC \u4E0B ${gPrefix}.MaxCPCAmount \u5FC5\u987B\u4E3A\u6B63\u6570`);
115032
- }
115332
+ if (typeof mc !== "number" || !Number.isFinite(mc) || Math.round(mc * 100) <= 0) {
115333
+ pushErr2(
115334
+ errors,
115335
+ `${gPrefix}.MaxCPCAmount \u5FC5\u987B\u4E3A\u6B63\u6570\uFF08\u5355\u4F4D\u300C\u5143\u300D\uFF0C\u5F53\u524D ${JSON.stringify(mc ?? null)}\uFF09\uFF1B\u4EFB\u4F55\u51FA\u4EF7\u7B56\u7565\uFF08\u542B ${biddingStr || "TARGET_SPEND"}\uFF09\u4E0B\u7F3A\u7701\u6216 0 \u90FD\u4F1A\u88AB Google \u62D2\uFF08cpc_bid_micros Too low\uFF09\uFF0C\u5E7F\u544A\u7EC4\u5EFA\u4E0D\u51FA\u6765\u3001\u5176\u4E0B\u5173\u952E\u8BCD/\u5E7F\u544A\u5168\u90E8 Resource not found\u3002\u6309\u65B9\u6848\u586B\u9ED8\u8BA4 CPC\uFF0C\u65B9\u6848\u65E0\u503C\u5219\u5148\u95EE\u7528\u6237`
115336
+ );
115337
+ } else if (typeof budget === "number" && budget > 0 && mc >= budget) {
115338
+ pushWarn2(
115339
+ warnings,
115340
+ `${gPrefix}.MaxCPCAmount\uFF08${mc} \u5143\uFF09\u2265 \u65E5\u9884\u7B97\uFF08${budget} \u5143\uFF09\uFF0C\u4E00\u6B21\u70B9\u51FB\u53EF\u80FD\u82B1\u5149\u5F53\u5929\u9884\u7B97\uFF1B\u521B\u5EFA\u524D\u987B\u5411\u7528\u6237\u786E\u8BA4`
115341
+ );
115033
115342
  }
115034
115343
  const ads = g["AdsForBatchJob"];
115035
115344
  if (Array.isArray(ads)) {
@@ -115074,6 +115383,7 @@ function validateCampaignCreateConfigCore(cfg) {
115074
115383
  }
115075
115384
  }
115076
115385
  validateCampaignRsaCrossGroupHeadlines(campaign, errors);
115386
+ warnPolicyRiskTerms(campaign, warnings);
115077
115387
  }
115078
115388
  validateCampaignExtensionsForBatchJob(campaign, errors, warnings, lengthViolations);
115079
115389
  return { errors, warnings, lengthViolations };
@@ -115321,6 +115631,16 @@ async function runAdCampaignDelete(opts) {
115321
115631
  );
115322
115632
  process.exit(1);
115323
115633
  }
115634
+ if (!opts.iConfirm) {
115635
+ const name2 = campaign["name"] ?? campaign["Name"] ?? "\u2014";
115636
+ const status = campaign["statusV2"] ?? campaign["status"] ?? "\u2014";
115637
+ console.error(`
115638
+ \u5F85\u5220\u9664\u7CFB\u5217\uFF1A${opts.id}\u300C${String(name2)}\u300D\uFF08\u72B6\u6001 ${String(status)}\uFF09`);
115639
+ }
115640
+ ensureIConfirm({
115641
+ iConfirm: opts.iConfirm,
115642
+ actionLabel: `ad campaign-delete\uFF08\u5220\u9664\u5E7F\u544A\u7CFB\u5217 ${opts.id}\uFF0C\u4E0D\u53EF\u6062\u590D\uFF09`
115643
+ });
115324
115644
  try {
115325
115645
  await apiDeleteRaw(detailUrl, config, {
115326
115646
  body: JSON.stringify(campaign),
@@ -117016,6 +117336,7 @@ init_auth();
117016
117336
  init_cli_json_snapshot();
117017
117337
  init_bid_modifier_display();
117018
117338
  init_bid_modifier_display();
117339
+ var CAMPAIGN_ZERO_AMBIGUOUS_DISPLAY = "\u2014 \u6216 -100%\uFF08\u7F51\u5173\u4E0D\u533A\u5206\uFF0C\u9700\u5728 Google Ads \u540E\u53F0\u786E\u8BA4\uFF09";
117019
117340
  function multiplierToAdGroupBidPercent(multiplier) {
117020
117341
  return Math.round((multiplier - 1) * 100 * 100) / 100;
117021
117342
  }
@@ -117107,16 +117428,20 @@ async function runAdDeviceBidList(opts) {
117107
117428
  if (opts.campaignId) {
117108
117429
  rows = rows.filter((r) => String(r.campaignId ?? "") === opts.campaignId);
117109
117430
  }
117110
- items3 = rows.map((row) => ({
117111
- level: "campaign",
117112
- id: row.id,
117113
- campaignId: row.campaignId,
117114
- campaignName: row.campaignName,
117115
- deviceType: row.deviceType,
117116
- bidModifier: row.bidModifier,
117117
- bidModifierDisplay: row.bidModifier != null ? formatBidModifierPercent(row.bidModifier, row.bidModifierSpecified) : GOOGLE_ADS_UNSET_BID_DISPLAY,
117118
- bidModifierSpecified: row.bidModifierSpecified
117119
- }));
117431
+ items3 = rows.map((row) => {
117432
+ const ambiguousZero = row.bidModifier === 0 && row.bidModifierSpecified == null;
117433
+ return {
117434
+ level: "campaign",
117435
+ id: row.id,
117436
+ campaignId: row.campaignId,
117437
+ campaignName: row.campaignName,
117438
+ deviceType: row.deviceType,
117439
+ bidModifier: row.bidModifier,
117440
+ bidModifierDisplay: ambiguousZero ? CAMPAIGN_ZERO_AMBIGUOUS_DISPLAY : row.bidModifier != null ? formatBidModifierPercent(row.bidModifier, row.bidModifierSpecified) : GOOGLE_ADS_UNSET_BID_DISPLAY,
117441
+ bidModifierSpecified: row.bidModifierSpecified,
117442
+ ...ambiguousZero ? { unsetOrExcluded: true } : {}
117443
+ };
117444
+ });
117120
117445
  levelLabel = opts.campaignId ? `\u7CFB\u5217 ${opts.campaignId}` : "\u8D26\u6237\u4E0B\u5168\u90E8\u7CFB\u5217";
117121
117446
  }
117122
117447
  const n = items3.length;
@@ -117270,18 +117595,89 @@ function geoItemDisplayName(item) {
117270
117595
  function geoItemType(item) {
117271
117596
  return String(item["targetType"] ?? item["typeV2"] ?? "");
117272
117597
  }
117273
- function pickGeoResolveCandidate(query, items3) {
117274
- if (items3.length === 0) return null;
117275
- const q = query.trim().toLowerCase();
117276
- const isCountry = (it) => /country/i.test(geoItemType(it)) || geoItemType(it).toUpperCase() === "COUNTRY";
117277
- const nameEq = (it) => geoItemDisplayName(it).trim().toLowerCase() === q;
117278
- const exactCountry = items3.find((it) => isCountry(it) && nameEq(it));
117279
- if (exactCountry) return exactCountry;
117280
- const anyCountry = items3.find((it) => isCountry(it));
117281
- if (anyCountry) return anyCountry;
117282
- const exactAny = items3.find((it) => nameEq(it));
117283
- if (exactAny) return exactAny;
117284
- return items3[0] ?? null;
117598
+ function splitGeoName(display) {
117599
+ const m = /^(.*\S)\s*\(([^()]+)\)\s*$/.exec(display.trim());
117600
+ if (!m) return { base: display.trim(), level: "" };
117601
+ const level = m[2].trim();
117602
+ if (!/^(Country|Region|Territory|State|Province|City|Municipality|County|District|Postal Code|Neighborhood|Sub District|Department|Prefecture|Governorate|Autonomous Community|Union Territory|Canton|Okrug|Borough|Airport|University|TV Region|Congressional District|National Park)$/i.test(level)) {
117603
+ return { base: display.trim(), level: "" };
117604
+ }
117605
+ return { base: m[1].trim(), level };
117606
+ }
117607
+ var GEO_NAME_ALIASES = {
117608
+ turkey: "turkiye",
117609
+ "czech republic": "czechia",
117610
+ burma: "myanmar (burma)",
117611
+ myanmar: "myanmar (burma)",
117612
+ "ivory coast": "cote d'ivoire",
117613
+ "c\xF4te d'ivoire": "cote d'ivoire",
117614
+ macau: "macao",
117615
+ swaziland: "eswatini",
117616
+ "east timor": "timor-leste",
117617
+ bahamas: "the bahamas",
117618
+ gambia: "the gambia",
117619
+ "republic of congo": "republic of the congo",
117620
+ "congo-brazzaville": "republic of the congo",
117621
+ "dr congo": "democratic republic of the congo",
117622
+ drc: "democratic republic of the congo",
117623
+ "congo-kinshasa": "democratic republic of the congo",
117624
+ "republic of korea": "south korea",
117625
+ uk: "united kingdom",
117626
+ "great britain": "united kingdom",
117627
+ usa: "united states",
117628
+ us: "united states",
117629
+ uae: "united arab emirates",
117630
+ "north macedonia": "north macedonia",
117631
+ macedonia: "north macedonia",
117632
+ "cape verde": "cabo verde",
117633
+ "vatican": "vatican city",
117634
+ "holy see": "vatican city"
117635
+ };
117636
+ var GEO_UNSERVED = {
117637
+ iran: "Iran",
117638
+ cuba: "Cuba",
117639
+ "north korea": "North Korea",
117640
+ "democratic people's republic of korea": "North Korea",
117641
+ dprk: "North Korea",
117642
+ crimea: "Crimea"
117643
+ };
117644
+ function normGeoName(s) {
117645
+ return s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim().toLowerCase().replace(/\s+/g, " ");
117646
+ }
117647
+ function geoQueryKey(query) {
117648
+ const q = normGeoName(query);
117649
+ return GEO_NAME_ALIASES[q] ?? q;
117650
+ }
117651
+ function pickGeoCandidate(query, items3) {
117652
+ const key = geoQueryKey(query);
117653
+ const unserved = GEO_UNSERVED[normGeoName(query)];
117654
+ const parsed = items3.map((it) => {
117655
+ const { base, level } = splitGeoName(geoItemDisplayName(it));
117656
+ return { it, base, level: level || geoItemType(it) };
117657
+ });
117658
+ const same = parsed.filter((p) => normGeoName(p.base) === key || normGeoName(geoItemDisplayName(p.it)) === key);
117659
+ const rank = (lvl) => {
117660
+ const l = lvl.toLowerCase();
117661
+ if (l === "country") return 0;
117662
+ if (l === "region" || l === "territory") return 1;
117663
+ return 2;
117664
+ };
117665
+ same.sort((a, b) => rank(a.level) - rank(b.level));
117666
+ const usable = unserved ? same.filter((p) => rank(p.level) < 2) : same;
117667
+ if (usable.length > 0) return { picked: usable[0].it, status: "ok" };
117668
+ if (unserved) {
117669
+ return {
117670
+ picked: null,
117671
+ status: "unserved",
117672
+ note: `${unserved} \u5728 Google \u5730\u57DF\u5E93\u4E2D\u65E0\u56FD\u5BB6\u7EA7\u6761\u76EE\uFF08Google Ads \u4E0D\u5728\u8BE5\u5730\u533A\u6295\u653E\uFF09\uFF0C\u6392\u9664\u5217\u8868\u53EF\u5FFD\u7565`
117673
+ };
117674
+ }
117675
+ if (items3.length === 0) return { picked: null, status: "not_found" };
117676
+ return {
117677
+ picked: null,
117678
+ status: "needs_review",
117679
+ note: "\u65E0\u540C\u540D\u5019\u9009\uFF0C\u672A\u81EA\u52A8\u9009\u62E9\uFF1B\u8BF7\u4ECE candidates \u4E2D\u4EBA\u5DE5\u786E\u8BA4\uFF0C\u6216\u7528 ad geo search \u6362\u82F1\u6587\u6807\u51C6\u540D"
117680
+ };
117285
117681
  }
117286
117682
  async function runAdGeoSearch(opts) {
117287
117683
  opts = withResolvedAdAccount(opts);
@@ -117307,14 +117703,17 @@ async function runAdGeoSearch(opts) {
117307
117703
  name: geoItemDisplayName(item) || null,
117308
117704
  targetType: geoItemType(item) || null
117309
117705
  }));
117310
- const picked = pickGeoResolveCandidate(opts.query, items3);
117706
+ const pick2 = pickGeoCandidate(opts.query, items3);
117707
+ const picked = pick2.picked;
117311
117708
  const pickedId = picked ? String(picked["id"] ?? "") || null : null;
117312
117709
  const payload = {
117313
117710
  account: opts.account,
117314
117711
  query: opts.query,
117315
117712
  itemCount: rows.length,
117316
117713
  items: rows,
117317
- /** 单国写入 campaign-create 时优先用此选中项(Country 精确匹配优先) */
117714
+ /** ok=同名候选(Country 优先);needs_review=无同名候选未自动选;unserved=Google 不投放地区 */
117715
+ pickStatus: pick2.status,
117716
+ pickNote: pick2.note ?? null,
117318
117717
  picked: picked ? {
117319
117718
  id: pickedId,
117320
117719
  name: geoItemDisplayName(picked) || null,
@@ -117356,7 +117755,9 @@ async function runAdGeoSearch(opts) {
117356
117755
  `
117357
117756
  );
117358
117757
  } else {
117359
- console.log();
117758
+ console.log(`
117759
+ \u26A0\uFE0F \u672A\u81EA\u52A8\u9009\u62E9\uFF1A${pick2.note ?? "\u65E0\u540C\u540D\u5019\u9009"}
117760
+ `);
117360
117761
  }
117361
117762
  }
117362
117763
  function parseGeoResolveQueries(opts) {
@@ -117398,6 +117799,26 @@ function parseGeoResolveQueries(opts) {
117398
117799
  }
117399
117800
  return unique;
117400
117801
  }
117802
+ var GEO_RESOLVE_CONCURRENCY = 6;
117803
+ function buildGeoResolveRow(query, items3) {
117804
+ const pick2 = pickGeoCandidate(query, items3);
117805
+ const row = {
117806
+ query,
117807
+ id: pick2.picked ? String(pick2.picked["id"] ?? "") || null : null,
117808
+ name: pick2.picked ? geoItemDisplayName(pick2.picked) || null : null,
117809
+ targetType: pick2.picked ? geoItemType(pick2.picked) || null : null,
117810
+ status: pick2.status,
117811
+ candidates: items3.length
117812
+ };
117813
+ if (pick2.note) row.note = pick2.note;
117814
+ if (pick2.status === "needs_review") {
117815
+ row.topCandidates = items3.slice(0, 5).map((it) => ({
117816
+ id: String(it["id"] ?? ""),
117817
+ name: geoItemDisplayName(it)
117818
+ }));
117819
+ }
117820
+ return row;
117821
+ }
117401
117822
  async function runAdGeoResolve(opts) {
117402
117823
  opts = withResolvedAdAccount(opts);
117403
117824
  let queries;
@@ -117415,53 +117836,46 @@ async function runAdGeoResolve(opts) {
117415
117836
  }
117416
117837
  const config = loadConfig(opts.token);
117417
117838
  const googleApiUrl = requireGoogleApi(config);
117418
- const rows = [];
117419
- for (const query of queries) {
117420
- let items3 = [];
117421
- try {
117422
- items3 = await fetchGeoLocationCandidates(
117423
- googleApiUrl,
117424
- opts.account,
117425
- query,
117426
- config,
117427
- opts.verbose
117428
- );
117429
- } catch (err) {
117430
- console.error(
117431
- `
117839
+ const rows = new Array(queries.length);
117840
+ let cursor = 0;
117841
+ const worker = async () => {
117842
+ while (cursor < queries.length) {
117843
+ const idx = cursor++;
117844
+ const query = queries[idx];
117845
+ let items3 = [];
117846
+ try {
117847
+ items3 = await fetchGeoLocationCandidates(
117848
+ googleApiUrl,
117849
+ opts.account,
117850
+ query,
117851
+ config,
117852
+ opts.verbose
117853
+ );
117854
+ } catch (err) {
117855
+ console.error(
117856
+ `
117432
117857
  \u274C \u89E3\u6790\u300C${query}\u300D\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}
117433
117858
  `
117434
- );
117435
- process.exit(1);
117436
- }
117437
- const picked = pickGeoResolveCandidate(query, items3);
117438
- if (!picked) {
117439
- rows.push({
117440
- query,
117441
- id: null,
117442
- name: null,
117443
- targetType: null,
117444
- status: "not_found",
117445
- candidates: 0
117446
- });
117447
- continue;
117859
+ );
117860
+ process.exit(1);
117861
+ }
117862
+ rows[idx] = buildGeoResolveRow(query, items3);
117448
117863
  }
117449
- rows.push({
117450
- query,
117451
- id: String(picked["id"] ?? "") || null,
117452
- name: geoItemDisplayName(picked) || null,
117453
- targetType: geoItemType(picked) || null,
117454
- status: items3.length > 1 ? "ambiguous_ok" : "ok",
117455
- candidates: items3.length
117456
- });
117457
- }
117458
- const failed = rows.filter((r) => !r.id);
117864
+ };
117865
+ await Promise.all(
117866
+ Array.from({ length: Math.min(GEO_RESOLVE_CONCURRENCY, queries.length) }, () => worker())
117867
+ );
117868
+ const failed = rows.filter((r) => !r.id && r.status !== "unserved");
117869
+ const unserved = rows.filter((r) => r.status === "unserved");
117459
117870
  const locations = rows.filter((r) => r.id).map((r) => r.query);
117460
117871
  const targetedLocations = rows.filter((r) => r.id).map((r) => ({ id: r.id }));
117461
117872
  const payload = {
117462
117873
  account: opts.account,
117463
117874
  resolved: rows.filter((r) => r.id).length,
117464
117875
  failed: failed.length,
117876
+ /** Google 不投放地区(Iran/Cuba/North Korea/Crimea):不计失败,不写入 locations */
117877
+ unserved: unserved.map((r) => r.query),
117878
+ needsReview: rows.filter((r) => r.status === "needs_review").map((r) => r.query),
117465
117879
  rows,
117466
117880
  /** 可直接写入 campaign-create JSON */
117467
117881
  locations,
@@ -117488,15 +117902,22 @@ async function runAdGeoResolve(opts) {
117488
117902
  );
117489
117903
  for (const r of rows) {
117490
117904
  if (r.id) {
117491
- console.log(` \u2705 ${r.query} \u2192 id:${r.id} ${r.name ?? ""} [${r.targetType ?? ""}]`);
117905
+ console.log(` \u2705 ${r.query} \u2192 id:${r.id} ${r.name ?? ""}`);
117906
+ } else if (r.status === "unserved") {
117907
+ console.log(` \u23ED ${r.query} \u2192 ${r.note}`);
117908
+ } else if (r.status === "needs_review") {
117909
+ const cands = (r.topCandidates ?? []).map((c) => `${c.id} ${c.name}`).join(" \uFF5C ");
117910
+ console.log(` \u26A0\uFE0F ${r.query} \u2192 \u65E0\u540C\u540D\u5019\u9009\uFF0C\u672A\u81EA\u52A8\u9009\u62E9\u3002\u5019\u9009\uFF1A${cands}`);
117492
117911
  } else {
117493
117912
  console.log(` \u274C ${r.query} \u2192 \u672A\u627E\u5230`);
117494
117913
  }
117495
117914
  }
117496
117915
  if (failed.length > 0) {
117497
- console.error(`
117498
- \u274C ${failed.length} \u4E2A\u5730\u540D\u672A\u89E3\u6790\uFF1B\u8BF7\u6539\u540D\u540E\u91CD\u8BD5\uFF0C\u6216\u68C0\u67E5\u62FC\u5199\uFF08\u52FF\u7F16\u9020 id\uFF09\u3002
117499
- `);
117916
+ console.error(
117917
+ `
117918
+ \u274C ${failed.length} \u4E2A\u5730\u540D\u672A\u89E3\u6790\uFF08\u542B\u65E0\u540C\u540D\u5019\u9009\uFF09\uFF1B\u8BF7\u6362\u82F1\u6587\u6807\u51C6\u540D\u6216\u7528 ad geo search \u4EBA\u5DE5\u786E\u8BA4\uFF08\u52FF\u7F16\u9020 id\u3001\u52FF\u53D6\u7B2C\u4E00\u6761\u5019\u9009\uFF09\u3002
117919
+ `
117920
+ );
117500
117921
  if (!opts.allowPartial) process.exit(1);
117501
117922
  } else {
117502
117923
  console.log(
@@ -117809,10 +118230,221 @@ function buildExtensionRemediateCommandLine(opts) {
117809
118230
  return null;
117810
118231
  }
117811
118232
 
117812
- // src/commands/ad/campaign-batch-diff.ts
118233
+ // src/commands/ad/campaign-batch-op-index.ts
117813
118234
  function asRecord3(v) {
117814
118235
  return v && typeof v === "object" && !Array.isArray(v) ? v : null;
117815
118236
  }
118237
+ function pickArray(obj, ...keys) {
118238
+ for (const k of keys) {
118239
+ const v = obj[k];
118240
+ if (Array.isArray(v)) return v;
118241
+ }
118242
+ return [];
118243
+ }
118244
+ function pickText(obj, ...keys) {
118245
+ if (!obj) return "";
118246
+ for (const k of keys) {
118247
+ const v = obj[k];
118248
+ if (typeof v === "string" && v.trim()) return v.trim();
118249
+ if (typeof v === "number") return String(v);
118250
+ }
118251
+ return "";
118252
+ }
118253
+ function idOf(v) {
118254
+ const r = asRecord3(v);
118255
+ return r ? pickText(r, "id", "Id") : typeof v === "string" || typeof v === "number" ? String(v) : "";
118256
+ }
118257
+ var AD_GROUP_CRITERIA_KEYS = [
118258
+ "AgeRanges",
118259
+ "ExcludedAgeRanges",
118260
+ "Genders",
118261
+ "ExcludedGenders",
118262
+ "IncomeRanges",
118263
+ "ExcludedIncomeRanges",
118264
+ "Parents",
118265
+ "ExcludedParents",
118266
+ "UserInterests",
118267
+ "CriterionVerticals"
118268
+ ];
118269
+ function lowerFirst(s) {
118270
+ return s.charAt(0).toLowerCase() + s.slice(1);
118271
+ }
118272
+ function buildBatchOperationSlots(cfg) {
118273
+ const campaign = asRecord3(cfg.campaign) ?? {};
118274
+ const names = Array.isArray(cfg.locations) ? cfg.locations : [];
118275
+ const slots = [];
118276
+ const push = (kind, path55, label) => slots.push({ index: slots.length, kind, path: path55, label });
118277
+ push("campaign_budget", "campaign.Budget", "\u7CFB\u5217\u9884\u7B97");
118278
+ push("campaign", "campaign.Name", `\u7CFB\u5217\u300C${pickText(campaign, "Name", "name") || "\u2014"}\u300D`);
118279
+ pickArray(campaign, "targetedLocations", "TargetedLocations").forEach((loc, i) => {
118280
+ const name2 = typeof names[i] === "string" ? `\uFF08${names[i]}\uFF09` : "";
118281
+ push(
118282
+ "campaign_criterion",
118283
+ `campaign.targetedLocations[${i}]`,
118284
+ `\u6295\u653E\u5730\u57DF id=${idOf(loc)}${name2}`
118285
+ );
118286
+ });
118287
+ pickArray(campaign, "excludedLocations", "ExcludedLocations").forEach((loc, i) => {
118288
+ push("campaign_criterion", `campaign.excludedLocations[${i}]`, `\u6392\u9664\u5730\u57DF id=${idOf(loc)}`);
118289
+ });
118290
+ pickArray(campaign, "excludedIpAddresses", "ExcludedIpAddresses").forEach((ip, i) => {
118291
+ push("campaign_criterion", `campaign.excludedIpAddresses[${i}]`, `\u6392\u9664 IP ${String(ip)}`);
118292
+ });
118293
+ pickArray(campaign, "adSchedules", "AdSchedules").forEach((_, i) => {
118294
+ push("campaign_criterion", `campaign.adSchedules[${i}]`, `\u6295\u653E\u65F6\u6BB5 #${i}`);
118295
+ });
118296
+ pickArray(campaign, "targetedPlatforms", "TargetedPlatforms").forEach((p, i) => {
118297
+ push("campaign_criterion", `campaign.targetedPlatforms[${i}]`, `\u6295\u653E\u8BBE\u5907 id=${idOf(p)}`);
118298
+ });
118299
+ pickArray(campaign, "targetedLanguages", "TargetedLanguages").forEach((l, i) => {
118300
+ push("campaign_criterion", `campaign.targetedLanguages[${i}]`, `\u6295\u653E\u8BED\u8A00 id=${idOf(l)}`);
118301
+ });
118302
+ pickArray(campaign, "excludedContentLabels", "ExcludedContentLabels").forEach((_, i) => {
118303
+ push("campaign_criterion", `campaign.excludedContentLabels[${i}]`, `\u6392\u9664\u5185\u5BB9\u6807\u7B7E #${i}`);
118304
+ });
118305
+ pickArray(campaign, "NegativeKeywordsForBatchJob", "negativeKeywordsForBatchJob").forEach(
118306
+ (block, bi) => {
118307
+ const texts = pickArray(asRecord3(block) ?? {}, "KeywordText", "keywordText");
118308
+ texts.forEach((t, ki) => {
118309
+ if (typeof t !== "string" || !t.trim()) return;
118310
+ push(
118311
+ "campaign_criterion",
118312
+ `campaign.NegativeKeywordsForBatchJob[${bi}].KeywordText[${ki}]`,
118313
+ `\u5426\u5B9A\u5173\u952E\u8BCD\u300C${t}\u300D`
118314
+ );
118315
+ });
118316
+ }
118317
+ );
118318
+ pickArray(campaign, "AdGroupsForBatchJob", "adGroupsForBatchJob").forEach((g, gi) => {
118319
+ const group = asRecord3(g) ?? {};
118320
+ const groupPath = `campaign.AdGroupsForBatchJob[${gi}]`;
118321
+ const groupName = pickText(group, "Name", "name") || `#${gi}`;
118322
+ push("ad_group", groupPath, `\u5E7F\u544A\u7EC4\u300C${groupName}\u300D`);
118323
+ for (const key of AD_GROUP_CRITERIA_KEYS) {
118324
+ pickArray(group, key, lowerFirst(key)).forEach((_, i) => {
118325
+ push(
118326
+ "ad_group_criterion",
118327
+ `${groupPath}.${key}[${i}]`,
118328
+ `\u5E7F\u544A\u7EC4\u300C${groupName}\u300D${key}[${i}]`
118329
+ );
118330
+ });
118331
+ }
118332
+ pickArray(group, "KeywordsForBatchJob", "keywordsForBatchJob").forEach((b, bi) => {
118333
+ const block = asRecord3(b) ?? {};
118334
+ const texts = pickArray(block, "KeywordText", "keywordText");
118335
+ if (texts.length > 0) {
118336
+ texts.forEach((t, ki) => {
118337
+ if (typeof t !== "string" || !t.trim()) return;
118338
+ push(
118339
+ "ad_group_criterion",
118340
+ `${groupPath}.KeywordsForBatchJob[${bi}].KeywordText[${ki}]`,
118341
+ `\u5173\u952E\u8BCD\u300C${t}\u300D\uFF08\u7EC4\u300C${groupName}\u300D\uFF09`
118342
+ );
118343
+ });
118344
+ return;
118345
+ }
118346
+ pickArray(block, "Items", "items").forEach((it, ii) => {
118347
+ const text2 = pickText(asRecord3(it), "Text", "text");
118348
+ push(
118349
+ "ad_group_criterion",
118350
+ `${groupPath}.KeywordsForBatchJob[${bi}].Items[${ii}]`,
118351
+ `\u5173\u952E\u8BCD\u300C${text2}\u300D\uFF08\u7EC4\u300C${groupName}\u300D\uFF09`
118352
+ );
118353
+ });
118354
+ });
118355
+ pickArray(group, "AdsForBatchJob", "adsForBatchJob").forEach((ad, ai) => {
118356
+ const h1 = pickText(asRecord3(ad), "headlinePart1", "HeadlinePart1");
118357
+ push(
118358
+ "ad_group_ad",
118359
+ `${groupPath}.AdsForBatchJob[${ai}]`,
118360
+ `\u5E7F\u544A #${ai}${h1 ? `\u300C${h1}\u300D` : ""}\uFF08\u7EC4\u300C${groupName}\u300D\uFF09`
118361
+ );
118362
+ });
118363
+ });
118364
+ const exts = pickArray(campaign, "ExtensionsForBatchJob", "extensionsForBatchJob");
118365
+ exts.forEach((e, ei) => {
118366
+ const type = pickText(asRecord3(e), "TypeV2", "typeV2", "AssetFieldType", "type");
118367
+ push(
118368
+ "asset",
118369
+ `campaign.ExtensionsForBatchJob[${ei}]`,
118370
+ `\u9644\u52A0\u4FE1\u606F #${ei}${type ? ` ${type}` : ""}`
118371
+ );
118372
+ });
118373
+ exts.forEach((_, ei) => {
118374
+ push("campaign_asset", `campaign.ExtensionsForBatchJob[${ei}]`, `\u9644\u52A0\u4FE1\u606F\u5173\u8054 #${ei}`);
118375
+ });
118376
+ return slots;
118377
+ }
118378
+ function buildSubmittedOperationSlots(cfg) {
118379
+ const clone = structuredClone(cfg);
118380
+ runCampaignCreateValidation(clone);
118381
+ return buildBatchOperationSlots(clone);
118382
+ }
118383
+ var OP_RE = /mutate_operations\[(\d+)\]\.([a-z_]+?)_operation\.([a-z_.]+)/;
118384
+ function parseBatchOperationErrors(text2) {
118385
+ const out = [];
118386
+ for (const seg of text2.split(/Processing error:\s*/).slice(1)) {
118387
+ const m = OP_RE.exec(seg);
118388
+ if (!m) continue;
118389
+ const head = seg.slice(0, m.index);
118390
+ const errorType = head.split(",")[0]?.trim() ?? "";
118391
+ const triggerMatch = /^[^,]*,\s*(\{[^}]*\}|)\s*,/.exec(head);
118392
+ const trigger = triggerMatch?.[1]?.trim() ?? "";
118393
+ const message = head.slice(triggerMatch?.[0].length ?? errorType.length + 1).replace(/,\s*$/, "").trim();
118394
+ const policyName = /"PolicyName"\s*:\s*"([^"]+)"/.exec(seg)?.[1];
118395
+ const exempt = /"IsExemptible"\s*:\s*(true|false)/i.exec(seg)?.[1];
118396
+ out.push({
118397
+ index: Number(m[1]),
118398
+ errorType,
118399
+ message,
118400
+ trigger,
118401
+ field: `${m[2]}_operation.${m[3]}`,
118402
+ cascade: /resource was not found/i.test(message) && /"int64Value"\s*:\s*"-\d+"/.test(trigger),
118403
+ ...policyName ? { policyName } : {},
118404
+ ...exempt ? { isExemptible: exempt.toLowerCase() === "true" } : {}
118405
+ });
118406
+ }
118407
+ return out;
118408
+ }
118409
+ function batchRecordErrorText(record2) {
118410
+ const reason = typeof record2["reason"] === "string" ? record2["reason"] : "";
118411
+ const errors = record2["errors"];
118412
+ const errText = typeof errors === "string" ? errors : errors ? JSON.stringify(errors) : "";
118413
+ return [reason, errText].filter(Boolean).join("\n");
118414
+ }
118415
+ function mapBatchOperationErrors(record2, cfg) {
118416
+ const parsed = parseBatchOperationErrors(batchRecordErrorText(record2));
118417
+ if (!cfg || parsed.length === 0) return parsed;
118418
+ const slots = buildSubmittedOperationSlots(cfg);
118419
+ return parsed.map((e) => {
118420
+ const slot = slots[e.index];
118421
+ if (!slot) return { ...e, slotMismatch: true };
118422
+ const kind = e.field.replace(/_operation\..*$/, "");
118423
+ return kind === slot.kind ? { ...e, slot } : { ...e, slot, slotMismatch: true };
118424
+ });
118425
+ }
118426
+ function formatMappedBatchErrors(errors, limit = 12) {
118427
+ if (errors.length === 0) return "";
118428
+ const roots = errors.filter((e) => !e.cascade);
118429
+ const cascades = errors.length - roots.length;
118430
+ const lines = roots.slice(0, limit).map((e) => {
118431
+ const where = e.slot && !e.slotMismatch ? `${e.slot.label} \u2192 ${e.slot.path}` : `\u64CD\u4F5C ${e.field}\uFF08\u6620\u5C04\u4E0D\u53EF\u4FE1\uFF0C\u6309 reason \u539F\u6587\uFF09`;
118432
+ const policy = e.policyName ? ` [\u653F\u7B56 ${e.policyName}${e.isExemptible === void 0 ? "" : e.isExemptible ? "\uFF0C\u53EF\u7533\u8BF7\u8C41\u514D" : "\uFF0C\u4E0D\u53EF\u8C41\u514D"}]` : "";
118433
+ return `[${e.index}] ${e.errorType}: ${e.message}${policy} \u2190 ${where}`;
118434
+ });
118435
+ if (roots.length > limit) lines.push(`\u2026\u53E6\u6709 ${roots.length - limit} \u6761\u6839\u56E0\u89C1 failedOperations[]`);
118436
+ if (cascades > 0) {
118437
+ lines.push(
118438
+ `\u53E6\u6709 ${cascades} \u6761\u4E3A\u7236\u8D44\u6E90\u672A\u5EFA\u6210\u5BFC\u81F4\u7684\u7EA7\u8054\u5931\u8D25\uFF08Resource was not found\uFF09\uFF0C\u4FEE\u597D\u4E0A\u9762\u7684\u6839\u56E0\u5373\u6D88\u5931\uFF0C\u52FF\u9010\u6761\u5904\u7406`
118439
+ );
118440
+ }
118441
+ return ` \u5931\u8D25\u9879\u5B9A\u4F4D\uFF08\u53EA\u6539\u8FD9\u4E9B\u9879\uFF0C\u7981\u6B62\u6574\u7C7B\u5220\u9664\u65B9\u6848\u5185\u5BB9\uFF09\uFF1A${lines.join("\uFF1B")}\u3002`;
118442
+ }
118443
+
118444
+ // src/commands/ad/campaign-batch-diff.ts
118445
+ function asRecord4(v) {
118446
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
118447
+ }
117816
118448
  function pickString2(...vals) {
117817
118449
  for (const v of vals) {
117818
118450
  if (typeof v === "string" && v.trim()) return v.trim();
@@ -117963,18 +118595,19 @@ function buildGeoRemediateCommandLine(opts) {
117963
118595
  `-a ${opts.accountId}`,
117964
118596
  `--campaign-id ${opts.campaignId}`,
117965
118597
  `--location-id ${opts.locationId}`,
117966
- `--commit "batch-diff remediate geo"`
118598
+ ...opts.exclude ? ["--exclude"] : [],
118599
+ `--commit "batch-diff remediate ${opts.exclude ? "geo exclude" : "geo"}"`
117967
118600
  ].join(" ");
117968
118601
  }
117969
118602
  function formatExtensionPlanned(ext) {
117970
118603
  if (!ext) return "\u2014";
117971
118604
  const type = pickString2(ext["typeV2"], ext["AssetFieldType"], ext["type"]);
117972
- const props = asRecord3(ext["Properties"]);
118605
+ const props = asRecord4(ext["Properties"]);
117973
118606
  const phone = props ? pickString2(props["PhoneNumber"], props["phoneNumber"]) : "";
117974
118607
  const code = props ? pickString2(props["ContryCode"], props["CountryCode"]) : "";
117975
118608
  const linkText = props ? pickString2(props["Text"], props["LinkText"]) : "";
117976
118609
  const callout = props ? pickString2(props["Text"], props["CalloutText"]) : "";
117977
- const snippet = asRecord3(ext["StructuredSnippetHeaderValue"]);
118610
+ const snippet = asRecord4(ext["StructuredSnippetHeaderValue"]);
117978
118611
  const snippetKey = pickString2(snippet?.["Key"], props?.["StructuredSnippetHeaderValue"]);
117979
118612
  const parts = [
117980
118613
  type ? `\u7C7B\u578B: ${type}` : "",
@@ -117993,13 +118626,13 @@ function listPlannedKeywords(campaign) {
117993
118626
  if (!Array.isArray(groups)) return [];
117994
118627
  const out = [];
117995
118628
  for (let gi = 0; gi < groups.length; gi++) {
117996
- const g = asRecord3(groups[gi]);
118629
+ const g = asRecord4(groups[gi]);
117997
118630
  if (!g) continue;
117998
118631
  const groupName = pickString2(g["Name"], g["name"]) || `AdGroupsForBatchJob[${gi}]`;
117999
118632
  const blocks = g["KeywordsForBatchJob"];
118000
118633
  if (!Array.isArray(blocks)) continue;
118001
118634
  for (let bi = 0; bi < blocks.length; bi++) {
118002
- const block = asRecord3(blocks[bi]);
118635
+ const block = asRecord4(blocks[bi]);
118003
118636
  if (!block) continue;
118004
118637
  const matchTypeV2 = pickString2(block["MatchTypeV2"], block["matchTypeV2"]) || "BROAD";
118005
118638
  const texts = block["KeywordText"];
@@ -118023,7 +118656,7 @@ function listPlannedNegativeKeywords(campaign) {
118023
118656
  if (!Array.isArray(blocks)) return [];
118024
118657
  const out = [];
118025
118658
  for (let bi = 0; bi < blocks.length; bi++) {
118026
- const block = asRecord3(blocks[bi]);
118659
+ const block = asRecord4(blocks[bi]);
118027
118660
  if (!block) continue;
118028
118661
  const matchTypeV2 = pickString2(block["MatchTypeV2"], block["matchTypeV2"]) || "BROAD";
118029
118662
  const texts = block["KeywordText"];
@@ -118063,7 +118696,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118063
118696
  const plannedGroupCount = Array.isArray(groups) ? groups.length : 0;
118064
118697
  if (Array.isArray(groups)) {
118065
118698
  for (let gi = 0; gi < groups.length; gi++) {
118066
- const g = asRecord3(groups[gi]);
118699
+ const g = asRecord4(groups[gi]);
118067
118700
  if (!g) continue;
118068
118701
  const groupName = pickString2(g["Name"], g["name"]) || `AdGroupsForBatchJob[${gi}]`;
118069
118702
  const groupPath = `campaign.AdGroupsForBatchJob[${gi}]`;
@@ -118115,7 +118748,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118115
118748
  const blocks = g["KeywordsForBatchJob"];
118116
118749
  if (Array.isArray(blocks)) {
118117
118750
  for (let bi = 0; bi < blocks.length; bi++) {
118118
- const block = asRecord3(blocks[bi]);
118751
+ const block = asRecord4(blocks[bi]);
118119
118752
  if (!block) continue;
118120
118753
  const matchTypeV2 = pickString2(block["MatchTypeV2"], block["matchTypeV2"]) || "BROAD";
118121
118754
  const texts = block["KeywordText"];
@@ -118169,7 +118802,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118169
118802
  const ads = g["AdsForBatchJob"];
118170
118803
  if (Array.isArray(ads)) {
118171
118804
  for (let ai = 0; ai < ads.length; ai++) {
118172
- const ad = asRecord3(ads[ai]);
118805
+ const ad = asRecord4(ads[ai]);
118173
118806
  if (!ad) continue;
118174
118807
  const path55 = `${groupPath}.AdsForBatchJob[${ai}]`;
118175
118808
  const primary = pickString2(ad["headlinePart1"], ad["AdTitle"]);
@@ -118303,7 +118936,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118303
118936
  ).length;
118304
118937
  if (Array.isArray(extBlocks)) {
118305
118938
  for (let ei = 0; ei < extBlocks.length; ei++) {
118306
- const ext = asRecord3(extBlocks[ei]);
118939
+ const ext = asRecord4(extBlocks[ei]);
118307
118940
  const plannedContent = formatExtensionPlanned(ext);
118308
118941
  const path55 = `campaign.ExtensionsForBatchJob[${ei}]`;
118309
118942
  if (campaignMissing) {
@@ -118342,7 +118975,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118342
118975
  if (Array.isArray(plannedLocs)) {
118343
118976
  plannedLocCount = plannedLocs.length;
118344
118977
  for (let li = 0; li < plannedLocs.length; li++) {
118345
- const loc = asRecord3(plannedLocs[li]);
118978
+ const loc = asRecord4(plannedLocs[li]);
118346
118979
  if (!loc) continue;
118347
118980
  const id = pickString2(loc["id"], loc["Id"]);
118348
118981
  if (!id) continue;
@@ -118373,6 +119006,42 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118373
119006
  });
118374
119007
  }
118375
119008
  }
119009
+ const plannedExcl = campaign["excludedLocations"] ?? campaign["ExcludedLocations"];
119010
+ const liveExclIds = new Set(
119011
+ (live.excludedLocations ?? []).filter((loc) => belongsToCampaign(loc, campaignId, campaignName)).map((loc) => liveLocationId(loc)).filter((id) => id.length > 0)
119012
+ );
119013
+ let plannedExclCount = 0;
119014
+ if (Array.isArray(plannedExcl)) {
119015
+ plannedExclCount = plannedExcl.length;
119016
+ for (let li = 0; li < plannedExcl.length; li++) {
119017
+ const loc = asRecord4(plannedExcl[li]);
119018
+ const id = loc ? pickString2(loc["id"], loc["Id"]) : "";
119019
+ if (!id) continue;
119020
+ const path55 = `campaign.excludedLocations[${li}]`;
119021
+ const plannedContent = `\u6392\u9664 locationId: ${id}`;
119022
+ if (campaignMissing) {
119023
+ pushItem(items3, {
119024
+ layer: "excluded_location",
119025
+ path: path55,
119026
+ plannedContent,
119027
+ status: "skipped",
119028
+ liveNote: "\u7CFB\u5217\u672A\u627E\u5230\uFF0C\u8DF3\u8FC7\u6392\u9664\u5730\u57DF\u6BD4\u5BF9",
119029
+ summary: `\u6392\u9664\u5730\u57DF\u672A\u6BD4\u5BF9\uFF08\u7CFB\u5217\u7F3A\u5931\uFF09\uFF1A${id}`
119030
+ });
119031
+ continue;
119032
+ }
119033
+ const found = liveExclIds.has(id);
119034
+ pushItem(items3, {
119035
+ layer: "excluded_location",
119036
+ path: path55,
119037
+ plannedContent,
119038
+ status: found ? "ok" : "missing",
119039
+ liveNote: `\u7CFB\u5217\u5DF2\u6392\u9664 ${liveExclIds.size}/${plannedExclCount} \u4E2A\u5730\u57DF`,
119040
+ summary: found ? `\u6392\u9664\u5730\u57DF\u5DF2\u751F\u6548\uFF1Aid=${id}` : `\u6392\u9664\u5730\u57DF\u672A\u751F\u6548\uFF1Aid=${id}`,
119041
+ remediateCommand: !found && accountId && campaignId ? buildGeoRemediateCommandLine({ accountId, campaignId, locationId: id, exclude: true }) : void 0
119042
+ });
119043
+ }
119044
+ }
118376
119045
  const plannedKeywords = listPlannedKeywords(campaign);
118377
119046
  const liveKwCount = live.keywords.filter(
118378
119047
  (k) => belongsToCampaign(k, campaignId, campaignName)
@@ -118392,6 +119061,13 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118392
119061
  } else {
118393
119062
  agentHint = `\u4E0E JSON \u8BA1\u5212\u4E00\u81F4\uFF08\u542B\u6295\u653E\u5730\u57DF\uFF1Bitems[] \u5171 ${statusCounts.ok} \u6761\u5747\u4E3A ok\uFF09\u3002**\u7ACB\u523B**\u628A\u672C\u547D\u4EE4 stdout \u4E2D BEGIN_USER_DELIVERY_MARKDOWN\u2026END \u5168\u6587\u539F\u6837\u53D1\u7ED9\u7528\u6237\uFF1B\u7981\u6B62\u53EA\u8BF4\u300C\u672A\u53D1\u73B0\u7F3A\u5931\u300D\u6216\u53EA\u8D34 counts \u6458\u8981\u3002`;
118394
119063
  }
119064
+ const emptyInPlan = [
119065
+ plannedExclCount === 0 ? "excludedLocations" : "",
119066
+ listPlannedNegativeKeywords(campaign).length === 0 ? "NegativeKeywordsForBatchJob" : ""
119067
+ ].filter(Boolean);
119068
+ if (emptyInPlan.length > 0) {
119069
+ agentHint += ` \u6CE8\u610F\uFF1A\u672C\u6B21\u6BD4\u5BF9\u7684\u8BA1\u5212 JSON \u4E2D ${emptyInPlan.join(" / ")} \u4E3A\u7A7A\u2014\u2014diff \u53EA\u80FD\u5BF9\u7167\u8FD9\u4EFD JSON\u3002\u82E5\u7528\u6237\u539F\u59CB\u65B9\u6848\u6709\u6392\u9664\u5730\u57DF/\u5426\u8BCD\u800C\u521B\u5EFA\u8FC7\u7A0B\u4E2D\u88AB\u5220\uFF0C\u5FC5\u987B\u5728\u4EA4\u4ED8\u65F6\u5982\u5B9E\u8BF4\u660E\u5E76\u8BE2\u95EE\u662F\u5426\u8865\u5EFA\uFF0C\u7981\u6B62\u58F0\u79F0\u300C\u5DF2\u6309\u65B9\u6848\u6392\u9664\u300D\u3002`;
119070
+ }
118395
119071
  return {
118396
119072
  accountId,
118397
119073
  campaignId,
@@ -118411,7 +119087,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118411
119087
  plannedKeywords: plannedKeywords.length,
118412
119088
  liveKeywords: liveKwCount,
118413
119089
  plannedAds: Array.isArray(groups) ? groups.reduce((n, g) => {
118414
- const gr = asRecord3(g);
119090
+ const gr = asRecord4(g);
118415
119091
  const ads = gr?.["AdsForBatchJob"];
118416
119092
  return n + (Array.isArray(ads) ? ads.length : 0);
118417
119093
  }, 0) : 0,
@@ -118421,7 +119097,9 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
118421
119097
  plannedExtensions: plannedExt,
118422
119098
  liveExtensions: liveExt,
118423
119099
  plannedLocations: plannedLocCount,
118424
- liveLocations: liveLocIds.size
119100
+ liveLocations: liveLocIds.size,
119101
+ plannedExcludedLocations: plannedExclCount,
119102
+ liveExcludedLocations: liveExclIds.size
118425
119103
  }
118426
119104
  };
118427
119105
  }
@@ -118440,7 +119118,16 @@ async function fetchLiveSnapshotForCampaign(config, accountId, campaignId, campa
118440
119118
  params.set("endDate", toGoogleDate(void 0, 0));
118441
119119
  params.set("newest", "true");
118442
119120
  const qs = params.toString();
118443
- const [campaigns, adGroups, keywords, negativeKeywords, ads, extensions, targetedLocations] = await Promise.all([
119121
+ const [
119122
+ campaigns,
119123
+ adGroups,
119124
+ keywords,
119125
+ negativeKeywords,
119126
+ ads,
119127
+ extensions,
119128
+ targetedLocations,
119129
+ excludedLocations
119130
+ ] = await Promise.all([
118444
119131
  fetchList(
118445
119132
  config,
118446
119133
  `${googleApiUrl}/campaignmanagement/v2/list/${accountId}?${qs}`,
@@ -118475,6 +119162,11 @@ async function fetchLiveSnapshotForCampaign(config, accountId, campaignId, campa
118475
119162
  config,
118476
119163
  `${googleApiUrl}/campaignmanagement/v2/targetedlocations/${accountId}?${qs}`,
118477
119164
  verbose
119165
+ ),
119166
+ fetchList(
119167
+ config,
119168
+ `${googleApiUrl}/campaignmanagement/v2/excludedlocations/${accountId}?${qs}`,
119169
+ verbose
118478
119170
  )
118479
119171
  ]);
118480
119172
  const campaignFound = campaigns.some(
@@ -118492,11 +119184,14 @@ async function fetchLiveSnapshotForCampaign(config, accountId, campaignId, campa
118492
119184
  extensions: extensions.filter((e) => belongsToCampaign(e, campaignId, campaignName)),
118493
119185
  targetedLocations: targetedLocations.filter(
118494
119186
  (loc) => belongsToCampaign(loc, campaignId, campaignName)
119187
+ ),
119188
+ excludedLocations: excludedLocations.filter(
119189
+ (loc) => belongsToCampaign(loc, campaignId, campaignName)
118495
119190
  )
118496
119191
  };
118497
119192
  }
118498
119193
  function resolveCampaignIdFromBatch(record2) {
118499
- const campaign = asRecord3(record2["campaign"]);
119194
+ const campaign = asRecord4(record2["campaign"]);
118500
119195
  const direct = pickString2(
118501
119196
  campaign?.["Id"],
118502
119197
  campaign?.["id"],
@@ -118507,7 +119202,7 @@ function resolveCampaignIdFromBatch(record2) {
118507
119202
  const groups = campaign?.["AdGroupsForBatchJob"];
118508
119203
  if (Array.isArray(groups)) {
118509
119204
  for (const g of groups) {
118510
- const gr = asRecord3(g);
119205
+ const gr = asRecord4(g);
118511
119206
  const cid = pickString2(gr?.["CampaignId"], gr?.["campaignId"]);
118512
119207
  if (cid) return cid;
118513
119208
  }
@@ -118515,7 +119210,7 @@ function resolveCampaignIdFromBatch(record2) {
118515
119210
  return "";
118516
119211
  }
118517
119212
  function resolveCampaignNameFromBatch(record2) {
118518
- const campaign = asRecord3(record2["campaign"]);
119213
+ const campaign = asRecord4(record2["campaign"]);
118519
119214
  return pickString2(
118520
119215
  record2["campaignName"],
118521
119216
  record2["CampaignName"],
@@ -118538,7 +119233,23 @@ function hintBatchFailureRemediation(record2) {
118538
119233
  );
118539
119234
  }
118540
119235
  if (/name is already assigned|already assigned to another/.test(blob)) {
118541
- tips.push("\u6539 campaign.Name\uFF08\u53CA\u5916\u5C42 name\uFF09\u4E3A\u8D26\u6237\u5185\u672A\u5360\u7528\u540D\u79F0\u540E\u91CD\u63D0");
119236
+ tips.push(
119237
+ "\u6539 campaign.Name\uFF08\u53CA\u5916\u5C42 name\uFF09\u4E3A\u8D26\u6237\u5185\u672A\u5360\u7528\u540D\u79F0\u540E\u91CD\u63D0\uFF1B\u7981\u6B62\u5220\u9664\u5360\u7528\u8BE5\u540D\u79F0\u7684\u5DF2\u6709\u7CFB\u5217"
119238
+ );
119239
+ }
119240
+ const destination = /destination_not_working|destination_not_found|destination_mismatch/.test(
119241
+ blob
119242
+ );
119243
+ if (destination) {
119244
+ tips.push(
119245
+ "\u843D\u5730\u9875\u4E0D\u53EF\u8BBF\u95EE\uFF08DESTINATION_*\uFF09\uFF1A\u5411\u7528\u6237\u8BF4\u660E\u5E76\u7D22\u53D6\u53EF\u6B63\u5E38\u6253\u5F00\u7684\u843D\u5730\u9875 URL\uFF0C\u6539\u5BF9\u5E94\u5E7F\u544A\u7684 Finalurl/DestinationUrl\uFF1B\u7CFB\u5217\u5DF2\u5EFA\u6210\u65F6\u7528 ad ad-create \u53EA\u8865\u8BE5\u5E7F\u544A\uFF0C\u52FF\u91CD\u63D0\u6574\u4E2A\u7CFB\u5217"
119246
+ );
119247
+ }
119248
+ if (/policyviolation/.test(blob) || /policy/.test(blob) && !destination) {
119249
+ const exemptible = /"isexemptible"\s*:\s*true/.test(blob);
119250
+ tips.push(
119251
+ "\u89E6\u53D1 Google \u653F\u7B56\uFF1A\u505C\u4E0B\u5411\u7528\u6237\u62A5\u544A\u89E6\u53D1\u7684\u5173\u952E\u8BCD/\u6587\u6848\uFF08\u89C1\u5931\u8D25\u9879\u5B9A\u4F4D\uFF09" + (exemptible ? "\uFF0C\u4E14\u8BE5\u653F\u7B56 IsExemptible=true\uFF08\u53EF\u7533\u8BF7\u8C41\u514D\uFF09" : "") + "\uFF1B\u7ED9\u51FA\u53EF\u9009\u65B9\u6848\uFF08\u53BB\u6389\u8FD9\u4E9B\u8BCD / \u6539\u5199\u8BCD\u9762\u6216\u6587\u6848 / \u7533\u8BF7\u653F\u7B56\u8C41\u514D / \u7531\u7528\u6237\u6307\u5B9A\u7F29\u51CF\u5730\u57DF\uFF09\u7B49\u7528\u6237\u9009\u62E9\u3002LEGAL_REQUIREMENTS \u7B49\u5730\u57DF\u76F8\u5173\u653F\u7B56\u62A5\u9519\u4E0D\u6307\u660E\u5177\u4F53\u56FD\u5BB6\uFF1A\u7981\u6B62\u81EA\u884C\u521B\u5EFA\u6D4B\u8BD5\u7CFB\u5217\u9010\u5730\u57DF\u4E8C\u5206\u6392\u67E5"
119252
+ );
118542
119253
  }
118543
119254
  return tips.length > 0 ? ` \u4FEE\u590D\u63D0\u793A\uFF1A${tips.join("\uFF1B")}\u3002` : "";
118544
119255
  }
@@ -118546,16 +119257,25 @@ function buildBatchGetAgentWorkflow(opts) {
118546
119257
  const status = pickString2(opts.record["status"]);
118547
119258
  const campaignId = resolveCampaignIdFromBatch(opts.record) || null;
118548
119259
  const campaignName = resolveCampaignNameFromBatch(opts.record) || null;
119260
+ const cfg = opts.config !== void 0 ? opts.config : opts.configFile ? tryLoadCampaignCreateConfig(opts.configFile) : null;
119261
+ const failedOperations = status === "Failed" || status === "HasFailed" ? mapBatchOperationErrors(opts.record, cfg) : [];
119262
+ const located = formatMappedBatchErrors(failedOperations) + (failedOperations.length > 0 && !cfg ? " \u672A\u63D0\u4F9B --config-file\uFF0C\u65E0\u6CD5\u628A mutate_operations[N] \u6620\u5C04\u5230 JSON \u9879\uFF1B\u8BF7\u5E26\u63D0\u4EA4\u65F6\u7684 JSON \u91CD\u8DD1 batch get\u3002" : "");
118549
119263
  const terminalNoCampaign = (status === "Failed" || status === "HasFailed") && !campaignId;
119264
+ const shellCreated = status === "HasFailed" && failedOperations.length > 0 && !failedOperations.some((e) => e.index <= 1);
118550
119265
  const runDiff = !terminalNoCampaign && shouldRunBatchDiff(status);
118551
119266
  let nextCommand = null;
118552
119267
  let agentHint;
118553
119268
  if (status === "Creating") {
118554
119269
  agentHint = "\u4EFB\u52A1\u4ECD\u5728 Creating\uFF1A\u6BCF 5s \u8F6E\u8BE2 ad batch get\uFF08\u987B\u5E26\u540C\u4E00 --config-file\uFF09\uFF0C\u52FF\u6267\u884C batch diff\u3002";
118555
119270
  nextCommand = opts.configFile ? `siluzan-tso ad batch get --id ${opts.batchId} --config-file ${shellArgPath(opts.configFile)} --json-out ./snap-campaign` : `siluzan-tso ad batch get --id ${opts.batchId} --config-file <campaign.json> --json-out ./snap-campaign`;
119271
+ } else if (terminalNoCampaign && shellCreated) {
119272
+ const account = pickString2(cfg?.account, opts.record["customerId"]) || "<accountId>";
119273
+ const name2 = campaignName ?? "<\u7CFB\u5217\u540D>";
119274
+ agentHint = `HasFailed \u4E14\u8BB0\u5F55\u91CC\u65E0 campaignId\uFF0C\u4F46\u9884\u7B97/\u7CFB\u5217\u64CD\u4F5C\u6CA1\u6709\u62A5\u9519\uFF1A\u7CFB\u5217\u300C${name2}\u300D**\u5DF2\u5728\u8D26\u6237\u4E2D\u521B\u5EFA**\uFF0C\u53EA\u6709\u90E8\u5206\u5B50\u9879\u5931\u8D25\u3002\u5148\u6267\u884C nextCommand \u6309\u540D\u79F0\u627E\u5230 campaignId\uFF0C\u518D ad batch diff --campaign-id <id> \u5E76\u628A\u62A5\u544A\u4EA4\u4ED8\u7528\u6237\uFF1B\u4E4B\u540E\u53EA\u8865\u5EFA\u5931\u8D25\u9879\uFF0C**\u7981\u6B62**\u91CD\u63D0\u6574\u4E2A\u7CFB\u5217\uFF08\u4F1A\u540D\u79F0\u51B2\u7A81\uFF09\u6216\u5220\u9664\u8BE5\u7CFB\u5217\u3002` + located + hintBatchFailureRemediation(opts.record);
119275
+ nextCommand = `siluzan-tso ad campaigns -a ${account} --fresh --json-out ./snap-campaign`;
118556
119276
  } else if (terminalNoCampaign) {
118557
119277
  const fix = hintBatchFailureRemediation(opts.record);
118558
- agentHint = `${status} \u4E14\u65E0 campaignId\uFF1A\u7CFB\u5217\u672A\u521B\u5EFA\u6210\u529F\u3002\u8BFB reason/errors\uFF0C\u6539 JSON \u540E\u91CD\u63D0 campaign-create\uFF1B\u4E0D\u8981\u8DD1 batch diff\u3002` + fix;
119278
+ agentHint = `${status} \u4E14\u65E0 campaignId\uFF1A\u7CFB\u5217\u672A\u521B\u5EFA\u6210\u529F\u3002\u8BFB reason/errors\uFF0C\u6539 JSON \u540E\u91CD\u63D0 campaign-create\uFF1B\u4E0D\u8981\u8DD1 batch diff\u3002` + (status === "HasFailed" ? "\u8D26\u6237\u91CC\u4ECD\u53EF\u80FD\u7559\u4E0B\u534A\u6210\u54C1\u7CFB\u5217\uFF1A\u5148 ad campaigns --fresh \u6838\u5BF9\u5E76\u544A\u77E5\u7528\u6237\uFF0C\u5220\u9664\u4E0E\u5426\u7531\u7528\u6237\u51B3\u5B9A\uFF08campaign-delete \u987B\u7528\u6237\u540C\u610F\u540E --i-confirm\uFF09\u3002" : "") + located + fix;
118559
119279
  nextCommand = null;
118560
119280
  } else if (runDiff) {
118561
119281
  if (!opts.configFile) {
@@ -118569,6 +119289,8 @@ function buildBatchGetAgentWorkflow(opts) {
118569
119289
  });
118570
119290
  agentHint = `\u5FC5\u505A\u4E0B\u4E00\u6B65\uFF1A\u6267\u884C nextCommand\uFF08ad batch diff\uFF09\u3002diff \u7684 stdout \u542B BEGIN_USER_DELIVERY_MARKDOWN\u2026END\u2014\u2014**\u7ACB\u523B\u539F\u6837\u53D1\u7ED9\u7528\u6237**\uFF08\u52FF\u6458\u8981\u3001\u52FF\u7B49\u8865\u5EFA\u7ED3\u675F\uFF09\uFF1B\u6709 remediateCommand \u5219\u4EA4\u4ED8\u540E\u518D\u8865\u5EFA\u5E76\u518D\u8DD1 diff\u3002`;
118571
119291
  }
119292
+ agentHint += located;
119293
+ if (status === "HasFailed") agentHint += hintBatchFailureRemediation(opts.record);
118572
119294
  } else {
118573
119295
  agentHint = `\u5F53\u524D status=${status || "\u2014"}\uFF0C\u6309 google-ads.md \xA7 batch \u5904\u7406\u3002`;
118574
119296
  }
@@ -118580,7 +119302,8 @@ function buildBatchGetAgentWorkflow(opts) {
118580
119302
  campaignName,
118581
119303
  configFile: opts.configFile ?? null,
118582
119304
  nextCommand,
118583
- agentHint
119305
+ agentHint,
119306
+ failedOperations
118584
119307
  };
118585
119308
  }
118586
119309
  function shellArgPath(p) {
@@ -118650,6 +119373,7 @@ function printBatchDiffFollowUpHint(opts) {
118650
119373
  var LAYER_ORDER = [
118651
119374
  "campaign",
118652
119375
  "location",
119376
+ "excluded_location",
118653
119377
  "adgroup",
118654
119378
  "keyword",
118655
119379
  "ad",
@@ -118659,6 +119383,7 @@ var LAYER_ORDER = [
118659
119383
  var LAYER_TITLE = {
118660
119384
  campaign: "\u7CFB\u5217",
118661
119385
  location: "\u6295\u653E\u56FD\u5BB6/\u5730\u57DF",
119386
+ excluded_location: "\u6392\u9664\u5730\u57DF",
118662
119387
  adgroup: "\u5E7F\u544A\u7EC4",
118663
119388
  keyword: "\u5173\u952E\u8BCD",
118664
119389
  ad: "RSA\u6587\u6848",
@@ -118740,10 +119465,21 @@ function buildCampaignCreateStatusMarkdown(result) {
118740
119465
  `| \u5426\u5B9A\u8BCD | ${c.liveNegativeKeywords} | ${c.plannedNegativeKeywords} |`,
118741
119466
  `| \u9644\u52A0\u4FE1\u606F | ${c.liveExtensions} | ${c.plannedExtensions} |`,
118742
119467
  `| \u6295\u653E\u5730\u57DF | ${c.liveLocations} | ${c.plannedLocations} |`,
119468
+ `| \u6392\u9664\u5730\u57DF | ${c.liveExcludedLocations} | ${c.plannedExcludedLocations} |`,
118743
119469
  ``,
118744
119470
  `**\u9010\u9879\u72B6\u6001\u8BA1\u6570**\uFF1A\u2705 ${sc.ok}\u3000\u274C ${sc.missing}\u3000\u23ED ${sc.skipped}\u3000\u5408\u8BA1 ${result.items.length}`,
118745
119471
  ``
118746
119472
  ];
119473
+ const emptyInPlan = [
119474
+ c.plannedExcludedLocations === 0 ? "\u6392\u9664\u5730\u57DF" : "",
119475
+ c.plannedNegativeKeywords === 0 ? "\u5426\u5B9A\u8BCD" : ""
119476
+ ].filter(Boolean);
119477
+ if (emptyInPlan.length > 0) {
119478
+ lines.push(
119479
+ `> \u26A0\uFE0F \u672C\u6B21\u63D0\u4EA4\u7684\u8BA1\u5212 JSON \u4E2D **${emptyInPlan.join("\u3001")}\u4E3A 0 \u6761**\uFF0C\u8D26\u6237\u5185\u4E5F\u5C31\u6CA1\u6709\u8BBE\u7F6E\u3002\u82E5\u6295\u653E\u65B9\u6848\u539F\u672C\u6709\u8FD9\u4E9B\u5185\u5BB9\uFF0C\u8BF4\u660E\u521B\u5EFA\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF0C\u8BF7\u4E0E\u52A9\u624B\u6838\u5BF9\u662F\u5426\u9700\u8981\u8865\u4E0A\u3002`,
119480
+ ``
119481
+ );
119482
+ }
118747
119483
  const planItems = result.items.length > 0 ? result.items : result.missing.map((m) => ({ ...m, status: "missing" }));
118748
119484
  for (const layer of LAYER_ORDER) {
118749
119485
  const layerItems = planItems.filter((i) => i.layer === layer);
@@ -119136,6 +119872,22 @@ async function runAiCreationList(opts) {
119136
119872
  }
119137
119873
  console.log();
119138
119874
  }
119875
+ async function lookupCampaignIdByName(config, account, name2, verbose) {
119876
+ if (!account || !name2 || !config.googleApiUrl) return "";
119877
+ try {
119878
+ const url = campaignListUrl(config.googleApiUrl, account, void 0, void 0, true);
119879
+ const res = await apiFetch2(
119880
+ url,
119881
+ config,
119882
+ {},
119883
+ verbose
119884
+ );
119885
+ const hits = (res.data ?? []).filter((c) => String(c.name ?? "").trim() === name2.trim());
119886
+ return hits.length === 1 ? String(hits[0].id ?? "") : "";
119887
+ } catch {
119888
+ return "";
119889
+ }
119890
+ }
119139
119891
  async function runAiCreationGet(opts) {
119140
119892
  const config = loadConfig(opts.token);
119141
119893
  const url = `${config.apiBaseUrl}/query/campaign-creation-record/campaign-batch-asyncs/${opts.id}`;
@@ -119148,11 +119900,28 @@ async function runAiCreationGet(opts) {
119148
119900
  `);
119149
119901
  process.exit(1);
119150
119902
  }
119151
- const agentWorkflow = buildBatchGetAgentWorkflow({
119903
+ let agentWorkflow = buildBatchGetAgentWorkflow({
119152
119904
  batchId: opts.id,
119153
119905
  record: data,
119154
119906
  configFile: opts.configFile
119155
119907
  });
119908
+ const shellCreatedNoId = agentWorkflow["status"] === "HasFailed" && !agentWorkflow["campaignId"] && String(agentWorkflow["nextCommand"] ?? "").includes("ad campaigns");
119909
+ if (shellCreatedNoId) {
119910
+ const found = await lookupCampaignIdByName(
119911
+ config,
119912
+ String(data["customerId"] ?? ""),
119913
+ resolveCampaignNameFromBatch(data),
119914
+ opts.verbose
119915
+ );
119916
+ if (found) {
119917
+ data = { ...data, campaignId: found, campaignIdSource: "lookup-by-name" };
119918
+ agentWorkflow = buildBatchGetAgentWorkflow({
119919
+ batchId: opts.id,
119920
+ record: data,
119921
+ configFile: opts.configFile
119922
+ });
119923
+ }
119924
+ }
119156
119925
  const payload = { ...data, agentWorkflow };
119157
119926
  if (await emitCliJsonOrSnapshot(opts, {
119158
119927
  section: `ad-batch-get-${opts.id}`,
@@ -119238,6 +120007,23 @@ ${reason}
119238
120007
  console.log(JSON.stringify(errors, null, 2));
119239
120008
  console.log();
119240
120009
  }
120010
+ const failedOps = agentWorkflow["failedOperations"];
120011
+ if (failedOps.length > 0) {
120012
+ const roots = failedOps.filter((e) => !e.cascade);
120013
+ console.log(
120014
+ `
120015
+ \u2500\u2500 \u5931\u8D25\u9879\u5B9A\u4F4D\uFF08\u6839\u56E0 ${roots.length} \u6761\uFF0C\u7EA7\u8054 ${failedOps.length - roots.length} \u6761\uFF09\u2500\u2500
120016
+ `
120017
+ );
120018
+ for (const e of roots) {
120019
+ const where = e.slot && !e.slotMismatch ? `${e.slot.label} ${e.slot.path}` : `${e.field}\uFF08\u672A\u80FD\u6620\u5C04\u5230 JSON \u9879\uFF09`;
120020
+ console.log(` [${e.index}] ${e.errorType}: ${e.message}
120021
+ \u2192 ${where}`);
120022
+ }
120023
+ console.log(
120024
+ "\n \u53EA\u4FEE\u6539\u4E0A\u9762\u5217\u51FA\u7684\u9879\uFF1B\u7981\u6B62\u4E3A\u901A\u8FC7\u521B\u5EFA\u6574\u7C7B\u5220\u9664\u65B9\u6848\u5185\u5BB9\uFF08\u5426\u8BCD/\u6392\u9664\u5730\u57DF/\u6295\u653E\u56FD\u5BB6\uFF09\u3002\n"
120025
+ );
120026
+ }
119241
120027
  const st = String(item.status ?? "");
119242
120028
  if (st === "Failed") {
119243
120029
  printBatchFailedFollowUpHint({ batchId: opts.id, configFile: opts.configFile });
@@ -121798,6 +122584,13 @@ async function runAdPmaxEdit(opts) {
121798
122584
  console.error("\n\u274C PATCH body \u4E3A\u7A7A\n");
121799
122585
  process.exit(1);
121800
122586
  }
122587
+ const statusV2 = body["statusV2"] ?? body["StatusV2"];
122588
+ if (statusV2 !== void 0 && parseStatusV2(String(statusV2)) === 4) {
122589
+ ensureIConfirm({
122590
+ iConfirm: opts.iConfirm,
122591
+ actionLabel: `ad pmax-edit --status Removed\uFF08\u79FB\u9664 PMax \u6D3B\u52A8 ${campaignId}\uFF0C\u4E0D\u53EF\u6062\u590D\uFF09`
122592
+ });
122593
+ }
121801
122594
  await withGoogleApi(opts, async (config, googleApiUrl) => {
121802
122595
  const url = pmaxCampaignUrl(googleApiUrl, accountId, campaignId);
121803
122596
  try {
@@ -122794,6 +123587,10 @@ function parseOptionalMatchType(raw) {
122794
123587
  `);
122795
123588
  process.exit(1);
122796
123589
  }
123590
+ function resolveWriteNormalizedPath(raw, configFile) {
123591
+ if (raw === true) return configFile;
123592
+ return typeof raw === "string" && raw.trim() ? raw : void 0;
123593
+ }
122797
123594
  function register21(program2) {
122798
123595
  const adCmd = program2.command("ad").description(
122799
123596
  "Google \u5E7F\u544A\u7BA1\u7406\uFF08Google API \u5730\u5740\u4ECE TSO API \u81EA\u52A8\u63A8\u5BFC\uFF0C\u53EF\u901A\u8FC7 SILUZAN_GOOGLE_API \u73AF\u5883\u53D8\u91CF\u8986\u76D6\uFF09\n \u542B\uFF1A\u7CFB\u5217/\u7EC4/\u521B\u610F/\u5173\u952E\u8BCD\u7B49\u5E38\u89C4\u5E7F\u544A\u6295\u653E\u4E0E\u7BA1\u7406\u80FD\u529B"
@@ -122985,14 +123782,19 @@ function register21(program2) {
122985
123782
  });
122986
123783
  }
122987
123784
  );
122988
- adCmd.command("campaign-delete").description("\u5220\u9664\u5E7F\u544A\u7CFB\u5217\uFF08\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF09").requiredOption("-a, --account <id>", "Google \u8D26\u6237 mediaCustomerId").requiredOption("--id <campaignId>", "\u5E7F\u544A\u7CFB\u5217 ID").option("-t, --token <token>", "Auth Token").option("--verbose", "\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F", false).action(async (opts) => {
122989
- await runAdCampaignDelete({
122990
- token: opts.token,
122991
- account: opts.account,
122992
- id: opts.id,
122993
- verbose: opts.verbose
122994
- });
122995
- });
123785
+ adCmd.command("campaign-delete").description(
123786
+ "\u5220\u9664\u5E7F\u544A\u7CFB\u5217\uFF08\u4E0D\u53EF\u6062\u590D\uFF1B\u7834\u574F\u6027\uFF1A\u987B\u7528\u6237\u660E\u786E\u540C\u610F\u540E\u52A0 --i-confirm + --commit\uFF0C\u542B Agent \u81EA\u5EFA\u7684\u6D4B\u8BD5\u7CFB\u5217\uFF09"
123787
+ ).requiredOption("-a, --account <id>", "Google \u8D26\u6237 mediaCustomerId").requiredOption("--id <campaignId>", "\u5E7F\u544A\u7CFB\u5217 ID").option("--i-confirm", "\u786E\u8BA4\u5DF2\u5411\u7528\u6237\u5217\u51FA\u5F85\u5220\u7CFB\u5217\uFF08ID+\u540D\u79F0\uFF09\u5E76\u83B7\u5F97\u660E\u786E\u540C\u610F", false).option("-t, --token <token>", "Auth Token").option("--verbose", "\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F", false).action(
123788
+ async (opts) => {
123789
+ await runAdCampaignDelete({
123790
+ token: opts.token,
123791
+ account: opts.account,
123792
+ id: opts.id,
123793
+ iConfirm: opts.iConfirm,
123794
+ verbose: opts.verbose
123795
+ });
123796
+ }
123797
+ );
122996
123798
  adCmd.command("adgroup-create").description("\u5728\u5E7F\u544A\u7CFB\u5217\u4E0B\u521B\u5EFA\u641C\u7D22\u5E7F\u544A\u7EC4").requiredOption("-a, --account <id>", "Google \u8D26\u6237 mediaCustomerId").requiredOption("--campaign-id <id>", "\u6240\u5C5E\u5E7F\u544A\u7CFB\u5217 ID").requiredOption("--campaign-name <name>", "\u6240\u5C5E\u5E7F\u544A\u7CFB\u5217\u540D\u79F0").requiredOption("--name <name>", "\u5E7F\u544A\u7EC4\u540D\u79F0").requiredOption(
122997
123799
  "--max-cpc <amount>",
122998
123800
  "\u6700\u9AD8\u5355\u6B21\u70B9\u51FB\u8D39\u7528\uFF0C\u4E3B\u5E01\u79CD\u91D1\u989D\uFF08\u5982 1.5 \u8868\u793A \xA51.50\uFF1BCLI \u5185\u90E8 \xD7100 \u5199\u5165\u300C\u5206\u300D\uFF09",
@@ -123197,12 +123999,15 @@ function register21(program2) {
123197
123999
  }
123198
124000
  );
123199
124001
  adCmd.command("campaign-validate").description(
123200
- "\u6821\u9A8C campaign-create JSON\uFF08\u8BCD\u9762\u89C4\u8303\u5316 + \u540E\u7AEF\u786C\u7EA6\u675F\uFF1B\u4E0D\u8C03\u7528 API\uFF09\n\n \u7528\u6CD5\uFF1A\n siluzan-tso ad campaign-validate --config-file ./campaign.json --json-out ./snap-campaign\n siluzan-tso ad campaign-validate --config-file ./campaign.json --write-normalized ./campaign.normalized.json"
123201
- ).requiredOption("--config-file <path>", "campaign-create JSON \u8DEF\u5F84").option("--write-normalized <path>", "\u5C06\u89C4\u8303\u5316\u540E\u7684 JSON \u5199\u5165\u8BE5\u8DEF\u5F84\uFF08\u5173\u952E\u8BCD\u8BCD\u9762\u5DF2\u4FEE\u6B63\uFF09").option("--json-out <path>", "\u843D\u76D8\u6821\u9A8C\u7ED3\u679C\uFF08\u542B lengthViolations\uFF09\u5E76\u66F4\u65B0 cli-manifest").option("--verbose", "\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F", false).action(
124002
+ "\u6821\u9A8C campaign-create JSON\uFF08\u8BCD\u9762\u89C4\u8303\u5316 + \u540E\u7AEF\u786C\u7EA6\u675F\uFF1B\u4E0D\u8C03\u7528 API\uFF09\n\n \u7528\u6CD5\uFF1A\n siluzan-tso ad campaign-validate --config-file ./campaign.json --json-out ./snap-campaign\n siluzan-tso ad campaign-validate --config-file ./campaign.json --write-normalized # \u539F\u5730\u8986\u76D6\n siluzan-tso ad campaign-validate --config-file ./campaign.json --write-normalized ./campaign.normalized.json"
124003
+ ).requiredOption("--config-file <path>", "campaign-create JSON \u8DEF\u5F84").option(
124004
+ "--write-normalized [path]",
124005
+ "\u5C06\u89C4\u8303\u5316\u540E\u7684 JSON \u5199\u5165\u8BE5\u8DEF\u5F84\uFF08\u5173\u952E\u8BCD\u8BCD\u9762\u5DF2\u4FEE\u6B63\uFF09\uFF1B\u4E0D\u5E26\u8DEF\u5F84\u65F6\u539F\u5730\u8986\u76D6 --config-file"
124006
+ ).option("--json-out <path>", "\u843D\u76D8\u6821\u9A8C\u7ED3\u679C\uFF08\u542B lengthViolations\uFF09\u5E76\u66F4\u65B0 cli-manifest").option("--verbose", "\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F", false).action(
123202
124007
  async (opts) => {
123203
124008
  await runAdCampaignValidate({
123204
124009
  configFile: opts.configFile,
123205
- writeNormalized: opts.writeNormalized,
124010
+ writeNormalized: resolveWriteNormalizedPath(opts.writeNormalized, opts.configFile),
123206
124011
  jsonOut: opts.jsonOut,
123207
124012
  verbose: opts.verbose
123208
124013
  });
@@ -123228,12 +124033,15 @@ function register21(program2) {
123228
124033
  }
123229
124034
  );
123230
124035
  adCmd.command("pmax-validate").description(
123231
- "\u6821\u9A8C pmax-create JSON\uFF08PMax \u4E13\u7528\uFF1B\u4E0D\u8C03\u7528 API\uFF09\n\n \u7528\u6CD5\uFF1A\n siluzan-tso ad pmax-validate --config-file ./pmax.json --json-out ./snap-pmax\n siluzan-tso ad pmax-validate --config-file ./pmax.json --write-normalized ./pmax.normalized.json"
123232
- ).requiredOption("--config-file <path>", "pmax-create JSON \u8DEF\u5F84").option("--write-normalized <path>", "\u5C06 JSON \u5199\u5165\u8BE5\u8DEF\u5F84\uFF08\u4FDD\u7559 _ \u6CE8\u89E3\u952E\uFF09").option("--json-out <path>", "\u843D\u76D8\u6821\u9A8C\u7ED3\u679C\u5E76\u66F4\u65B0 cli-manifest").option("--verbose", "\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F", false).action(
124036
+ "\u6821\u9A8C pmax-create JSON\uFF08PMax \u4E13\u7528\uFF1B\u4E0D\u8C03\u7528 API\uFF09\n\n \u7528\u6CD5\uFF1A\n siluzan-tso ad pmax-validate --config-file ./pmax.json --json-out ./snap-pmax\n siluzan-tso ad pmax-validate --config-file ./pmax.json --write-normalized # \u539F\u5730\u8986\u76D6\n siluzan-tso ad pmax-validate --config-file ./pmax.json --write-normalized ./pmax.normalized.json"
124037
+ ).requiredOption("--config-file <path>", "pmax-create JSON \u8DEF\u5F84").option(
124038
+ "--write-normalized [path]",
124039
+ "\u5C06 JSON \u5199\u5165\u8BE5\u8DEF\u5F84\uFF08\u4FDD\u7559 _ \u6CE8\u89E3\u952E\uFF09\uFF1B\u4E0D\u5E26\u8DEF\u5F84\u65F6\u539F\u5730\u8986\u76D6 --config-file"
124040
+ ).option("--json-out <path>", "\u843D\u76D8\u6821\u9A8C\u7ED3\u679C\u5E76\u66F4\u65B0 cli-manifest").option("--verbose", "\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F", false).action(
123233
124041
  async (opts) => {
123234
124042
  await runAdPmaxValidate({
123235
124043
  configFile: opts.configFile,
123236
- writeNormalized: opts.writeNormalized,
124044
+ writeNormalized: resolveWriteNormalizedPath(opts.writeNormalized, opts.configFile),
123237
124045
  jsonOut: opts.jsonOut,
123238
124046
  verbose: opts.verbose
123239
124047
  });
@@ -123290,7 +124098,10 @@ function register21(program2) {
123290
124098
  addPmaxJsonOptions(
123291
124099
  adCmd.command("pmax-edit").description(
123292
124100
  "\u66F4\u65B0 PMax \u6D3B\u52A8\uFF08PATCH\uFF1B\u52FF\u7528 ad campaign-edit\uFF09\n --patch-file \u89C1 assets/pmax-patch-campaign-template.json"
123293
- ).requiredOption("-a, --account <id>", "Google \u5A92\u4F53\u5BA2\u6237 ID").requiredOption("--campaign-id <id>", "\u6D3B\u52A8 ID").option("--patch-file <path>", "PATCH JSON\uFF08budget/targetCpa \u586B\u5143\uFF09").option("--status <status>", "2|3|4 \u6216 Enabled|Paused|Removed").option("--budget <yuan>", "\u65E5\u9884\u7B97\uFF08\u5143\uFF09\uFF1B\u987B\u914D\u5408 --budget-id").option("--budget-id <id>", "budgetId\uFF08\u6765\u81EA pmax-get\uFF09").option("--bidding <strategy>", "\u51FA\u4EF7\u7B56\u7565\uFF0C\u5982 MAXIMIZE_CONVERSIONS").option("--target-cpa <yuan>", "\u76EE\u6807 CPA\uFF08\u5143\uFF09").option("--target-roas <n>", "\u76EE\u6807 ROAS").option("--url-expansion-opt-out", "\u5173\u95ED\u6700\u7EC8\u5230\u8FBE\u7F51\u5740\u6269\u5C55").option("-t, --token <token>", "Auth Token")
124101
+ ).requiredOption("-a, --account <id>", "Google \u5A92\u4F53\u5BA2\u6237 ID").requiredOption("--campaign-id <id>", "\u6D3B\u52A8 ID").option("--patch-file <path>", "PATCH JSON\uFF08budget/targetCpa \u586B\u5143\uFF09").option(
124102
+ "--status <status>",
124103
+ "2|3|4 \u6216 Enabled|Paused|Removed\uFF08Removed \u4E0D\u53EF\u6062\u590D\uFF0C\u987B\u7528\u6237\u540C\u610F\u540E\u52A0 --i-confirm\uFF09"
124104
+ ).option("--i-confirm", "\u72B6\u6001\u6539 Removed \u65F6\u5FC5\u586B\uFF1A\u5DF2\u83B7\u7528\u6237\u660E\u786E\u540C\u610F", false).option("--budget <yuan>", "\u65E5\u9884\u7B97\uFF08\u5143\uFF09\uFF1B\u987B\u914D\u5408 --budget-id").option("--budget-id <id>", "budgetId\uFF08\u6765\u81EA pmax-get\uFF09").option("--bidding <strategy>", "\u51FA\u4EF7\u7B56\u7565\uFF0C\u5982 MAXIMIZE_CONVERSIONS").option("--target-cpa <yuan>", "\u76EE\u6807 CPA\uFF08\u5143\uFF09").option("--target-roas <n>", "\u76EE\u6807 ROAS").option("--url-expansion-opt-out", "\u5173\u95ED\u6700\u7EC8\u5230\u8FBE\u7F51\u5740\u6269\u5C55").option("-t, --token <token>", "Auth Token")
123294
124105
  ).action(
123295
124106
  async (opts) => {
123296
124107
  await runAdPmaxEdit(opts);
@@ -127583,21 +128394,6 @@ init_media_customer_id();
127583
128394
 
127584
128395
  // src/commands/account-manage/google-mcc.ts
127585
128396
  init_auth();
127586
-
127587
- // src/utils/destructive-confirm.ts
127588
- function ensureIConfirm(opts) {
127589
- if (opts.iConfirm) return;
127590
- console.error(
127591
- `
127592
- \u274C \u62D2\u7EDD\u6267\u884C\uFF1A${opts.actionLabel} \u4E3A\u7834\u574F\u6027\u64CD\u4F5C\uFF0C\u987B\u5148\u5411\u7528\u6237\u8BF4\u660E\u98CE\u9669\u5E76\u83B7\u5F97\u660E\u786E\u786E\u8BA4\u3002
127593
- \u7528\u6237\u540C\u610F\u540E\uFF0C\u8BF7\u9644\u52A0 --i-confirm\uFF0C\u5E76\u4F7F\u7528 --commit "\u2026" \u8BF4\u660E\u539F\u56E0\u540E\u518D\u6267\u884C\u3002
127594
- \u793A\u4F8B\uFF1Asiluzan-tso \u2026 --i-confirm --commit "\u7528\u6237\u786E\u8BA4\u89E3\u7ED1 entityId=\u2026"
127595
- `
127596
- );
127597
- process.exit(1);
127598
- }
127599
-
127600
- // src/commands/account-manage/google-mcc.ts
127601
128397
  init_cli_json_snapshot();
127602
128398
  function parseMccManagerIds(input) {
127603
128399
  const normalized = input.replace(/[,,;、]/g, ";");
@@ -131590,7 +132386,7 @@ function readJsonFile(filePath) {
131590
132386
  }
131591
132387
  });
131592
132388
  }
131593
- function asRecord4(value) {
132389
+ function asRecord5(value) {
131594
132390
  if (value && typeof value === "object" && !Array.isArray(value)) {
131595
132391
  return value;
131596
132392
  }
@@ -131616,10 +132412,10 @@ function injectReportData(html, payload) {
131616
132412
  async function runWebsiteDiagnosisRender(opts) {
131617
132413
  const dataPath = path20.resolve(opts.dataFile);
131618
132414
  const dataRaw = await readJsonFile(dataPath);
131619
- let data = asRecord4(dataRaw);
132415
+ let data = asRecord5(dataRaw);
131620
132416
  if (opts.collectFile) {
131621
132417
  const collectRaw = await readJsonFile(path20.resolve(opts.collectFile));
131622
- data = mergeCollectLighthouse(data, asRecord4(collectRaw));
132418
+ data = mergeCollectLighthouse(data, asRecord5(collectRaw));
131623
132419
  }
131624
132420
  const templatePath = websiteDiagnosisReportTemplatePath();
131625
132421
  let html;
@@ -132277,7 +133073,7 @@ function formatMarketReportContentErrors(result) {
132277
133073
  }
132278
133074
 
132279
133075
  // src/commands/market-analysis/render-report.ts
132280
- function asRecord5(value) {
133076
+ function asRecord6(value) {
132281
133077
  if (value && typeof value === "object" && !Array.isArray(value)) {
132282
133078
  return value;
132283
133079
  }
@@ -132307,7 +133103,7 @@ async function runMarketAnalysisRender(opts) {
132307
133103
  }
132308
133104
  let html;
132309
133105
  try {
132310
- html = resolveMarketAnalysisHtml(asRecord5(dataRaw));
133106
+ html = resolveMarketAnalysisHtml(asRecord6(dataRaw));
132311
133107
  } catch (err) {
132312
133108
  const message = err instanceof Error ? err.message : String(err);
132313
133109
  console.error(`
@@ -132319,7 +133115,7 @@ async function runMarketAnalysisRender(opts) {
132319
133115
  console.error("\n\u274C \u62A5\u544A HTML \u5185\u5BB9\u4E3A\u7A7A\n");
132320
133116
  process.exit(1);
132321
133117
  }
132322
- const reportData = asRecord5(dataRaw);
133118
+ const reportData = asRecord6(dataRaw);
132323
133119
  const contentCheck = validateMarketReportContent(html, validationContextFromReport(reportData));
132324
133120
  if (!contentCheck.ok) {
132325
133121
  console.error(`
@@ -133327,14 +134123,14 @@ function buildGoogleAdsDiagnosisCollectPayload(opts) {
133327
134123
  }
133328
134124
 
133329
134125
  // src/commands/google-ads-diagnosis/collect-digest.ts
133330
- function asRecord6(value) {
134126
+ function asRecord7(value) {
133331
134127
  if (value && typeof value === "object" && !Array.isArray(value)) {
133332
134128
  return value;
133333
134129
  }
133334
134130
  return null;
133335
134131
  }
133336
134132
  function fieldsOfFirstRow(rows) {
133337
- const first = asRecord6(rows[0]);
134133
+ const first = asRecord7(rows[0]);
133338
134134
  return first ? Object.keys(first) : [];
133339
134135
  }
133340
134136
  function describeSectionShapes(reportData) {
@@ -133344,7 +134140,7 @@ function describeSectionShapes(reportData) {
133344
134140
  if (Array.isArray(value)) {
133345
134141
  return { section, itemCount: value.length, fields: fieldsOfFirstRow(value), needsNarrative };
133346
134142
  }
133347
- const record2 = asRecord6(value);
134143
+ const record2 = asRecord7(value);
133348
134144
  if (!record2) {
133349
134145
  return { section, itemCount: null, fields: [], needsNarrative };
133350
134146
  }
@@ -133413,21 +134209,21 @@ function buildCollectDigest(reportData, meta) {
133413
134209
  }
133414
134210
 
133415
134211
  // src/commands/google-ads-diagnosis/collect-integrity.ts
133416
- function asRecord7(value) {
134212
+ function asRecord8(value) {
133417
134213
  if (value && typeof value === "object" && !Array.isArray(value)) {
133418
134214
  return value;
133419
134215
  }
133420
134216
  return null;
133421
134217
  }
133422
134218
  function itemCount(block) {
133423
- const items3 = asRecord7(block)?.items;
134219
+ const items3 = asRecord8(block)?.items;
133424
134220
  return Array.isArray(items3) ? items3.length : 0;
133425
134221
  }
133426
134222
  function getCollectIntegrityWarnings(reportData) {
133427
134223
  const warnings = [];
133428
134224
  const kwItems = itemCount(reportData.keywords);
133429
134225
  const fullKwItems = itemCount(reportData.fullKeywords);
133430
- const keywordCount = Number(asRecord7(reportData.structure)?.keywordCount ?? 0);
134226
+ const keywordCount = Number(asRecord8(reportData.structure)?.keywordCount ?? 0);
133431
134227
  if (kwItems === 0 && fullKwItems > 0) {
133432
134228
  warnings.push(
133433
134229
  `keywords.items \u5BF9\u6BD4\u8868\u4E3A\u7A7A\uFF0C\u4F46 fullKeywords.items \u6709 ${fullKwItems} \u884C\uFF1B\u8BF7\u786E\u8BA4 collect \u662F\u5426\u6210\u529F\u62C9\u53D6\u4E0A\u4E00\u5468\u671F keywords \u5FEB\u7167\uFF08\u73AF\u6BD4\u5217\u4F9D\u8D56 prev \u5468\u671F JSON\uFF09\u3002`
@@ -133438,7 +134234,7 @@ function getCollectIntegrityWarnings(reportData) {
133438
134234
  );
133439
134235
  }
133440
134236
  const campaignItems = itemCount(reportData.campaigns);
133441
- const campaignCount = Number(asRecord7(reportData.structure)?.campaignCount ?? 0);
134237
+ const campaignCount = Number(asRecord8(reportData.structure)?.campaignCount ?? 0);
133442
134238
  if (campaignItems === 0 && campaignCount > 0) {
133443
134239
  warnings.push(
133444
134240
  `campaigns.items \u5BF9\u6BD4\u8868\u4E3A\u7A7A\uFF0C\u4F46 structure.campaignCount=${campaignCount}\uFF1B\u8BF7\u786E\u8BA4\u4E0A\u4E00\u5468\u671F campaigns \u5FEB\u7167\u662F\u5426\u62C9\u53D6\u6210\u529F\u3002`
@@ -133496,7 +134292,7 @@ function invokeGoogleAnalysisCli(opts) {
133496
134292
 
133497
134293
  // src/commands/google-ads-diagnosis/write-draft.ts
133498
134294
  import fs20 from "fs/promises";
133499
- function asRecord8(value) {
134295
+ function asRecord9(value) {
133500
134296
  if (value && typeof value === "object" && !Array.isArray(value)) {
133501
134297
  return value;
133502
134298
  }
@@ -133505,7 +134301,7 @@ function asRecord8(value) {
133505
134301
  function valueAtPath(data, keys) {
133506
134302
  let cursor = data;
133507
134303
  for (const key of keys) {
133508
- const record2 = asRecord8(cursor);
134304
+ const record2 = asRecord9(cursor);
133509
134305
  if (!record2) return void 0;
133510
134306
  cursor = record2[key];
133511
134307
  }
@@ -133524,7 +134320,7 @@ function hasAgentNarrative(data) {
133524
134320
  async function writeDiagnosisDraft(opts) {
133525
134321
  try {
133526
134322
  const existing = JSON.parse(await fs20.readFile(opts.draftPath, "utf8"));
133527
- const record2 = asRecord8(existing);
134323
+ const record2 = asRecord9(existing);
133528
134324
  if (record2 && hasAgentNarrative(record2)) return "skipped-existing-narrative";
133529
134325
  } catch {
133530
134326
  }
@@ -133714,7 +134510,7 @@ import fs22 from "fs/promises";
133714
134510
  import path26 from "path";
133715
134511
 
133716
134512
  // src/commands/google-ads-diagnosis/report-content.ts
133717
- function asRecord9(value) {
134513
+ function asRecord10(value) {
133718
134514
  if (value && typeof value === "object" && !Array.isArray(value)) {
133719
134515
  return value;
133720
134516
  }
@@ -133723,7 +134519,7 @@ function asRecord9(value) {
133723
134519
  function getNestedValue(root, path55) {
133724
134520
  let cur = root;
133725
134521
  for (const key of path55) {
133726
- const rec = asRecord9(cur);
134522
+ const rec = asRecord10(cur);
133727
134523
  if (!rec) return void 0;
133728
134524
  cur = rec[key];
133729
134525
  }
@@ -133740,7 +134536,7 @@ function validateBudgetCompetitivenessStrategies(data) {
133740
134536
  }
133741
134537
  const warnings = [];
133742
134538
  for (let i = 0; i < items3.length; i++) {
133743
- const row = asRecord9(items3[i]);
134539
+ const row = asRecord10(items3[i]);
133744
134540
  const name2 = String(row?.name ?? row?.metric ?? i);
133745
134541
  if (!hasNarrativeContent(row?.strategy)) {
133746
134542
  warnings.push(`budgetCompetitiveness[${name2}].strategy \u4E3A\u7A7A\uFF08\u987B\u7531 Agent \u586B\u5199\uFF09`);
@@ -133749,13 +134545,13 @@ function validateBudgetCompetitivenessStrategies(data) {
133749
134545
  return warnings;
133750
134546
  }
133751
134547
  function validateNewFeatureRecommendations(data) {
133752
- const nf = asRecord9(data.newFeatures);
134548
+ const nf = asRecord10(data.newFeatures);
133753
134549
  if (!nf) return [];
133754
134550
  const items3 = nf.items;
133755
134551
  if (!Array.isArray(items3)) return [];
133756
134552
  const warnings = [];
133757
134553
  for (let i = 0; i < items3.length; i++) {
133758
- const row = asRecord9(items3[i]);
134554
+ const row = asRecord10(items3[i]);
133759
134555
  const name2 = String(row?.strategyName ?? row?.feature ?? row?.strategy ?? i);
133760
134556
  if (!hasNarrativeContent(row?.optimizerRecommendation)) {
133761
134557
  warnings.push(`newFeatures.items[${name2}].optimizerRecommendation \u4E3A\u7A7A\uFF08\u987B\u7531 Agent \u586B\u5199\uFF09`);
@@ -133764,13 +134560,13 @@ function validateNewFeatureRecommendations(data) {
133764
134560
  return warnings;
133765
134561
  }
133766
134562
  function validateAdCreativeItemSuggestions(data) {
133767
- const creative = asRecord9(data.adCreativeOptimization);
134563
+ const creative = asRecord10(data.adCreativeOptimization);
133768
134564
  if (!creative) return [];
133769
134565
  const items3 = creative.items;
133770
134566
  if (!Array.isArray(items3) || items3.length === 0) return [];
133771
134567
  const warnings = [];
133772
134568
  for (let i = 0; i < items3.length; i++) {
133773
- const row = asRecord9(items3[i]);
134569
+ const row = asRecord10(items3[i]);
133774
134570
  const title = String(row?.adTitle ?? i);
133775
134571
  if (!hasNarrativeContent(row?.suggestion ?? row?.suggestions)) {
133776
134572
  warnings.push(`adCreativeOptimization.items[${title}].suggestion \u4E3A\u7A7A\uFF08\u987B\u7531 Agent \u586B\u5199\uFF09`);
@@ -133781,7 +134577,7 @@ function validateAdCreativeItemSuggestions(data) {
133781
134577
  function validateGoogleAdsDiagnosisContent(data) {
133782
134578
  const missingKeys = GOOGLE_ADS_DIAGNOSIS_TOP_LEVEL_KEYS.filter((key) => data[key] === void 0);
133783
134579
  const warnings = [];
133784
- const accountInfo = asRecord9(data.accountInfo);
134580
+ const accountInfo = asRecord10(data.accountInfo);
133785
134581
  if (accountInfo && !accountInfo.companyName && !accountInfo.period) {
133786
134582
  warnings.push("accountInfo \u7F3A\u5C11 companyName \u4E0E period\uFF0C\u9875\u7709\u53EF\u80FD\u4E3A\u7A7A");
133787
134583
  }
@@ -133829,7 +134625,7 @@ var GOOGLE_ADS_DIAGNOSIS_RESTORE_ITEM_MODULES = [
133829
134625
  GOOGLE_ADS_DIAGNOSIS_BIDDING_STRATEGY_MODULE,
133830
134626
  GOOGLE_ADS_DIAGNOSIS_NEW_FEATURES_MODULE
133831
134627
  ];
133832
- function asRecord10(value) {
134628
+ function asRecord11(value) {
133833
134629
  if (value && typeof value === "object" && !Array.isArray(value)) {
133834
134630
  return value;
133835
134631
  }
@@ -133840,7 +134636,7 @@ function isValidRateChange(value) {
133840
134636
  return typeof value === "number" && Number.isFinite(value);
133841
134637
  }
133842
134638
  function isComparisonTableRowValid(row) {
133843
- const rec = asRecord10(row);
134639
+ const rec = asRecord11(row);
133844
134640
  if (!rec) return false;
133845
134641
  if (!String(rec.title ?? "").trim()) return false;
133846
134642
  if (!Number.isFinite(Number(rec.currentCost))) return false;
@@ -133852,12 +134648,12 @@ function isComparisonTableRowValid(row) {
133852
134648
  return true;
133853
134649
  }
133854
134650
  function isNewFeatureRowValid(row) {
133855
- const rec = asRecord10(row);
134651
+ const rec = asRecord11(row);
133856
134652
  if (!rec) return false;
133857
134653
  return Boolean(String(rec.strategyName ?? rec.feature ?? rec.strategy ?? "").trim());
133858
134654
  }
133859
134655
  function isBiddingStrategyRowValid(row) {
133860
- const rec = asRecord10(row);
134656
+ const rec = asRecord11(row);
133861
134657
  if (!rec) return false;
133862
134658
  if (!String(rec.campaignName ?? "").trim()) return false;
133863
134659
  if (!Number.isFinite(Number(rec.duration)) || Number(rec.duration) <= 0) return false;
@@ -133895,11 +134691,11 @@ function getFactItemsErrors(data) {
133895
134691
  for (const mod of GOOGLE_ADS_DIAGNOSIS_RESTORE_ITEM_MODULES) {
133896
134692
  const validator = MODULE_ITEM_VALIDATORS[mod];
133897
134693
  const hint = MODULE_ITEM_ERROR_HINT[mod];
133898
- const block = asRecord10(data[mod]);
134694
+ const block = asRecord11(data[mod]);
133899
134695
  const items3 = block?.items;
133900
134696
  if (!Array.isArray(items3) || items3.length === 0) {
133901
134697
  if (mod === "keywords") {
133902
- const fullKw = asRecord10(data.fullKeywords)?.items;
134698
+ const fullKw = asRecord11(data.fullKeywords)?.items;
133903
134699
  if (Array.isArray(fullKw) && fullKw.length > 0) {
133904
134700
  errors.push(
133905
134701
  "keywords.items \u4E3A\u7A7A\u4F46 fullKeywords.items \u6709\u6570\u636E\uFF1B\u8BF7\u4FDD\u7559\u540C\u76EE\u5F55 google-ads-diagnosis-collect.json \u540E\u91CD\u65B0 render\uFF08\u4F1A\u81EA\u52A8\u6062\u590D\u5BF9\u6BD4\u8868\uFF09"
@@ -133924,15 +134720,15 @@ var LANDING_PAGE_SPEED_KEYS = [
133924
134720
  "speedIndex"
133925
134721
  ];
133926
134722
  function isLandingPageSpeedValid(value) {
133927
- const rec = asRecord10(value);
134723
+ const rec = asRecord11(value);
133928
134724
  if (!rec) return false;
133929
134725
  return LANDING_PAGE_SPEED_KEYS.every(
133930
134726
  (key) => typeof rec[key] === "number" && Number.isFinite(rec[key])
133931
134727
  );
133932
134728
  }
133933
134729
  function restoreLandingPageSpeedFromCollect(finalData, collectReportData) {
133934
- const finalBlock = asRecord10(finalData[GOOGLE_ADS_DIAGNOSIS_LANDING_PAGE_MODULE]);
133935
- const collectBlock = asRecord10(collectReportData[GOOGLE_ADS_DIAGNOSIS_LANDING_PAGE_MODULE]);
134730
+ const finalBlock = asRecord11(finalData[GOOGLE_ADS_DIAGNOSIS_LANDING_PAGE_MODULE]);
134731
+ const collectBlock = asRecord11(collectReportData[GOOGLE_ADS_DIAGNOSIS_LANDING_PAGE_MODULE]);
133936
134732
  if (!collectBlock) return { data: finalData, restored: false };
133937
134733
  const needsDesktop = !isLandingPageSpeedValid(finalBlock?.desktop) && isLandingPageSpeedValid(collectBlock.desktop);
133938
134734
  const needsMobile = !isLandingPageSpeedValid(finalBlock?.mobile) && isLandingPageSpeedValid(collectBlock.mobile);
@@ -133955,8 +134751,8 @@ function mergeComparisonItemsFromCollect(finalData, collectReportData) {
133955
134751
  const restoredModules = [];
133956
134752
  for (const mod of GOOGLE_ADS_DIAGNOSIS_RESTORE_ITEM_MODULES) {
133957
134753
  const validator = MODULE_ITEM_VALIDATORS[mod];
133958
- const finalBlock = asRecord10(data[mod]);
133959
- const collectBlock = asRecord10(collectReportData[mod]);
134754
+ const finalBlock = asRecord11(data[mod]);
134755
+ const collectBlock = asRecord11(collectReportData[mod]);
133960
134756
  const finalItems = finalBlock?.items;
133961
134757
  const collectItems = collectBlock?.items;
133962
134758
  if (!Array.isArray(collectItems) || collectItems.length === 0) continue;
@@ -133972,7 +134768,7 @@ function mergeComparisonItemsFromCollect(finalData, collectReportData) {
133972
134768
  }
133973
134769
 
133974
134770
  // src/commands/google-ads-diagnosis/narrative-consistency-check.ts
133975
- function asRecord11(value) {
134771
+ function asRecord12(value) {
133976
134772
  if (value && typeof value === "object" && !Array.isArray(value)) {
133977
134773
  return value;
133978
134774
  }
@@ -133983,14 +134779,14 @@ function normalizeSuggestionText(value) {
133983
134779
  }
133984
134780
  function collectNarrativeTexts(data) {
133985
134781
  const texts = [];
133986
- const summary = asRecord11(data.summary);
134782
+ const summary = asRecord12(data.summary);
133987
134783
  if (Array.isArray(summary?.keyIssues)) {
133988
134784
  for (const item of summary.keyIssues) texts.push(String(item ?? ""));
133989
134785
  }
133990
- const overview = asRecord11(data.diagnosisOverview);
134786
+ const overview = asRecord12(data.diagnosisOverview);
133991
134787
  if (Array.isArray(overview?.disadvantages)) {
133992
134788
  for (const item of overview.disadvantages) {
133993
- const rec = asRecord11(item);
134789
+ const rec = asRecord12(item);
133994
134790
  if (rec) {
133995
134791
  texts.push(String(rec.title ?? ""), String(rec.description ?? ""));
133996
134792
  } else {
@@ -134001,16 +134797,16 @@ function collectNarrativeTexts(data) {
134001
134797
  return texts.filter((t) => t.trim().length > 0);
134002
134798
  }
134003
134799
  function newFeatureAccountStatus(data, strategy) {
134004
- const nf = asRecord11(data.newFeatures);
134800
+ const nf = asRecord12(data.newFeatures);
134005
134801
  const items3 = nf?.items;
134006
134802
  if (!Array.isArray(items3)) return null;
134007
- const row = items3.find((it) => asRecord11(it)?.strategy === strategy);
134008
- const rec = asRecord11(row);
134803
+ const row = items3.find((it) => asRecord12(it)?.strategy === strategy);
134804
+ const rec = asRecord12(row);
134009
134805
  if (!rec || typeof rec.accountStatus !== "boolean") return null;
134010
134806
  return rec.accountStatus;
134011
134807
  }
134012
134808
  function goldAccountFlag(data, key) {
134013
- const gold = asRecord11(data.goldAccount);
134809
+ const gold = asRecord12(data.goldAccount);
134014
134810
  const value = gold?.[key];
134015
134811
  return typeof value === "boolean" ? value : null;
134016
134812
  }
@@ -134055,7 +134851,7 @@ function getRepetitiveNarrativeErrors(data) {
134055
134851
  const errors = [];
134056
134852
  const budget = data.budgetCompetitiveness;
134057
134853
  if (Array.isArray(budget) && budget.length >= 3) {
134058
- const strategies = budget.map((row) => normalizeSuggestionText(asRecord11(row)?.strategy)).filter((s) => s.length > 0);
134854
+ const strategies = budget.map((row) => normalizeSuggestionText(asRecord12(row)?.strategy)).filter((s) => s.length > 0);
134059
134855
  const dup = findIdenticalTexts(strategies, 3);
134060
134856
  if (dup) {
134061
134857
  errors.push(
@@ -134063,10 +134859,10 @@ function getRepetitiveNarrativeErrors(data) {
134063
134859
  );
134064
134860
  }
134065
134861
  }
134066
- const creative = asRecord11(data.adCreativeOptimization);
134862
+ const creative = asRecord12(data.adCreativeOptimization);
134067
134863
  const creativeItems = creative?.items;
134068
134864
  if (Array.isArray(creativeItems) && creativeItems.length >= 3) {
134069
- const suggestions = creativeItems.map((row) => normalizeSuggestionText(asRecord11(row)?.suggestion)).filter((s) => s.length > 0);
134865
+ const suggestions = creativeItems.map((row) => normalizeSuggestionText(asRecord12(row)?.suggestion)).filter((s) => s.length > 0);
134070
134866
  const dup = findIdenticalTexts(suggestions, 3);
134071
134867
  if (dup) {
134072
134868
  errors.push(
@@ -134077,7 +134873,7 @@ function getRepetitiveNarrativeErrors(data) {
134077
134873
  return errors;
134078
134874
  }
134079
134875
  function getLandingPageTopicErrors(data) {
134080
- const lp = asRecord11(data.landingPageAnalysis);
134876
+ const lp = asRecord12(data.landingPageAnalysis);
134081
134877
  if (!lp) return [];
134082
134878
  const analysis = String(lp.analysis ?? "");
134083
134879
  if (!analysis.trim()) return [];
@@ -134107,7 +134903,7 @@ function getNarrativeConsistencyErrors(data) {
134107
134903
  }
134108
134904
 
134109
134905
  // src/commands/google-ads-diagnosis/render-report.ts
134110
- function asRecord12(value) {
134906
+ function asRecord13(value) {
134111
134907
  if (value && typeof value === "object" && !Array.isArray(value)) {
134112
134908
  return value;
134113
134909
  }
@@ -134116,8 +134912,8 @@ function asRecord12(value) {
134116
134912
  async function tryLoadCollectReportData(collectPath) {
134117
134913
  try {
134118
134914
  const raw = JSON.parse(await fs22.readFile(collectPath, "utf8"));
134119
- const root = asRecord12(raw);
134120
- const reportData = asRecord12(root?.reportData);
134915
+ const root = asRecord13(raw);
134916
+ const reportData = asRecord13(root?.reportData);
134121
134917
  return reportData ?? root;
134122
134918
  } catch {
134123
134919
  return null;
@@ -134134,7 +134930,7 @@ async function runGoogleAdsDiagnosisRender(opts) {
134134
134930
  `);
134135
134931
  process.exit(1);
134136
134932
  }
134137
- let data = asRecord12(dataRaw);
134933
+ let data = asRecord13(dataRaw);
134138
134934
  if (!opts.noMergeCollect) {
134139
134935
  const collectPath = path26.resolve(
134140
134936
  opts.collectFile ?? path26.join(path26.dirname(dataPath), GOOGLE_ADS_DIAGNOSIS_COLLECT_BASENAME)
@@ -135464,26 +136260,26 @@ import fs26 from "fs/promises";
135464
136260
  import path31 from "path";
135465
136261
 
135466
136262
  // src/commands/google-quarterly/report-content.ts
135467
- function asRecord13(value) {
136263
+ function asRecord14(value) {
135468
136264
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
135469
136265
  }
135470
136266
  function asStringArray(value) {
135471
136267
  return Array.isArray(value) ? value.map((x) => String(x).trim()).filter(Boolean) : [];
135472
136268
  }
135473
136269
  function validateQuarterlyNarrative(data) {
135474
- const root = asRecord13(data);
135475
- const narrative = asRecord13(root?.narrative);
136270
+ const root = asRecord14(data);
136271
+ const narrative = asRecord14(root?.narrative);
135476
136272
  const missing = [];
135477
136273
  if (!narrative) {
135478
136274
  return { ok: false, missing: ["narrative"] };
135479
136275
  }
135480
136276
  if (asStringArray(narrative.executiveSummary).length < 1) missing.push("narrative.executiveSummary");
135481
- const sections = asRecord13(narrative.sections);
136277
+ const sections = asRecord14(narrative.sections);
135482
136278
  for (const key of ["efficiency", "adType", "region", "summary"]) {
135483
- const block = asRecord13(sections?.[key]);
136279
+ const block = asRecord14(sections?.[key]);
135484
136280
  if (asStringArray(block?.analysis).length < 1) missing.push(`narrative.sections.${key}.analysis`);
135485
136281
  }
135486
- const plan = asRecord13(narrative.plan);
136282
+ const plan = asRecord14(narrative.plan);
135487
136283
  if (asStringArray(plan?.analysis ?? plan?.goals).length < 1 && !String(plan?.text ?? "").trim()) {
135488
136284
  missing.push("narrative.plan");
135489
136285
  }
@@ -135496,8 +136292,8 @@ function mergeCollectFacts(agentData, collect) {
135496
136292
  ...facts,
135497
136293
  narrative: agentData.narrative ?? collect.narrative,
135498
136294
  meta: {
135499
- ...asRecord13(collect.meta) ?? {},
135500
- ...asRecord13(agentData.meta) ?? {}
136295
+ ...asRecord14(collect.meta) ?? {},
136296
+ ...asRecord14(agentData.meta) ?? {}
135501
136297
  }
135502
136298
  };
135503
136299
  }
@@ -135509,7 +136305,7 @@ import { fileURLToPath as fileURLToPath8 } from "url";
135509
136305
  var TSO_CLI_ROOT = path30.join(path30.dirname(fileURLToPath8(import.meta.url)), "../..");
135510
136306
 
135511
136307
  // src/commands/google-quarterly/render-report.ts
135512
- function asRecord14(value) {
136308
+ function asRecord15(value) {
135513
136309
  if (value && typeof value === "object" && !Array.isArray(value)) {
135514
136310
  return value;
135515
136311
  }
@@ -135538,7 +136334,7 @@ async function runGoogleQuarterlyRender(opts) {
135538
136334
  `);
135539
136335
  process.exit(1);
135540
136336
  }
135541
- const merged = mergeCollectFacts(asRecord14(agentRaw), asRecord14(collectRaw));
136337
+ const merged = mergeCollectFacts(asRecord15(agentRaw), asRecord15(collectRaw));
135542
136338
  const check = validateQuarterlyNarrative(merged);
135543
136339
  if (!check.ok && !opts.lenient) {
135544
136340
  console.error("\n\u274C narrative \u4E0D\u5B8C\u6574\uFF0C\u62D2\u7EDD\u51FA HTML\uFF1A\n");
@@ -135702,7 +136498,7 @@ import * as fs33 from "fs/promises";
135702
136498
  import * as path40 from "path";
135703
136499
 
135704
136500
  // src/commands/facebook-analysis/report-metrics.ts
135705
- function asRecord20(value) {
136501
+ function asRecord21(value) {
135706
136502
  if (value && typeof value === "object" && !Array.isArray(value)) {
135707
136503
  return value;
135708
136504
  }
@@ -135839,7 +136635,7 @@ function localizeFacebookReportLabels(payload) {
135839
136635
  for (const rows of Object.values(tables)) {
135840
136636
  if (!Array.isArray(rows)) continue;
135841
136637
  for (const row of rows) {
135842
- localizeMetricLabels(asRecord20(row));
136638
+ localizeMetricLabels(asRecord21(row));
135843
136639
  }
135844
136640
  }
135845
136641
  return payload;
@@ -135872,7 +136668,7 @@ async function readManifest3(snapshotDir) {
135872
136668
  async function loadSectionFile3(snapshotDir, file) {
135873
136669
  try {
135874
136670
  const raw = await fs33.readFile(path40.join(snapshotDir, file), "utf8");
135875
- return asRecord20(JSON.parse(raw));
136671
+ return asRecord21(JSON.parse(raw));
135876
136672
  } catch {
135877
136673
  return null;
135878
136674
  }
@@ -135928,7 +136724,7 @@ async function mergeFacebookSnapshotIntoReport(payload, snapshotDir) {
135928
136724
  if (data) sectionMap.set(art.section, data);
135929
136725
  }
135930
136726
  const overview = sectionMap.get("overview");
135931
- const current = asRecord20(overview?.currentPeriod);
136727
+ const current = asRecord21(overview?.currentPeriod);
135932
136728
  const accountName = typeof overview?.accountName === "string" ? overview.accountName : void 0;
135933
136729
  const accountId = manifest.accountId ?? (typeof overview?.accountId === "string" ? overview.accountId : void 0);
135934
136730
  const kpis = { ...payload.kpis ?? {} };
@@ -136065,7 +136861,7 @@ function writeSimpleXlsx(filePath, sheets, opts = {}) {
136065
136861
  }
136066
136862
 
136067
136863
  // src/commands/facebook-analysis/render-excel.ts
136068
- function asRecord21(value) {
136864
+ function asRecord22(value) {
136069
136865
  if (value && typeof value === "object" && !Array.isArray(value)) {
136070
136866
  return value;
136071
136867
  }
@@ -136113,8 +136909,8 @@ function bullets(value) {
136113
136909
  return asArray3(value).map((item) => typeof item === "string" ? item.trim() : "").filter(Boolean);
136114
136910
  }
136115
136911
  function insightLines(section) {
136116
- const rec = asRecord21(section);
136117
- const insight = asRecord21(rec?.insight) ?? rec;
136912
+ const rec = asRecord22(section);
136913
+ const insight = asRecord22(rec?.insight) ?? rec;
136118
136914
  return [...bullets(insight?.analysis), ...bullets(insight?.advice)];
136119
136915
  }
136120
136916
  function numberedSection(index, title, lines) {
@@ -136123,15 +136919,15 @@ function numberedSection(index, title, lines) {
136123
136919
  ${body}`;
136124
136920
  }
136125
136921
  function buildSummaryNarrative(data) {
136126
- const kpis = asRecord21(data.kpis) ?? {};
136127
- const meta = asRecord21(data.meta) ?? {};
136128
- const sections = asRecord21(data.sections) ?? {};
136922
+ const kpis = asRecord22(data.kpis) ?? {};
136923
+ const meta = asRecord22(data.meta) ?? {};
136924
+ const sections = asRecord22(data.sections) ?? {};
136129
136925
  const period = str2(meta.periodLabel) || `${str2(meta.startDate)} ~ ${str2(meta.endDate)}`.trim();
136130
136926
  const account = str2(meta.accountName) || "Facebook \u5E7F\u544A\u8D26\u6237";
136131
136927
  const campaign = str2(meta.campaignName);
136132
136928
  const resultLabel = displayResultType(kpis.resultType ?? meta.resultType) || "\u6210\u6548";
136133
136929
  const resultNoun = /潜在客户|lead/i.test(resultLabel) ? "\u4E2A\u6F5C\u5728\u5BA2\u6237\u8868\u5355" : `\u4E2A${resultLabel}`;
136134
- const firstQuestion = asRecord21(asArray3(data.fourQuestions)[0]);
136930
+ const firstQuestion = asRecord22(asArray3(data.fourQuestions)[0]);
136135
136931
  const extra = str2(firstQuestion?.verdict);
136136
136932
  const spendLine = [
136137
136933
  campaign ? `\uFF08\u5E7F\u544A\u7CFB\u5217\uFF1A${campaign}\uFF09` : "",
@@ -136151,7 +136947,7 @@ function buildSummaryNarrative(data) {
136151
136947
  numberedSection(3, "\u5E7F\u544A\u9891\u6B21\u4E0E\u65E5\u8D8B\u52BF", insightLines(sections.daily))
136152
136948
  ].join("\n");
136153
136949
  const recBlocks = asArray3(data.recommendations).map((raw, i) => {
136154
- const rec = asRecord21(raw);
136950
+ const rec = asRecord22(raw);
136155
136951
  if (!rec) return "";
136156
136952
  const title = [str2(rec.title), str2(rec.tag)].filter(Boolean).join(" \xB7 ");
136157
136953
  return numberedSection(i + 1, title || "\u4F18\u5316\u5EFA\u8BAE", bullets(rec.items));
@@ -136162,9 +136958,9 @@ function buildSummaryNarrative(data) {
136162
136958
  return [partOne, partTwo, partThree];
136163
136959
  }
136164
136960
  function buildMetaPeriodExcelSheets(data) {
136165
- const meta = asRecord21(data.meta) ?? {};
136166
- const kpis = asRecord21(data.kpis) ?? {};
136167
- const tables = asRecord21(data.tables) ?? {};
136961
+ const meta = asRecord22(data.meta) ?? {};
136962
+ const kpis = asRecord22(data.kpis) ?? {};
136963
+ const tables = asRecord22(data.tables) ?? {};
136168
136964
  const currency = str2(meta.currency) || "USD";
136169
136965
  const resultType = displayResultType(kpis.resultType ?? meta.resultType);
136170
136966
  const attribution = displayAttribution(kpis.attributionSetting ?? meta.attributionSetting);
@@ -136183,19 +136979,19 @@ function buildMetaPeriodExcelSheets(data) {
136183
136979
  ];
136184
136980
  const dailyRows = [metricHeaders(currency, "\u5355\u65E5")];
136185
136981
  for (const raw of asArray3(tables.daily)) {
136186
- const row = asRecord21(raw);
136982
+ const row = asRecord22(raw);
136187
136983
  if (!row) continue;
136188
136984
  dailyRows.push([normalizeInsightDate(row.date), ...metricCells(row)]);
136189
136985
  }
136190
136986
  const countryRows = [metricHeaders(currency, "\u56FD\u5BB6/\u5730\u533A")];
136191
136987
  for (const raw of asArray3(tables.countries)) {
136192
- const row = asRecord21(raw);
136988
+ const row = asRecord22(raw);
136193
136989
  if (!row) continue;
136194
136990
  countryRows.push([str2(row.countryOrRegion), ...metricCells(row)]);
136195
136991
  }
136196
136992
  const campaignRows3 = [metricHeaders(currency, "\u5E7F\u544A\u7CFB\u5217\u540D\u79F0")];
136197
136993
  for (const raw of asArray3(tables.campaigns)) {
136198
- const row = asRecord21(raw);
136994
+ const row = asRecord22(raw);
136199
136995
  if (!row) continue;
136200
136996
  campaignRows3.push([str2(row.campaignName), ...metricCells(row)]);
136201
136997
  }
@@ -136214,7 +137010,7 @@ function buildMetaPeriodExcelSheets(data) {
136214
137010
  ]
136215
137011
  ];
136216
137012
  for (const raw of asArray3(tables.audiences)) {
136217
- const row = asRecord21(raw);
137013
+ const row = asRecord22(raw);
136218
137014
  if (!row) continue;
136219
137015
  audienceRows.push([str2(row.age), str2(row.gender), ...metricCells(row)]);
136220
137016
  }
@@ -136246,7 +137042,7 @@ function isFiniteNumber(value) {
136246
137042
  function asArray4(value) {
136247
137043
  return Array.isArray(value) ? value : [];
136248
137044
  }
136249
- function asRecord22(value) {
137045
+ function asRecord23(value) {
136250
137046
  if (value && typeof value === "object" && !Array.isArray(value)) {
136251
137047
  return value;
136252
137048
  }
@@ -136259,8 +137055,8 @@ function stringList3(value) {
136259
137055
  return asArray4(value).map((item) => typeof item === "string" ? item.trim() : "").filter(Boolean);
136260
137056
  }
136261
137057
  function insightLists(section) {
136262
- const rec = asRecord22(section);
136263
- const insight = asRecord22(rec?.insight) ?? rec;
137058
+ const rec = asRecord23(section);
137059
+ const insight = asRecord23(rec?.insight) ?? rec;
136264
137060
  return {
136265
137061
  analysis: stringList3(insight?.analysis),
136266
137062
  advice: stringList3(insight?.advice)
@@ -136290,11 +137086,11 @@ function requireInsight(missing, key, chapter, section, required) {
136290
137086
  }
136291
137087
  function validateMetaPeriodReportContent(data) {
136292
137088
  const missing = [];
136293
- const meta = asRecord22(data.meta) ?? {};
136294
- const kpis = asRecord22(data.kpis) ?? {};
136295
- const tables = asRecord22(data.tables) ?? {};
136296
- const charts = asRecord22(data.charts) ?? {};
136297
- const sections = asRecord22(data.sections) ?? {};
137089
+ const meta = asRecord23(data.meta) ?? {};
137090
+ const kpis = asRecord23(data.kpis) ?? {};
137091
+ const tables = asRecord23(data.tables) ?? {};
137092
+ const charts = asRecord23(data.charts) ?? {};
137093
+ const sections = asRecord23(data.sections) ?? {};
136298
137094
  const fourQuestions = asArray4(data.fourQuestions);
136299
137095
  const recommendations = asArray4(data.recommendations);
136300
137096
  if (!textLen3(meta.accountName) && !textLen3(meta.accountId)) {
@@ -136373,7 +137169,7 @@ function validateMetaPeriodReportContent(data) {
136373
137169
  "\u987B\u6709 tables.audiences \u6570\u7EC4\uFF1B\u62C9\u6570\u52A0 --sections audience\uFF0Crender \u65F6\u4F20 --snapshot-dir\u3002\u672C\u671F\u65E0\u6D88\u8017\u53EF\u4E3A []"
136374
137170
  );
136375
137171
  }
136376
- const dailyChart = asRecord22(charts.daily);
137172
+ const dailyChart = asRecord23(charts.daily);
136377
137173
  if (!Array.isArray(dailyChart?.labels)) {
136378
137174
  pushMissing3(
136379
137175
  missing,
@@ -136383,7 +137179,7 @@ function validateMetaPeriodReportContent(data) {
136383
137179
  "\u987B\u6709 charts.daily.labels \u6570\u7EC4\uFF1B\u53EF\u7531 --snapshot-dir \u5408\u5E76 daily\u3002\u672C\u671F\u65E0\u6D88\u8017\u53EF\u4E3A []"
136384
137180
  );
136385
137181
  }
136386
- const countryChart = asRecord22(charts.country);
137182
+ const countryChart = asRecord23(charts.country);
136387
137183
  if (!Array.isArray(countryChart?.labels)) {
136388
137184
  pushMissing3(
136389
137185
  missing,
@@ -136393,7 +137189,7 @@ function validateMetaPeriodReportContent(data) {
136393
137189
  "\u987B\u6709 charts.country.labels \u6570\u7EC4\uFF1B\u53EF\u7531 --snapshot-dir \u5408\u5E76 country\u3002\u672C\u671F\u65E0\u6D88\u8017\u53EF\u4E3A []"
136394
137190
  );
136395
137191
  }
136396
- const audienceChart = asRecord22(charts.audience);
137192
+ const audienceChart = asRecord23(charts.audience);
136397
137193
  if (!Array.isArray(audienceChart?.labels)) {
136398
137194
  pushMissing3(
136399
137195
  missing,
@@ -136412,7 +137208,7 @@ function validateMetaPeriodReportContent(data) {
136412
137208
  "\u5FC5\u987B\u6070\u597D 4 \u95EE\uFF1A\u94B1\u82B1\u5F97\u503C\u4E0D\u503C / \u8C01\u771F\u7684\u60F3\u4E70 / \u5E7F\u544A\u8FD8\u65B0\u9C9C\u5417 / \u7528\u6237\u4E3A\u4EC0\u4E48\u4E0D\u7559\u8D44"
136413
137209
  );
136414
137210
  } else {
136415
- const titles = fourQuestions.map((q) => asRecord22(q)?.title);
137211
+ const titles = fourQuestions.map((q) => asRecord23(q)?.title);
136416
137212
  for (const title of FOUR_QUESTION_TITLES) {
136417
137213
  if (!titles.includes(title)) {
136418
137214
  pushMissing3(
@@ -136425,7 +137221,7 @@ function validateMetaPeriodReportContent(data) {
136425
137221
  }
136426
137222
  }
136427
137223
  for (let i = 0; i < fourQuestions.length; i++) {
136428
- const q = asRecord22(fourQuestions[i]);
137224
+ const q = asRecord23(fourQuestions[i]);
136429
137225
  if (textLen3(q?.verdict) < 8) {
136430
137226
  pushMissing3(
136431
137227
  missing,
@@ -136465,7 +137261,7 @@ function validateMetaPeriodReportContent(data) {
136465
137261
  );
136466
137262
  } else {
136467
137263
  for (let i = 0; i < recommendations.length; i++) {
136468
- const rec = asRecord22(recommendations[i]);
137264
+ const rec = asRecord23(recommendations[i]);
136469
137265
  if (textLen3(rec?.title) < 2) {
136470
137266
  pushMissing3(
136471
137267
  missing,
@@ -136558,7 +137354,7 @@ async function readJsonFile4(filePath) {
136558
137354
  throw new Error(`\u65E0\u6CD5\u89E3\u6790 JSON\uFF1A${filePath}`);
136559
137355
  }
136560
137356
  }
136561
- function asRecord23(value) {
137357
+ function asRecord24(value) {
136562
137358
  if (value && typeof value === "object" && !Array.isArray(value)) {
136563
137359
  return value;
136564
137360
  }
@@ -136587,7 +137383,7 @@ function defaultOutPath(dataPath, format, out) {
136587
137383
  }
136588
137384
  async function runFacebookAnalysisRender(opts) {
136589
137385
  const dataPath = path41.resolve(opts.dataFile);
136590
- let data = asRecord23(await readJsonFile4(dataPath));
137386
+ let data = asRecord24(await readJsonFile4(dataPath));
136591
137387
  if (opts.snapshotDir?.trim()) {
136592
137388
  data = await mergeFacebookSnapshotIntoReport(data, path41.resolve(opts.snapshotDir));
136593
137389
  }
@@ -136651,7 +137447,7 @@ import { fileURLToPath as fileURLToPath11 } from "url";
136651
137447
  // src/commands/facebook-analysis/diagnosis-merge-snapshot.ts
136652
137448
  import * as fs35 from "fs/promises";
136653
137449
  import * as path42 from "path";
136654
- function asRecord24(value) {
137450
+ function asRecord25(value) {
136655
137451
  if (value && typeof value === "object" && !Array.isArray(value)) {
136656
137452
  return value;
136657
137453
  }
@@ -136662,7 +137458,7 @@ function num8(value) {
136662
137458
  return Number.isFinite(n) ? n : void 0;
136663
137459
  }
136664
137460
  function asRows(value) {
136665
- return Array.isArray(value) ? value.filter((r) => asRecord24(r) !== null) : [];
137461
+ return Array.isArray(value) ? value.filter((r) => asRecord25(r) !== null) : [];
136666
137462
  }
136667
137463
  function pickMetricExtras(row, extras) {
136668
137464
  const out = {
@@ -136711,14 +137507,14 @@ async function readManifest4(snapshotDir, accountId) {
136711
137507
  async function loadSectionFile4(snapshotDir, file) {
136712
137508
  try {
136713
137509
  const raw = await fs35.readFile(path42.join(snapshotDir, file), "utf8");
136714
- return asRecord24(JSON.parse(raw));
137510
+ return asRecord25(JSON.parse(raw));
136715
137511
  } catch {
136716
137512
  return null;
136717
137513
  }
136718
137514
  }
136719
137515
  async function mergeMetaDiagnosisSnapshotIntoReport(payload, snapshotDir) {
136720
137516
  const absDir = path42.resolve(snapshotDir);
136721
- const metaAccountId = typeof asRecord24(payload.meta)?.accountId === "string" ? asRecord24(payload.meta)?.accountId : void 0;
137517
+ const metaAccountId = typeof asRecord25(payload.meta)?.accountId === "string" ? asRecord25(payload.meta)?.accountId : void 0;
136722
137518
  const manifest = await readManifest4(snapshotDir, metaAccountId);
136723
137519
  if (!manifest) {
136724
137520
  throw new Error(
@@ -136731,8 +137527,8 @@ async function mergeMetaDiagnosisSnapshotIntoReport(payload, snapshotDir) {
136731
137527
  if (data) sectionMap.set(art.section, data);
136732
137528
  }
136733
137529
  const overview = sectionMap.get("overview");
136734
- const currentPeriod = asRecord24(overview?.currentPeriod);
136735
- const previousPeriod = asRecord24(overview?.previousPeriod);
137530
+ const currentPeriod = asRecord25(overview?.currentPeriod);
137531
+ const previousPeriod = asRecord25(overview?.previousPeriod);
136736
137532
  const accountId = manifest.accountId ?? metaAccountId;
136737
137533
  const meta = { ...payload.meta ?? {} };
136738
137534
  if (!meta.accountId && accountId) meta.accountId = accountId;
@@ -136866,7 +137662,7 @@ function textLen4(value) {
136866
137662
  function asArray5(value) {
136867
137663
  return Array.isArray(value) ? value : [];
136868
137664
  }
136869
- function asRecord25(value) {
137665
+ function asRecord26(value) {
136870
137666
  if (value && typeof value === "object" && !Array.isArray(value)) {
136871
137667
  return value;
136872
137668
  }
@@ -136877,9 +137673,9 @@ function pushMissing4(missing, id, chapter, dimension, hint) {
136877
137673
  }
136878
137674
  function validateMetaDiagnosisReportContent(data) {
136879
137675
  const missing = [];
136880
- const meta = asRecord25(data.meta) ?? {};
136881
- const narrative = asRecord25(data.narrative) ?? {};
136882
- const sections = asRecord25(narrative.sections) ?? {};
137676
+ const meta = asRecord26(data.meta) ?? {};
137677
+ const narrative = asRecord26(data.narrative) ?? {};
137678
+ const sections = asRecord26(narrative.sections) ?? {};
136883
137679
  if (!textLen4(meta.accountId)) {
136884
137680
  pushMissing4(missing, "meta-account", "\u5143\u4FE1\u606F", "\u8D26\u6237 ID", "meta.accountId \u5FC5\u586B");
136885
137681
  }
@@ -136897,7 +137693,7 @@ function validateMetaDiagnosisReportContent(data) {
136897
137693
  const sectionSuggestionCounts = {};
136898
137694
  const sectionNotAvailable = {};
136899
137695
  for (const key of NORMAL_SECTION_KEYS) {
136900
- const section = asRecord25(sections[key]);
137696
+ const section = asRecord26(sections[key]);
136901
137697
  const analysis = asArray5(section?.analysis).filter((s) => textLen4(s) > 0);
136902
137698
  const suggestions = asArray5(section?.suggestions).filter((s) => textLen4(s) > 0);
136903
137699
  sectionAnalysisCounts[key] = analysis.length;
@@ -136923,7 +137719,7 @@ function validateMetaDiagnosisReportContent(data) {
136923
137719
  }
136924
137720
  }
136925
137721
  for (const key of NA_SECTION_KEYS) {
136926
- const section = asRecord25(sections[key]);
137722
+ const section = asRecord26(sections[key]);
136927
137723
  const analysis = asArray5(section?.analysis).filter((s) => textLen4(s) > 0);
136928
137724
  const suggestions = asArray5(section?.suggestions).filter((s) => textLen4(s) > 0);
136929
137725
  const notAvailable = section?.notAvailable === true;
@@ -136945,7 +137741,7 @@ function validateMetaDiagnosisReportContent(data) {
136945
137741
  }
136946
137742
  const recommendations = asArray5(narrative.recommendations).filter((r) => {
136947
137743
  if (typeof r === "string") return textLen4(r) > 0;
136948
- const rec = asRecord25(r);
137744
+ const rec = asRecord26(r);
136949
137745
  return textLen4(rec?.content) > 0;
136950
137746
  });
136951
137747
  if (recommendations.length < 3) {
@@ -137018,7 +137814,7 @@ async function readJsonFile5(filePath) {
137018
137814
  throw new Error(`\u65E0\u6CD5\u89E3\u6790 JSON\uFF1A${filePath}`);
137019
137815
  }
137020
137816
  }
137021
- function asRecord26(value) {
137817
+ function asRecord27(value) {
137022
137818
  if (value && typeof value === "object" && !Array.isArray(value)) {
137023
137819
  return value;
137024
137820
  }
@@ -137033,7 +137829,7 @@ function injectReportData4(html, payload) {
137033
137829
  }
137034
137830
  async function runFacebookAnalysisDiagnosisRender(opts) {
137035
137831
  const dataPath = path43.resolve(opts.dataFile);
137036
- let data = asRecord26(await readJsonFile5(dataPath));
137832
+ let data = asRecord27(await readJsonFile5(dataPath));
137037
137833
  if (opts.snapshotDir?.trim()) {
137038
137834
  data = await mergeMetaDiagnosisSnapshotIntoReport(data, path43.resolve(opts.snapshotDir));
137039
137835
  }
@@ -137232,7 +138028,7 @@ function resolveFacebookPageSize(raw, fallback = FB_ENTITY_PAGE_SIZE_DEFAULT) {
137232
138028
  if (!Number.isFinite(n) || n <= 0) return fallback;
137233
138029
  return Math.min(Math.max(Math.floor(n), 1), FB_ENTITY_PAGE_SIZE_MAX);
137234
138030
  }
137235
- function asRecord27(value) {
138031
+ function asRecord28(value) {
137236
138032
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
137237
138033
  }
137238
138034
  function pickProp(obj, ...keys) {
@@ -137242,12 +138038,12 @@ function pickProp(obj, ...keys) {
137242
138038
  return void 0;
137243
138039
  }
137244
138040
  function unwrapFacebookPaged(raw) {
137245
- const rec = asRecord27(raw);
138041
+ const rec = asRecord28(raw);
137246
138042
  if (!rec) return { items: [] };
137247
138043
  const data = pickProp(rec, "data", "Data");
137248
138044
  const items3 = Array.isArray(data) ? data : [];
137249
- const paging = asRecord27(pickProp(rec, "paging", "Paging"));
137250
- const cursors = paging ? asRecord27(pickProp(paging, "cursors", "Cursors")) : void 0;
138045
+ const paging = asRecord28(pickProp(rec, "paging", "Paging"));
138046
+ const cursors = paging ? asRecord28(pickProp(paging, "cursors", "Cursors")) : void 0;
137251
138047
  const afterRaw = cursors ? pickProp(cursors, "after", "After") : void 0;
137252
138048
  const after = typeof afterRaw === "string" && afterRaw.trim() ? afterRaw.trim() : void 0;
137253
138049
  return { items: items3, after };
@@ -137395,7 +138191,7 @@ async function fetchFacebookInsights(config, digits, level, opts) {
137395
138191
  opts.verbose
137396
138192
  );
137397
138193
  if (Array.isArray(raw)) return raw;
137398
- const rec = asRecord27(raw);
138194
+ const rec = asRecord28(raw);
137399
138195
  const data = rec ? pickProp(rec, "data", "Data") : void 0;
137400
138196
  return Array.isArray(data) ? data : [];
137401
138197
  }
@@ -137404,7 +138200,7 @@ function sumActionArray(raw) {
137404
138200
  let sum = 0;
137405
138201
  let hit = false;
137406
138202
  for (const item of raw) {
137407
- const rec = asRecord27(item);
138203
+ const rec = asRecord28(item);
137408
138204
  if (!rec) continue;
137409
138205
  const n = Number(rec.value);
137410
138206
  if (!Number.isFinite(n)) continue;
@@ -138683,7 +139479,7 @@ import { fileURLToPath as fileURLToPath12 } from "url";
138683
139479
  // src/commands/bing-analysis/merge-snapshot.ts
138684
139480
  import * as fs37 from "fs/promises";
138685
139481
  import * as path46 from "path";
138686
- function asRecord28(value) {
139482
+ function asRecord29(value) {
138687
139483
  if (value && typeof value === "object" && !Array.isArray(value)) {
138688
139484
  return value;
138689
139485
  }
@@ -138698,7 +139494,7 @@ function round27(value) {
138698
139494
  }
138699
139495
  function asRows2(value) {
138700
139496
  if (Array.isArray(value)) {
138701
- return value.filter((r) => asRecord28(r) !== null);
139497
+ return value.filter((r) => asRecord29(r) !== null);
138702
139498
  }
138703
139499
  return [];
138704
139500
  }
@@ -138780,17 +139576,17 @@ function campaignStatusDisplay(status) {
138780
139576
  return status == null || status === "" ? "\u2014" : String(status);
138781
139577
  }
138782
139578
  function mapDeviceRows(payload) {
138783
- const obj = asRecord28(payload);
139579
+ const obj = asRecord29(payload);
138784
139580
  return asRows2(obj?.devices).map((r) => pickMetrics(r, ["deviceType"]));
138785
139581
  }
138786
139582
  function mapGeographicRows(payload) {
138787
- const obj = asRecord28(payload);
139583
+ const obj = asRecord29(payload);
138788
139584
  return asRows2(obj?.countries).map(
138789
139585
  (r) => pickMetrics(r, ["countryOrRegion", "countryCriteriaId", "regionName", "cityName"])
138790
139586
  );
138791
139587
  }
138792
139588
  function mapAudienceLabelRows(payload, labelKey) {
138793
- const obj = asRecord28(payload);
139589
+ const obj = asRecord29(payload);
138794
139590
  return asRows2(obj?.audience).map((r) => {
138795
139591
  const m = pickMetrics(r, ["audience", "bidModifier"]);
138796
139592
  m[labelKey] = r.audience;
@@ -138798,7 +139594,7 @@ function mapAudienceLabelRows(payload, labelKey) {
138798
139594
  });
138799
139595
  }
138800
139596
  function mapAudienceFromMerged(payload) {
138801
- const data = asRecord28(asRecord28(payload)?.data);
139597
+ const data = asRecord29(asRecord29(payload)?.data);
138802
139598
  return {
138803
139599
  audienceAge: mapAudienceLabelRows(data?.ageAudience, "ageRange"),
138804
139600
  audienceGender: mapAudienceLabelRows(data?.genderAudience, "gender")
@@ -138893,7 +139689,7 @@ function mapSearchTermRows(payload) {
138893
139689
  }
138894
139690
  async function mergeBingAnalysisSnapshotIntoReport(payload, snapshotDir) {
138895
139691
  const absDir = path46.resolve(snapshotDir);
138896
- const metaAccountId = typeof asRecord28(payload.meta)?.accountId === "string" ? asRecord28(payload.meta)?.accountId : void 0;
139692
+ const metaAccountId = typeof asRecord29(payload.meta)?.accountId === "string" ? asRecord29(payload.meta)?.accountId : void 0;
138897
139693
  const manifest = await readManifest5(snapshotDir, metaAccountId);
138898
139694
  if (!manifest) {
138899
139695
  throw new Error(`\u672A\u5728 ${absDir} \u627E\u5230 report-manifest*.json\uFF0C\u8BF7\u5148\u6267\u884C bing-analysis --json-out`);
@@ -138903,9 +139699,9 @@ async function mergeBingAnalysisSnapshotIntoReport(payload, snapshotDir) {
138903
139699
  const data = await loadSectionPayload(absDir, art.file);
138904
139700
  if (data != null) sectionMap.set(art.section, data);
138905
139701
  }
138906
- const overview = asRecord28(sectionMap.get("overview"));
138907
- const currentPeriod = asRecord28(overview?.currentPeriod);
138908
- const previousPeriod = asRecord28(overview?.previousPeriod);
139702
+ const overview = asRecord29(sectionMap.get("overview"));
139703
+ const currentPeriod = asRecord29(overview?.currentPeriod);
139704
+ const previousPeriod = asRecord29(overview?.previousPeriod);
138909
139705
  const accountId = manifest.accountId ?? metaAccountId;
138910
139706
  const campaignRows3 = mapCampaignRows2(sectionMap.get("campaigns"));
138911
139707
  const campaignKpis = sumBingCampaignRowsToPeriodKpis(campaignRows3);
@@ -139032,7 +139828,7 @@ function textLen5(value) {
139032
139828
  function asArray6(value) {
139033
139829
  return Array.isArray(value) ? value : [];
139034
139830
  }
139035
- function asRecord29(value) {
139831
+ function asRecord30(value) {
139036
139832
  if (value && typeof value === "object" && !Array.isArray(value)) {
139037
139833
  return value;
139038
139834
  }
@@ -139043,9 +139839,9 @@ function pushMissing5(missing, id, chapter, dimension, hint) {
139043
139839
  }
139044
139840
  function validateBingPeriodReportContent(data) {
139045
139841
  const missing = [];
139046
- const meta = asRecord29(data.meta) ?? {};
139047
- const narrative = asRecord29(data.narrative) ?? {};
139048
- const sections = asRecord29(narrative.sections) ?? {};
139842
+ const meta = asRecord30(data.meta) ?? {};
139843
+ const narrative = asRecord30(data.narrative) ?? {};
139844
+ const sections = asRecord30(narrative.sections) ?? {};
139049
139845
  if (!textLen5(meta.accountId)) {
139050
139846
  pushMissing5(missing, "meta-account", "\u5143\u4FE1\u606F", "\u8D26\u6237 ID", "meta.accountId \u5FC5\u586B");
139051
139847
  }
@@ -139062,7 +139858,7 @@ function validateBingPeriodReportContent(data) {
139062
139858
  const sectionAnalysisCounts = {};
139063
139859
  const sectionSuggestionCounts = {};
139064
139860
  for (const key of SECTION_KEYS2) {
139065
- const section = asRecord29(sections[key]);
139861
+ const section = asRecord30(sections[key]);
139066
139862
  const analysis = asArray6(section?.analysis).filter((s) => textLen5(s) > 0);
139067
139863
  const suggestions = asArray6(section?.suggestions).filter((s) => textLen5(s) > 0);
139068
139864
  sectionAnalysisCounts[key] = analysis.length;
@@ -139088,7 +139884,7 @@ function validateBingPeriodReportContent(data) {
139088
139884
  }
139089
139885
  const recommendations = asArray6(narrative.recommendations).filter((r) => {
139090
139886
  if (typeof r === "string") return textLen5(r) > 0;
139091
- const rec = asRecord29(r);
139887
+ const rec = asRecord30(r);
139092
139888
  return textLen5(rec?.content) > 0;
139093
139889
  });
139094
139890
  if (recommendations.length < 3) {
@@ -139149,7 +139945,7 @@ async function readJsonFile6(filePath) {
139149
139945
  throw new Error(`\u65E0\u6CD5\u89E3\u6790 JSON\uFF1A${filePath}`);
139150
139946
  }
139151
139947
  }
139152
- function asRecord30(value) {
139948
+ function asRecord31(value) {
139153
139949
  if (value && typeof value === "object" && !Array.isArray(value)) {
139154
139950
  return value;
139155
139951
  }
@@ -139164,7 +139960,7 @@ function injectReportData5(html, payload) {
139164
139960
  }
139165
139961
  async function runBingAnalysisRender(opts) {
139166
139962
  const dataPath = path47.resolve(opts.dataFile);
139167
- let data = asRecord30(await readJsonFile6(dataPath));
139963
+ let data = asRecord31(await readJsonFile6(dataPath));
139168
139964
  if (opts.snapshotDir?.trim()) {
139169
139965
  data = await mergeBingAnalysisSnapshotIntoReport(data, path47.resolve(opts.snapshotDir));
139170
139966
  }
@@ -139637,7 +140433,7 @@ import { fileURLToPath as fileURLToPath13 } from "url";
139637
140433
  // src/commands/tiktok-analysis/merge-snapshot.ts
139638
140434
  import * as fs39 from "fs/promises";
139639
140435
  import * as path49 from "path";
139640
- function asRecord31(value) {
140436
+ function asRecord32(value) {
139641
140437
  if (value && typeof value === "object" && !Array.isArray(value)) {
139642
140438
  return value;
139643
140439
  }
@@ -139815,7 +140611,7 @@ function mapAudienceMerged(payload) {
139815
140611
  }
139816
140612
  async function mergeTikTokAnalysisSnapshotIntoReport(payload, snapshotDir) {
139817
140613
  const absDir = path49.resolve(snapshotDir);
139818
- const metaAccountId = typeof asRecord31(payload.meta)?.accountId === "string" ? asRecord31(payload.meta)?.accountId : void 0;
140614
+ const metaAccountId = typeof asRecord32(payload.meta)?.accountId === "string" ? asRecord32(payload.meta)?.accountId : void 0;
139819
140615
  const manifest = await readManifest6(snapshotDir, metaAccountId);
139820
140616
  if (!manifest) {
139821
140617
  throw new Error(
@@ -139929,7 +140725,7 @@ function textLen6(value) {
139929
140725
  function asArray7(value) {
139930
140726
  return Array.isArray(value) ? value : [];
139931
140727
  }
139932
- function asRecord32(value) {
140728
+ function asRecord33(value) {
139933
140729
  if (value && typeof value === "object" && !Array.isArray(value)) {
139934
140730
  return value;
139935
140731
  }
@@ -139940,9 +140736,9 @@ function pushMissing6(missing, id, chapter, dimension, hint) {
139940
140736
  }
139941
140737
  function validateTikTokPeriodReportContent(data) {
139942
140738
  const missing = [];
139943
- const meta = asRecord32(data.meta) ?? {};
139944
- const narrative = asRecord32(data.narrative) ?? {};
139945
- const sections = asRecord32(narrative.sections) ?? {};
140739
+ const meta = asRecord33(data.meta) ?? {};
140740
+ const narrative = asRecord33(data.narrative) ?? {};
140741
+ const sections = asRecord33(narrative.sections) ?? {};
139946
140742
  if (!textLen6(meta.accountId)) {
139947
140743
  pushMissing6(missing, "meta-account", "\u5143\u4FE1\u606F", "\u8D26\u6237 ID", "meta.accountId \u5FC5\u586B");
139948
140744
  }
@@ -139959,7 +140755,7 @@ function validateTikTokPeriodReportContent(data) {
139959
140755
  const sectionAnalysisCounts = {};
139960
140756
  const sectionSuggestionCounts = {};
139961
140757
  for (const key of SECTION_KEYS3) {
139962
- const section = asRecord32(sections[key]);
140758
+ const section = asRecord33(sections[key]);
139963
140759
  const analysis = asArray7(section?.analysis).filter((s) => textLen6(s) > 0);
139964
140760
  const suggestions = asArray7(section?.suggestions).filter((s) => textLen6(s) > 0);
139965
140761
  sectionAnalysisCounts[key] = analysis.length;
@@ -139985,7 +140781,7 @@ function validateTikTokPeriodReportContent(data) {
139985
140781
  }
139986
140782
  const recommendations = asArray7(narrative.recommendations).filter((r) => {
139987
140783
  if (typeof r === "string") return textLen6(r) > 0;
139988
- const rec = asRecord32(r);
140784
+ const rec = asRecord33(r);
139989
140785
  return textLen6(rec?.content) > 0;
139990
140786
  });
139991
140787
  if (recommendations.length < 3) {
@@ -140046,7 +140842,7 @@ async function readJsonFile7(filePath) {
140046
140842
  throw new Error(`\u65E0\u6CD5\u89E3\u6790 JSON\uFF1A${filePath}`);
140047
140843
  }
140048
140844
  }
140049
- function asRecord33(value) {
140845
+ function asRecord34(value) {
140050
140846
  if (value && typeof value === "object" && !Array.isArray(value)) {
140051
140847
  return value;
140052
140848
  }
@@ -140061,7 +140857,7 @@ function injectReportData6(html, payload) {
140061
140857
  }
140062
140858
  async function runTikTokAnalysisRender(opts) {
140063
140859
  const dataPath = path50.resolve(opts.dataFile);
140064
- let data = asRecord33(await readJsonFile7(dataPath));
140860
+ let data = asRecord34(await readJsonFile7(dataPath));
140065
140861
  if (opts.snapshotDir?.trim()) {
140066
140862
  data = await mergeTikTokAnalysisSnapshotIntoReport(data, path50.resolve(opts.snapshotDir));
140067
140863
  }
@@ -141160,7 +141956,7 @@ function endpointHintForYandexSection(def) {
141160
141956
  // src/commands/yandex-analysis/merge-snapshot.ts
141161
141957
  import * as fs41 from "fs/promises";
141162
141958
  import * as path51 from "path";
141163
- function asRecord34(value) {
141959
+ function asRecord35(value) {
141164
141960
  if (value && typeof value === "object" && !Array.isArray(value)) {
141165
141961
  return value;
141166
141962
  }
@@ -141180,11 +141976,11 @@ function normalizeYandexRoi(value) {
141180
141976
  return r === -1 ? void 0 : r;
141181
141977
  }
141182
141978
  function asItems(payload) {
141183
- const obj = asRecord34(payload);
141979
+ const obj = asRecord35(payload);
141184
141980
  if (!obj) return [];
141185
141981
  const items3 = obj.items;
141186
141982
  if (!Array.isArray(items3)) return [];
141187
- return items3.filter((r) => asRecord34(r) !== null);
141983
+ return items3.filter((r) => asRecord35(r) !== null);
141188
141984
  }
141189
141985
  function pickMetrics2(row, extras = []) {
141190
141986
  const spend = num12(row.spend) ?? 0;
@@ -141320,7 +142116,7 @@ function aggregateDailyToWeekly(dailyRows) {
141320
142116
  });
141321
142117
  }
141322
142118
  function prepareYandexDailyPayload(payload) {
141323
- const obj = asRecord34(payload) ?? {};
142119
+ const obj = asRecord35(payload) ?? {};
141324
142120
  const items3 = asItems(obj).map((r) => {
141325
142121
  const date = normalizeYandexDailyDate(r.date);
141326
142122
  return date ? { ...r, date } : r;
@@ -141389,7 +142185,7 @@ function mapDeviceRows2(payload) {
141389
142185
  }
141390
142186
  async function mergeYandexAnalysisSnapshotIntoReport(payload, snapshotDir) {
141391
142187
  const absDir = path51.resolve(snapshotDir);
141392
- const metaAccountId = typeof asRecord34(payload.meta)?.accountId === "string" ? asRecord34(payload.meta)?.accountId : void 0;
142188
+ const metaAccountId = typeof asRecord35(payload.meta)?.accountId === "string" ? asRecord35(payload.meta)?.accountId : void 0;
141393
142189
  const manifest = await readManifest7(snapshotDir, metaAccountId);
141394
142190
  if (!manifest) {
141395
142191
  throw new Error(
@@ -141401,8 +142197,8 @@ async function mergeYandexAnalysisSnapshotIntoReport(payload, snapshotDir) {
141401
142197
  const data = await loadSectionPayload3(absDir, art.file);
141402
142198
  if (data != null) sectionMap.set(art.section, data);
141403
142199
  }
141404
- const overview = asRecord34(sectionMap.get("overview"));
141405
- const totals = asRecord34(overview?.totals);
142200
+ const overview = asRecord35(sectionMap.get("overview"));
142201
+ const totals = asRecord35(overview?.totals);
141406
142202
  const accountId = manifest.accountId ?? metaAccountId;
141407
142203
  const meta = { ...payload.meta ?? {} };
141408
142204
  if (!meta.accountId && accountId) meta.accountId = accountId;
@@ -141624,7 +142420,7 @@ function textLen7(value) {
141624
142420
  function asArray8(value) {
141625
142421
  return Array.isArray(value) ? value : [];
141626
142422
  }
141627
- function asRecord35(value) {
142423
+ function asRecord36(value) {
141628
142424
  if (value && typeof value === "object" && !Array.isArray(value)) {
141629
142425
  return value;
141630
142426
  }
@@ -141637,23 +142433,23 @@ function normKey(value) {
141637
142433
  return String(value ?? "").trim().toLowerCase();
141638
142434
  }
141639
142435
  function insightMatchRecord(item) {
141640
- const rec = asRecord35(item);
142436
+ const rec = asRecord36(item);
141641
142437
  if (!rec) return {};
141642
- return asRecord35(rec.match) ?? rec;
142438
+ return asRecord36(rec.match) ?? rec;
141643
142439
  }
141644
142440
  function findRowInsight(list, primaryField, primaryValue, row) {
141645
142441
  const target = normKey(primaryValue);
141646
142442
  if (!target) return null;
141647
142443
  const candidates = list.filter((it) => normKey(insightMatchRecord(it)[primaryField]) === target);
141648
- if (candidates.length <= 1) return asRecord35(candidates[0]);
142444
+ if (candidates.length <= 1) return asRecord36(candidates[0]);
141649
142445
  const campaign = normKey(row.campaignName);
141650
142446
  const narrowed = candidates.find(
141651
142447
  (it) => normKey(insightMatchRecord(it).campaignName) === campaign
141652
142448
  );
141653
- return asRecord35(narrowed ?? candidates[0]);
142449
+ return asRecord36(narrowed ?? candidates[0]);
141654
142450
  }
141655
142451
  function topRowsBySpend(rows, limit) {
141656
- return rows.map((r) => asRecord35(r)).filter((r) => r != null).sort((a, b) => (Number(b.spend) || 0) - (Number(a.spend) || 0)).slice(0, limit);
142452
+ return rows.map((r) => asRecord36(r)).filter((r) => r != null).sort((a, b) => (Number(b.spend) || 0) - (Number(a.spend) || 0)).slice(0, limit);
141657
142453
  }
141658
142454
  var ROW_INSIGHT_SPECS = [
141659
142455
  {
@@ -141668,17 +142464,17 @@ var ROW_INSIGHT_SPECS = [
141668
142464
  ];
141669
142465
  function validateYandexPeriodReportContent(data) {
141670
142466
  const missing = [];
141671
- const meta = asRecord35(data.meta) ?? {};
141672
- const narrative = asRecord35(data.narrative) ?? {};
141673
- const sections = asRecord35(narrative.sections) ?? {};
141674
- const kpis = asRecord35(data.kpis) ?? {};
142467
+ const meta = asRecord36(data.meta) ?? {};
142468
+ const narrative = asRecord36(data.narrative) ?? {};
142469
+ const sections = asRecord36(narrative.sections) ?? {};
142470
+ const kpis = asRecord36(data.kpis) ?? {};
141675
142471
  if (!textLen7(meta.accountId)) {
141676
142472
  pushMissing7(missing, "meta-account", "\u5143\u4FE1\u606F", "\u8D26\u6237 ID", "meta.accountId \u5FC5\u586B");
141677
142473
  }
141678
142474
  const sectionAnalysisCounts = {};
141679
142475
  const sectionSuggestionCounts = {};
141680
142476
  for (const key of SECTION_KEYS4) {
141681
- const section = asRecord35(sections[key]);
142477
+ const section = asRecord36(sections[key]);
141682
142478
  const analysis = asArray8(section?.analysis).filter((s) => textLen7(s) > 0);
141683
142479
  const suggestions = asArray8(section?.suggestions).filter((s) => textLen7(s) > 0);
141684
142480
  sectionAnalysisCounts[key] = analysis.length;
@@ -141704,7 +142500,7 @@ function validateYandexPeriodReportContent(data) {
141704
142500
  }
141705
142501
  const recommendations = asArray8(narrative.recommendations).filter((r) => {
141706
142502
  if (typeof r === "string") return textLen7(r) > 0;
141707
- const rec = asRecord35(r);
142503
+ const rec = asRecord36(r);
141708
142504
  return textLen7(rec?.content) > 0 || textLen7(rec?.text) > 0;
141709
142505
  });
141710
142506
  if (recommendations.length < 3) {
@@ -141726,8 +142522,8 @@ function validateYandexPeriodReportContent(data) {
141726
142522
  "\u81F3\u5C11\u4E00\u9879\u6709\u6548\u6570\u5B57\uFF08\u8BF7\u4F20 --snapshot-dir \u7531 CLI \u4ECE overview \u5408\u5E76\uFF09"
141727
142523
  );
141728
142524
  }
141729
- const tables = asRecord35(data.tables) ?? {};
141730
- const weeklyRows = asArray8(tables.weekly).map((r) => asRecord35(r)).filter((r) => r != null);
142525
+ const tables = asRecord36(data.tables) ?? {};
142526
+ const weeklyRows = asArray8(tables.weekly).map((r) => asRecord36(r)).filter((r) => r != null);
141731
142527
  for (const [i, row] of weeklyRows.entries()) {
141732
142528
  const label = `${row.weekLabel ?? ""} ${row.startDate ?? ""} ${row.endDate ?? ""}`;
141733
142529
  if (/nan/i.test(label) || !normalizeYandexDailyDate(row.startDate) || !normalizeYandexDailyDate(row.endDate)) {
@@ -141740,7 +142536,7 @@ function validateYandexPeriodReportContent(data) {
141740
142536
  );
141741
142537
  }
141742
142538
  }
141743
- const rowInsights = asRecord35(narrative.rowInsights) ?? {};
142539
+ const rowInsights = asRecord36(narrative.rowInsights) ?? {};
141744
142540
  const rowInsightCoverage = {};
141745
142541
  for (const spec of ROW_INSIGHT_SPECS) {
141746
142542
  const shown = topRowsBySpend(asArray8(tables[spec.tableKey]), spec.limit).filter(
@@ -141820,7 +142616,7 @@ async function readJsonFile8(filePath) {
141820
142616
  throw new Error(`\u65E0\u6CD5\u89E3\u6790 JSON\uFF1A${filePath}`);
141821
142617
  }
141822
142618
  }
141823
- function asRecord36(value) {
142619
+ function asRecord37(value) {
141824
142620
  if (value && typeof value === "object" && !Array.isArray(value)) {
141825
142621
  return value;
141826
142622
  }
@@ -141848,7 +142644,7 @@ function injectReportData7(html, payload) {
141848
142644
  }
141849
142645
  async function runYandexAnalysisRender(opts) {
141850
142646
  const dataPath = path53.resolve(opts.dataFile);
141851
- let data = asRecord36(await readJsonFile8(dataPath));
142647
+ let data = asRecord37(await readJsonFile8(dataPath));
141852
142648
  if (opts.snapshotDir?.trim()) {
141853
142649
  data = await mergeYandexAnalysisSnapshotIntoReport(data, path53.resolve(opts.snapshotDir));
141854
142650
  }
@@ -142044,7 +142840,7 @@ function unwrapYandexItems(raw) {
142044
142840
  }
142045
142841
  return [];
142046
142842
  }
142047
- function asRecord37(raw) {
142843
+ function asRecord38(raw) {
142048
142844
  return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
142049
142845
  }
142050
142846
 
@@ -142123,7 +142919,7 @@ async function runYandexAccountStatus(opts) {
142123
142919
  } catch (err) {
142124
142920
  fail3("\u67E5\u8BE2 Yandex \u8D26\u6237\u603B\u89C8\u5931\u8D25", err);
142125
142921
  }
142126
- const row = asRecord37(result.raw);
142922
+ const row = asRecord38(result.raw);
142127
142923
  await emitOrTable(opts, {
142128
142924
  section: "yandex-account-status",
142129
142925
  commandLabel: "yandex-analysis account-status",