siluzan-tso-cli 1.1.73-beta.2 → 1.1.73

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
@@ -258,9 +258,9 @@ var require_semver = __commonJS({
258
258
  } else {
259
259
  this.prerelease = m[4].split(".").map((id) => {
260
260
  if (/^[0-9]+$/.test(id)) {
261
- const num15 = +id;
262
- if (num15 >= 0 && num15 < MAX_SAFE_INTEGER) {
263
- return num15;
261
+ const num14 = +id;
262
+ if (num14 >= 0 && num14 < MAX_SAFE_INTEGER) {
263
+ return num14;
264
264
  }
265
265
  }
266
266
  return id;
@@ -3481,8 +3481,8 @@ function formatBeijingIsoTimestamp(d) {
3481
3481
  }
3482
3482
  return `${Y}-${M}-${D}T${h}:${m}:${s}.${ms}+08:00`;
3483
3483
  }
3484
- function addCalendarDaysToYmd(ymd2, deltaDays) {
3485
- const [y, mo, d] = ymd2.split("-").map(Number);
3484
+ function addCalendarDaysToYmd(ymd, deltaDays) {
3485
+ const [y, mo, d] = ymd.split("-").map(Number);
3486
3486
  const anchor = new Date(Date.UTC(y, mo - 1, d, 4, 0, 0));
3487
3487
  return formatBeijingYmd(new Date(anchor.getTime() + deltaDays * 864e5));
3488
3488
  }
@@ -4104,7 +4104,7 @@ var DEFAULT_API_BASE;
4104
4104
  var init_defaults = __esm({
4105
4105
  "src/config/defaults.ts"() {
4106
4106
  "use strict";
4107
- DEFAULT_API_BASE = "https://tso-api-ci.siluzan.com";
4107
+ DEFAULT_API_BASE = "https://tso-api.siluzan.com";
4108
4108
  }
4109
4109
  });
4110
4110
 
@@ -8093,9 +8093,9 @@ function sheetRelsXml(sheet) {
8093
8093
  return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${rels}</Relationships>`;
8094
8094
  }
8095
8095
  function estimateWrapHeight(text5, colWidthChars) {
8096
- const str4 = String(text5 ?? "");
8097
- if (!str4) return void 0;
8098
- const lines = str4.split("\n").reduce((sum, line) => {
8096
+ const str3 = String(text5 ?? "");
8097
+ if (!str3) return void 0;
8098
+ const lines = str3.split("\n").reduce((sum, line) => {
8099
8099
  const width = Math.max(colWidthChars || 20, 8);
8100
8100
  return sum + Math.max(1, Math.ceil(line.length / (width * 1.8)));
8101
8101
  }, 0);
@@ -8105,7 +8105,7 @@ function estimateWrapHeight(text5, colWidthChars) {
8105
8105
  function createExcelWorkbook(opts = {}) {
8106
8106
  return new ExcelWorkbookBuilder(opts);
8107
8107
  }
8108
- var PLATFORM_ACCENTS, NEUTRAL, FONT_NAME, NUM_FMT_PERCENT_2, StyleRegistry, SheetBuilder, ExcelWorkbookBuilder;
8108
+ var PLATFORM_ACCENTS, NEUTRAL, FONT_NAME, StyleRegistry, SheetBuilder, ExcelWorkbookBuilder;
8109
8109
  var init_xlsx_style_engine = __esm({
8110
8110
  "src/commands/facebook-analysis/xlsx-style-engine.ts"() {
8111
8111
  "use strict";
@@ -8130,7 +8130,6 @@ var init_xlsx_style_engine = __esm({
8130
8130
  white: "FFFFFF"
8131
8131
  };
8132
8132
  FONT_NAME = "\u5FAE\u8F6F\u96C5\u9ED1";
8133
- NUM_FMT_PERCENT_2 = 10;
8134
8133
  StyleRegistry = class {
8135
8134
  fonts = [{ size: 11, color: "000000", name: "\u5B8B\u4F53", bold: false }];
8136
8135
  fills = [{ kind: "none" }, { kind: "gray125" }];
@@ -8192,8 +8191,7 @@ var init_xlsx_style_engine = __esm({
8192
8191
  hAlign = "left",
8193
8192
  vAlign = "center",
8194
8193
  wrap = true,
8195
- forceText = false,
8196
- numFmtId = 0
8194
+ forceText = false
8197
8195
  } = opts;
8198
8196
  const fontId = this.fontId({ size: fontSize, color: fontColor, bold });
8199
8197
  const fillId = fill ? this.fillId(fill) : 0;
@@ -8202,7 +8200,7 @@ var init_xlsx_style_engine = __esm({
8202
8200
  fontId,
8203
8201
  fillId,
8204
8202
  borderId,
8205
- numFmtId: forceText ? 49 : numFmtId,
8203
+ numFmtId: forceText ? 49 : 0,
8206
8204
  align: { h: hAlign, v: vAlign, wrap }
8207
8205
  });
8208
8206
  }
@@ -8314,7 +8312,7 @@ var init_xlsx_style_engine = __esm({
8314
8312
  return this;
8315
8313
  }
8316
8314
  dataRow(cells, opts = {}) {
8317
- const { textColumns = [], centerColumns = [], labelColumns = [], percentColumns = [] } = opts;
8315
+ const { textColumns = [], centerColumns = [], labelColumns = [] } = opts;
8318
8316
  const shaded = this.zebra % 2 === 1;
8319
8317
  this.zebra += 1;
8320
8318
  const fill = shaded ? NEUTRAL.zebraFill : void 0;
@@ -8331,8 +8329,7 @@ var init_xlsx_style_engine = __esm({
8331
8329
  border: true,
8332
8330
  hAlign,
8333
8331
  vAlign: "top",
8334
- forceText,
8335
- numFmtId: percentColumns.includes(idx) && typeof value === "number" ? NUM_FMT_PERCENT_2 : 0
8332
+ forceText
8336
8333
  });
8337
8334
  const h = estimateWrapHeight(value, this.colWidths[idx]);
8338
8335
  if (h && (!maxHeight || h > maxHeight)) maxHeight = h;
@@ -105588,873 +105585,9 @@ var init_demand_gen_render = __esm({
105588
105585
  }
105589
105586
  });
105590
105587
 
105591
- // src/commands/google-analysis/merge-snapshot.ts
105588
+ // src/commands/google-analysis/okki-pmax-search-terms.ts
105592
105589
  import * as fs33 from "fs/promises";
105593
105590
  import * as path38 from "path";
105594
- function asRecord20(value) {
105595
- if (value && typeof value === "object" && !Array.isArray(value)) {
105596
- return value;
105597
- }
105598
- return null;
105599
- }
105600
- function num3(value) {
105601
- const n = Number(value);
105602
- return Number.isFinite(n) ? n : void 0;
105603
- }
105604
- function round23(value) {
105605
- return value == null ? void 0 : Math.round(value * 100) / 100;
105606
- }
105607
- async function readManifest(snapshotDir, accountId) {
105608
- const candidates = [];
105609
- if (accountId) candidates.push(googleAnalysisManifestFile(accountId));
105610
- try {
105611
- const entries = await fs33.readdir(snapshotDir);
105612
- const manifestNames = entries.filter((n) => n.startsWith("manifest") && n.endsWith(".json"));
105613
- for (const name2 of manifestNames) {
105614
- if (!candidates.includes(name2)) candidates.push(name2);
105615
- }
105616
- } catch {
105617
- }
105618
- for (const name2 of candidates) {
105619
- try {
105620
- const raw = await fs33.readFile(path38.join(snapshotDir, name2), "utf8");
105621
- const parsed = JSON.parse(raw);
105622
- if (Array.isArray(parsed.artifacts) && parsed.artifacts.length > 0) return parsed;
105623
- } catch {
105624
- }
105625
- }
105626
- return null;
105627
- }
105628
- async function loadSectionFile(snapshotDir, file) {
105629
- try {
105630
- const raw = await fs33.readFile(path38.join(snapshotDir, file), "utf8");
105631
- const parsed = JSON.parse(raw);
105632
- if (parsed && typeof parsed === "object") return parsed;
105633
- return null;
105634
- } catch {
105635
- return null;
105636
- }
105637
- }
105638
- function negativeKeywordText(row) {
105639
- const text5 = row.keywordText;
105640
- if (Array.isArray(text5)) {
105641
- const parts = text5.map((part) => String(part).trim()).filter(Boolean);
105642
- if (parts.length > 0) return parts.join(", ");
105643
- }
105644
- if (typeof text5 === "string" && text5.trim()) return text5.trim();
105645
- if (typeof row.keyword === "string" && row.keyword.trim()) return row.keyword.trim();
105646
- return "\u2014";
105647
- }
105648
- function mapNegativeKeywordRows(rows) {
105649
- const seen = /* @__PURE__ */ new Set();
105650
- const mapped = [];
105651
- for (const row of rows) {
105652
- const id = row.id == null ? "" : String(row.id);
105653
- if (id && seen.has(id)) continue;
105654
- if (id) seen.add(id);
105655
- const level = String(row.negativeLevel ?? "").trim();
105656
- const campaignId = String(row.campaignId ?? "").trim();
105657
- const adGroupId = String(row.adGroupId ?? "").trim();
105658
- const campaignName = String(row.campaignName ?? "").trim();
105659
- const adGroupName = String(row.adGroupName ?? "").trim();
105660
- mapped.push({
105661
- keyword: negativeKeywordText(row),
105662
- matchType: String(row.matchTypeV2 ?? row.matchType ?? "\u2014"),
105663
- level: level || "\u2014",
105664
- levelZh: NEGATIVE_LEVEL_ZH[level] ?? (level || "\u2014"),
105665
- campaignId: campaignId || "\u2014",
105666
- adGroupId: adGroupId || "\u2014",
105667
- campaignName: campaignName || "\u2014",
105668
- adGroupName: adGroupName || "\u2014"
105669
- });
105670
- }
105671
- return mapped;
105672
- }
105673
- function dateTagFromRange(dateRange) {
105674
- if (!dateRange || dateRange.mode !== "range") return void 0;
105675
- return `${dateRange.start.replace(/-/g, "")}-${dateRange.end.replace(/-/g, "")}`;
105676
- }
105677
- function dateTagFromMeta(meta) {
105678
- const start = typeof meta?.startDate === "string" ? meta.startDate : "";
105679
- const end = typeof meta?.endDate === "string" ? meta.endDate : "";
105680
- if (!/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) return void 0;
105681
- return `${start.replace(/-/g, "")}-${end.replace(/-/g, "")}`;
105682
- }
105683
- function pickSectionSnapshotFile(files, section, accountId, preferredDateTag) {
105684
- const escapedSection = section.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
105685
- const escapedId = accountId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
105686
- const re = new RegExp(`^${escapedSection}-${escapedId}(?:_(\\d{8}-\\d{8}))?\\.json$`);
105687
- const matches = files.filter((f) => re.test(f));
105688
- if (matches.length === 0) return null;
105689
- if (preferredDateTag) {
105690
- const preferred = matches.find((f) => f.endsWith(`_${preferredDateTag}.json`));
105691
- if (preferred) return preferred;
105692
- }
105693
- return [...matches].sort().at(-1) ?? null;
105694
- }
105695
- async function recoverMissingReportSections(sectionMap, absDir, accountId, preferredDateTag) {
105696
- if (!accountId) return;
105697
- let entries;
105698
- try {
105699
- entries = await fs33.readdir(absDir);
105700
- } catch {
105701
- return;
105702
- }
105703
- for (const section of REPORT_MERGE_SECTIONS) {
105704
- if (sectionMap.has(section)) continue;
105705
- const file = pickSectionSnapshotFile(entries, section, accountId, preferredDateTag);
105706
- if (!file) continue;
105707
- const data = await loadSectionFile(absDir, file);
105708
- if (data) sectionMap.set(section, data);
105709
- }
105710
- }
105711
- function periodMetricsFromRow(row) {
105712
- if (!row) return null;
105713
- return {
105714
- cost: num3(row.spend),
105715
- impressions: num3(row.impressions),
105716
- clicks: num3(row.clicks),
105717
- conversions: num3(row.conversions),
105718
- ctr: num3(row.ctr),
105719
- averageCpc: num3(row.averageCpc),
105720
- costPerConversion: num3(row.costPerConversion)
105721
- };
105722
- }
105723
- function items(envelope) {
105724
- if (!envelope || !Array.isArray(envelope.items)) return [];
105725
- return envelope.items.filter((row) => asRecord20(row) !== null);
105726
- }
105727
- function record(envelope) {
105728
- return envelope?.record ?? null;
105729
- }
105730
- function pickMetricRow(row, extraFields) {
105731
- const base2 = {
105732
- spend: num3(row.spend) ?? 0,
105733
- impressions: num3(row.impressions) ?? 0,
105734
- clicks: num3(row.clicks) ?? 0,
105735
- ctr: num3(row.ctr),
105736
- averageCpc: num3(row.averageCpc),
105737
- conversions: num3(row.conversions) ?? 0,
105738
- costPerConversion: num3(row.costPerConversion)
105739
- };
105740
- for (const f of extraFields) {
105741
- if (row[f] !== void 0) base2[f] = row[f];
105742
- }
105743
- return base2;
105744
- }
105745
- function sumCampaignRowsToPeriodKpis(rows) {
105746
- if (rows.length === 0) return null;
105747
- let cost = 0;
105748
- let impressions = 0;
105749
- let clicks = 0;
105750
- let conversions = 0;
105751
- for (const row of rows) {
105752
- cost += num3(row.spend) ?? 0;
105753
- impressions += num3(row.impressions) ?? 0;
105754
- clicks += num3(row.clicks) ?? 0;
105755
- conversions += num3(row.conversions) ?? 0;
105756
- }
105757
- const ctr = impressions > 0 ? clicks / impressions : void 0;
105758
- const averageCpc = clicks > 0 ? cost / clicks : void 0;
105759
- const costPerConversion = conversions > 0 ? cost / conversions : void 0;
105760
- return {
105761
- cost: round23(cost),
105762
- impressions: Math.round(impressions),
105763
- clicks: Math.round(clicks),
105764
- conversions: round23(conversions),
105765
- ctr,
105766
- averageCpc: round23(averageCpc),
105767
- costPerConversion: round23(costPerConversion)
105768
- };
105769
- }
105770
- async function mergeGoogleAnalysisSnapshotIntoReport(payload, snapshotDir) {
105771
- const absDir = path38.resolve(snapshotDir);
105772
- const metaAccountId = typeof asRecord20(payload.meta)?.accountId === "string" ? asRecord20(payload.meta)?.accountId : void 0;
105773
- const manifest = await readManifest(snapshotDir, metaAccountId);
105774
- if (!manifest) {
105775
- throw new Error(`\u672A\u5728 ${absDir} \u627E\u5230 manifest*.json\uFF0C\u8BF7\u5148\u6267\u884C google-analysis --json-out`);
105776
- }
105777
- const accountId = manifest.googleAnalysis?.accountId ?? metaAccountId;
105778
- const dateRange = manifest.googleAnalysis?.dateRange;
105779
- const preferredDateTag = dateTagFromRange(dateRange) ?? dateTagFromMeta(asRecord20(payload.meta) ?? void 0);
105780
- const sectionMap = /* @__PURE__ */ new Map();
105781
- for (const art of manifest.artifacts ?? []) {
105782
- const data = await loadSectionFile(absDir, art.file);
105783
- if (data) sectionMap.set(art.section, data);
105784
- }
105785
- await recoverMissingReportSections(sectionMap, absDir, accountId, preferredDateTag);
105786
- const overviewRecord = record(sectionMap.get("overview"));
105787
- const currentPeriod = asRecord20(overviewRecord?.currentPeriod);
105788
- const previousPeriod = asRecord20(overviewRecord?.previousPeriod);
105789
- const meta = { ...payload.meta ?? {} };
105790
- if (!meta.accountId && accountId) meta.accountId = accountId;
105791
- if (!meta.currency) {
105792
- const currency = overviewRecord?.currencyCode ?? currentPeriod?.currencyCode;
105793
- if (typeof currency === "string" && currency) meta.currency = currency;
105794
- }
105795
- if (!meta.startDate && dateRange && dateRange.mode === "range") meta.startDate = dateRange.start;
105796
- if (!meta.endDate && dateRange && dateRange.mode === "range") meta.endDate = dateRange.end;
105797
- if (!meta.generatedAt) meta.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
105798
- const campaignRows3 = items(sectionMap.get("campaigns"));
105799
- const campaignKpis = sumCampaignRowsToPeriodKpis(campaignRows3);
105800
- const dimensionSummaryRecord = record(sectionMap.get("dimension-summary"));
105801
- const kpis = { ...payload.kpis ?? {} };
105802
- const currentKpiSource = campaignKpis ?? periodMetricsFromRow(currentPeriod) ?? periodMetricsFromRow(dimensionSummaryRecord);
105803
- if (currentKpiSource) {
105804
- if (currentKpiSource.cost != null) kpis.cost = currentKpiSource.cost;
105805
- if (currentKpiSource.impressions != null) kpis.impressions = currentKpiSource.impressions;
105806
- if (currentKpiSource.clicks != null) kpis.clicks = currentKpiSource.clicks;
105807
- if (currentKpiSource.conversions != null) kpis.conversions = currentKpiSource.conversions;
105808
- if (currentKpiSource.ctr != null) kpis.ctr = currentKpiSource.ctr;
105809
- if (currentKpiSource.averageCpc != null) kpis.averageCpc = currentKpiSource.averageCpc;
105810
- if (currentKpiSource.costPerConversion != null) {
105811
- kpis.costPerConversion = currentKpiSource.costPerConversion;
105812
- }
105813
- }
105814
- if (overviewRecord) {
105815
- const activeDays = num3(overviewRecord.activeDays);
105816
- if (activeDays != null) kpis.activeDays = Math.round(activeDays);
105817
- const averageDailyCost = num3(overviewRecord.averageDailyCost);
105818
- if (averageDailyCost != null) kpis.averageDailyCost = round23(averageDailyCost);
105819
- }
105820
- if (previousPeriod) {
105821
- kpis.previousPeriod = {
105822
- cost: num3(previousPeriod.spend),
105823
- impressions: num3(previousPeriod.impressions),
105824
- clicks: num3(previousPeriod.clicks),
105825
- conversions: num3(previousPeriod.conversions),
105826
- ctr: num3(previousPeriod.ctr),
105827
- averageCpc: num3(previousPeriod.averageCpc),
105828
- costPerConversion: num3(previousPeriod.costPerConversion)
105829
- };
105830
- }
105831
- const charts = { ...payload.charts ?? {} };
105832
- {
105833
- const dailyRows = items(sectionMap.get("daily-metrics"));
105834
- if (dailyRows.length > 0) {
105835
- const sorted = [...dailyRows].sort(
105836
- (a, b) => String(a.date ?? "").localeCompare(String(b.date ?? ""))
105837
- );
105838
- charts.dailyTrend = {
105839
- dates: sorted.map((r) => String(r.date ?? "\u2014")),
105840
- cost: sorted.map((r) => round23(num3(r.spend)) ?? 0),
105841
- conversions: sorted.map((r) => Math.round(num3(r.conversions) ?? 0)),
105842
- conversionsValue: sorted.map((r) => round23(num3(r.conversionsValue)) ?? 0),
105843
- cpa: sorted.map((r) => round23(num3(r.costPerConversion)) ?? 0)
105844
- };
105845
- }
105846
- }
105847
- const tables = { ...payload.tables ?? {} };
105848
- if (dimensionSummaryRecord) {
105849
- tables.dimensionSummary = {
105850
- cost: num3(dimensionSummaryRecord.spend),
105851
- impressions: num3(dimensionSummaryRecord.impressions),
105852
- clicks: num3(dimensionSummaryRecord.clicks),
105853
- conversions: num3(dimensionSummaryRecord.conversions),
105854
- ctr: num3(dimensionSummaryRecord.ctr),
105855
- averageCpc: num3(dimensionSummaryRecord.averageCpc),
105856
- costPerConversion: num3(dimensionSummaryRecord.costPerConversion),
105857
- searchImpressionShare: num3(dimensionSummaryRecord.searchImpressionShare),
105858
- searchBudgetLostImpressionShare: num3(dimensionSummaryRecord.searchBudgetLostImpressionShare),
105859
- searchRankLostImpressionShare: num3(dimensionSummaryRecord.searchRankLostImpressionShare)
105860
- };
105861
- }
105862
- if (campaignRows3.length > 0) {
105863
- tables.campaigns = campaignRows3.map((r) => ({
105864
- ...pickMetricRow(r, ["campaignName", "campaignStatusDisplay", "channelTypeV2"]),
105865
- budgetAmountYuan: r.budgetAmountYuan ?? null
105866
- }));
105867
- }
105868
- {
105869
- const rows = items(sectionMap.get("devices"));
105870
- if (rows.length > 0) {
105871
- tables.devices = rows.map((r) => pickMetricRow(r, ["deviceType", "conversionsValue"]));
105872
- }
105873
- }
105874
- {
105875
- const rows = items(sectionMap.get("geographic"));
105876
- if (rows.length > 0) {
105877
- tables.geographic = rows.map(
105878
- (r) => pickMetricRow(r, [
105879
- "countryOrRegion",
105880
- "countryOrRegionZh",
105881
- "countryNameZh",
105882
- "conversionsValue"
105883
- ])
105884
- );
105885
- }
105886
- }
105887
- {
105888
- const rows = items(sectionMap.get("audience"));
105889
- if (rows.length > 0) {
105890
- tables.audience = rows.map((r) => {
105891
- const mapped = pickMetricRow(r, [
105892
- "audience",
105893
- "audienceName",
105894
- "audienceType",
105895
- "campaignName"
105896
- ]);
105897
- if (mapped.audience == null && mapped.audienceName != null) {
105898
- mapped.audience = mapped.audienceName;
105899
- }
105900
- return mapped;
105901
- });
105902
- }
105903
- }
105904
- {
105905
- const rows = items(sectionMap.get("keywords"));
105906
- if (rows.length > 0) {
105907
- tables.keywords = rows.map(
105908
- (r) => pickMetricRow(r, ["keyword", "keywordMatchType", "keywordMatchTypeZh", "campaignName"])
105909
- );
105910
- }
105911
- }
105912
- if (sectionMap.has("negative-keywords")) {
105913
- tables.negativeKeywords = mapNegativeKeywordRows(items(sectionMap.get("negative-keywords")));
105914
- }
105915
- return {
105916
- ...payload,
105917
- meta,
105918
- kpis,
105919
- charts,
105920
- tables
105921
- };
105922
- }
105923
- var REPORT_MERGE_SECTIONS, NEGATIVE_LEVEL_ZH;
105924
- var init_merge_snapshot = __esm({
105925
- "src/commands/google-analysis/merge-snapshot.ts"() {
105926
- "use strict";
105927
- init_google_analysis();
105928
- REPORT_MERGE_SECTIONS = [
105929
- "overview",
105930
- "daily-metrics",
105931
- "dimension-summary",
105932
- "campaigns",
105933
- "devices",
105934
- "geographic",
105935
- "audience",
105936
- "keywords",
105937
- "negative-keywords"
105938
- ];
105939
- NEGATIVE_LEVEL_ZH = {
105940
- Account: "\u8D26\u6237",
105941
- Campaign: "\u7CFB\u5217",
105942
- AdGroup: "\u5E7F\u544A\u7EC4",
105943
- "Ad group": "\u5E7F\u544A\u7EC4"
105944
- };
105945
- }
105946
- });
105947
-
105948
- // src/commands/google-analysis/daily-report-excel.ts
105949
- function num4(value) {
105950
- const n = typeof value === "number" ? value : Number(value);
105951
- return Number.isFinite(n) ? n : 0;
105952
- }
105953
- function round24(value) {
105954
- return Math.round(value * 100) / 100;
105955
- }
105956
- function round4(value) {
105957
- return Math.round(value * 1e4) / 1e4;
105958
- }
105959
- function str(value, fallback = DASH) {
105960
- if (typeof value === "string" && value.trim()) return value.trim();
105961
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
105962
- return fallback;
105963
- }
105964
- function ymd(value) {
105965
- const m = typeof value === "string" ? /^(\d{4}-\d{2}-\d{2})/.exec(value) : null;
105966
- return m ? m[1] : "";
105967
- }
105968
- function channelTypeZh(row) {
105969
- const raw = str(row.channelTypeV2 ?? row.channelType, "").toUpperCase();
105970
- return CHANNEL_TYPE_ZH[raw] ?? (raw || DASH);
105971
- }
105972
- function competitive(row) {
105973
- const cm = row.competitiveMetrics;
105974
- return cm && typeof cm === "object" ? cm : {};
105975
- }
105976
- function optionalShare(value) {
105977
- if (value == null || value === "") return void 0;
105978
- const n = Number(value);
105979
- return Number.isFinite(n) ? n : void 0;
105980
- }
105981
- function campaignShares(row) {
105982
- const cm = competitive(row);
105983
- return {
105984
- impressionShare: optionalShare(cm.searchImpressionShare ?? row.searchImpressionShare),
105985
- absTop: optionalShare(cm.searchAbsoluteTopImpressionShare),
105986
- top: optionalShare(cm.searchTopImpressionShare)
105987
- };
105988
- }
105989
- function emptyTotals() {
105990
- return {
105991
- clicks: 0,
105992
- impressions: 0,
105993
- spend: 0,
105994
- conversions: 0,
105995
- shareWeight: 0,
105996
- absTopWeighted: 0,
105997
- topWeighted: 0
105998
- };
105999
- }
106000
- function addRow(t, row, withShares) {
106001
- const impressions = num4(row.impressions);
106002
- t.clicks += num4(row.clicks);
106003
- t.impressions += impressions;
106004
- t.spend += num4(row.spend);
106005
- t.conversions += num4(row.conversions);
106006
- if (!withShares || impressions <= 0) return;
106007
- const s = campaignShares(row);
106008
- if (s.absTop === void 0 || s.top === void 0) return;
106009
- const weight = s.impressionShare && s.impressionShare > 0 ? impressions / s.impressionShare : impressions;
106010
- t.shareWeight += weight;
106011
- t.absTopWeighted += s.absTop * weight;
106012
- t.topWeighted += s.top * weight;
106013
- }
106014
- function sumRows(rows, withShares) {
106015
- const t = emptyTotals();
106016
- for (const row of rows) addRow(t, row, withShares && channelTypeZh(row) === "\u641C\u7D22");
106017
- return t;
106018
- }
106019
- function metricCells(t, currency, shares) {
106020
- const cells = [
106021
- Math.round(t.clicks),
106022
- Math.round(t.impressions),
106023
- t.impressions > 0 ? round4(t.clicks / t.impressions) : 0,
106024
- currency,
106025
- t.clicks > 0 ? round24(t.spend / t.clicks) : 0,
106026
- round24(t.spend)
106027
- ];
106028
- if (shares === "aggregate") {
106029
- cells.push(
106030
- t.shareWeight > 0 ? round4(t.absTopWeighted / t.shareWeight) : DASH,
106031
- t.shareWeight > 0 ? round4(t.topWeighted / t.shareWeight) : DASH
106032
- );
106033
- }
106034
- cells.push(
106035
- round24(t.conversions),
106036
- t.conversions > 0 ? round24(t.spend / t.conversions) : 0,
106037
- t.clicks > 0 ? round4(t.conversions / t.clicks) : 0
106038
- );
106039
- return cells;
106040
- }
106041
- function campaignRowCells(row, currency) {
106042
- const t = sumRows([row], false);
106043
- const cells = metricCells(t, currency, "none");
106044
- const s = channelTypeZh(row) === "\u641C\u7D22" ? campaignShares(row) : {};
106045
- cells.splice(
106046
- 6,
106047
- 0,
106048
- s.absTop === void 0 ? DASH : round4(s.absTop),
106049
- s.top === void 0 ? DASH : round4(s.top)
106050
- );
106051
- return cells;
106052
- }
106053
- function shift(cols, by) {
106054
- return cols.map((c) => c + by);
106055
- }
106056
- function bySpendDesc(a, b) {
106057
- return num4(b.spend) - num4(a.spend);
106058
- }
106059
- function byDateDescThenSpend(a, b) {
106060
- const d = ymd(b.date).localeCompare(ymd(a.date));
106061
- return d !== 0 ? d : bySpendDesc(a, b);
106062
- }
106063
- function groupBy(rows, key) {
106064
- const map = /* @__PURE__ */ new Map();
106065
- for (const row of rows) {
106066
- const k = key(row);
106067
- const list = map.get(k);
106068
- if (list) list.push(row);
106069
- else map.set(k, [row]);
106070
- }
106071
- return map;
106072
- }
106073
- function hasVolume(row) {
106074
- return num4(row.impressions) > 0 || num4(row.clicks) > 0 || num4(row.spend) > 0;
106075
- }
106076
- function formatGoogleCustomerId(id) {
106077
- const digits = id.replace(/\D/g, "");
106078
- return digits.length === 10 ? `${digits.slice(0, 3)}-${digits.slice(3, 6)}-${digits.slice(6)}` : id;
106079
- }
106080
- function buildDailyReportDrafts(input) {
106081
- const { currency } = input;
106082
- const range = `${input.startDate.replace(/-/g, "/")} \u2013 ${input.endDate.replace(/-/g, "/")}`;
106083
- const subtitle = `\u8D26\u6237ID ${formatGoogleCustomerId(input.accountId)}\uFF5C\u7EDF\u8BA1\u533A\u95F4 ${range}\uFF5C\u5E01\u79CD ${currency}`;
106084
- const title = input.title?.trim() || "Google Ads \u6295\u653E\u65E5\u62A5";
106085
- const campaigns = input.campaigns.filter(hasVolume);
106086
- const campaignsDaily = [...campaigns].sort(byDateDescThenSpend);
106087
- const keywords = input.keywords.filter(hasVolume).sort(byDateDescThenSpend);
106088
- const searchTerms = input.searchTerms.filter(hasVolume).sort(byDateDescThenSpend);
106089
- const byType = groupBy(campaigns, channelTypeZh);
106090
- const typeOrder = [...byType.entries()].sort((a, b) => sumRows(b[1], false).spend - sumRows(a[1], false).spend).map(([type]) => type);
106091
- const byDate = groupBy(campaigns, (r) => ymd(r.date));
106092
- const days = [...byDate.keys()].sort().reverse();
106093
- const typeTotalRows = typeOrder.map((type) => [
106094
- type,
106095
- ...metricCells(sumRows(byType.get(type) ?? [], true), currency, "aggregate")
106096
- ]);
106097
- typeTotalRows.push(["\u5408\u8BA1", ...metricCells(sumRows(campaigns, true), currency, "aggregate")]);
106098
- const typeDailyRows = [];
106099
- for (const day of days) {
106100
- const dayRows = byDate.get(day) ?? [];
106101
- const dayTypes = groupBy(dayRows, channelTypeZh);
106102
- for (const type of typeOrder) {
106103
- const rows = dayTypes.get(type);
106104
- if (!rows?.length) continue;
106105
- typeDailyRows.push([day, type, ...metricCells(sumRows(rows, true), currency, "aggregate")]);
106106
- }
106107
- }
106108
- const accountDailyRows = days.map((day) => [
106109
- day,
106110
- ...metricCells(sumRows(byDate.get(day) ?? [], true), currency, "aggregate")
106111
- ]);
106112
- const campaignDailyRows = campaignsDaily.map((row) => [
106113
- ymd(row.date),
106114
- str(row.campaignName),
106115
- channelTypeZh(row),
106116
- str(row.campaignStatusDisplay),
106117
- ...campaignRowCells(row, currency)
106118
- ]);
106119
- const byCampaign = groupBy(campaigns, (r) => str(r.campaignId, str(r.campaignName)));
106120
- const campaignTotalRows = [...byCampaign.values()].map((rows) => ({ rows, totals: sumRows(rows, true) })).sort((a, b) => b.totals.spend - a.totals.spend).map(({ rows, totals }) => {
106121
- const latest = [...rows].sort(byDateDescThenSpend)[0];
106122
- return [
106123
- str(latest.campaignName),
106124
- channelTypeZh(latest),
106125
- str(latest.campaignStatusDisplay),
106126
- ...metricCells(totals, currency, "aggregate")
106127
- ];
106128
- });
106129
- campaignTotalRows.push([
106130
- "\u5408\u8BA1",
106131
- DASH,
106132
- DASH,
106133
- ...metricCells(sumRows(campaigns, true), currency, "aggregate")
106134
- ]);
106135
- const searchTermRows2 = searchTerms.map((row) => [
106136
- ymd(row.date),
106137
- str(row.searchTermText),
106138
- str(row.matchTypeZh ?? row.matchType),
106139
- str(row.keywordText),
106140
- str(row.queryTargetingStatusZh ?? row.queryTargetingStatus),
106141
- str(row.campaignName),
106142
- str(row.adGroupName),
106143
- ...metricCells(sumRows([row], false), currency, "none")
106144
- ]);
106145
- const keywordRows2 = keywords.map((row) => [
106146
- ymd(row.date),
106147
- str(row.campaignName),
106148
- str(row.adGroupName),
106149
- str(row.keyword),
106150
- str(row.keywordMatchTypeZh ?? row.keywordMatchType),
106151
- ...metricCells(sumRows([row], false), currency, "none")
106152
- ]);
106153
- const metricWidths = [10, 11, 9, 9, 16, 11, 16, 13, 10, 13, 9];
106154
- const metricWidthsNoShare = [10, 11, 9, 9, 16, 11, 10, 13, 9];
106155
- return [
106156
- {
106157
- name: "\u8D26\u6237\u6982\u89C8",
106158
- title,
106159
- subtitle,
106160
- colWidths: [12, 12, ...metricWidths],
106161
- notes: [],
106162
- tables: [
106163
- {
106164
- heading: "\u4E00\u3001\u672C\u671F\u6309\u5E7F\u544A\u7CFB\u5217\u7C7B\u578B\u6C47\u603B",
106165
- headers: ["\u5E7F\u544A\u7CFB\u5217\u7C7B\u578B", ...METRIC_HEADERS_WITH_SHARE],
106166
- rows: typeTotalRows,
106167
- percentColumns: shift(PERCENT_WITH_SHARE, 1)
106168
- },
106169
- {
106170
- heading: "\u4E8C\u3001\u6BCF\u65E5\u6309\u5E7F\u544A\u7CFB\u5217\u7C7B\u578B\u6C47\u603B",
106171
- headers: ["\u5929", "\u5E7F\u544A\u7CFB\u5217\u7C7B\u578B", ...METRIC_HEADERS_WITH_SHARE],
106172
- rows: typeDailyRows,
106173
- percentColumns: shift(PERCENT_WITH_SHARE, 2)
106174
- }
106175
- ]
106176
- },
106177
- {
106178
- name: "\u6BCF\u65E5\u6570\u636E",
106179
- title: `\u65E5\u6570\u636E\uFF08${range}\uFF09`,
106180
- subtitle,
106181
- colWidths: [12, 30, ...metricWidths],
106182
- notes: [],
106183
- tables: [
106184
- {
106185
- heading: "\u4E00\u3001\u8D26\u6237\u6BCF\u65E5",
106186
- headers: ["\u5929", ...METRIC_HEADERS_WITH_SHARE],
106187
- rows: accountDailyRows,
106188
- percentColumns: shift(PERCENT_WITH_SHARE, 1)
106189
- },
106190
- {
106191
- heading: "\u4E8C\u3001\u6BCF\u65E5 \xD7 \u5E7F\u544A\u7CFB\u5217",
106192
- headers: ["\u5929", "\u5E7F\u544A\u7CFB\u5217", ...METRIC_HEADERS_WITH_SHARE],
106193
- rows: campaignsDaily.map((row) => [
106194
- ymd(row.date),
106195
- str(row.campaignName),
106196
- ...campaignRowCells(row, currency)
106197
- ]),
106198
- percentColumns: shift(PERCENT_WITH_SHARE, 2)
106199
- }
106200
- ]
106201
- },
106202
- {
106203
- name: "\u5206\u8BA1\u5212\u6570\u636E",
106204
- title: `\u5206\u5E7F\u544A\u7CFB\u5217\u6570\u636E\uFF08${range}\uFF09`,
106205
- subtitle,
106206
- colWidths: [26, 30, 12, 10, ...metricWidths],
106207
- notes: [],
106208
- tables: [
106209
- {
106210
- heading: "\u4E00\u3001\u672C\u671F\u6309\u5E7F\u544A\u7CFB\u5217\u6C47\u603B",
106211
- headers: ["\u5E7F\u544A\u7CFB\u5217", "\u5E7F\u544A\u7CFB\u5217\u7C7B\u578B", "\u5E7F\u544A\u7CFB\u5217\u72B6\u6001", ...METRIC_HEADERS_WITH_SHARE],
106212
- rows: campaignTotalRows,
106213
- percentColumns: shift(PERCENT_WITH_SHARE, 3)
106214
- },
106215
- {
106216
- heading: "\u4E8C\u3001\u6BCF\u65E5 \xD7 \u5E7F\u544A\u7CFB\u5217",
106217
- headers: ["\u5929", "\u5E7F\u544A\u7CFB\u5217", "\u5E7F\u544A\u7CFB\u5217\u7C7B\u578B", "\u5E7F\u544A\u7CFB\u5217\u72B6\u6001", ...METRIC_HEADERS_WITH_SHARE],
106218
- rows: campaignDailyRows,
106219
- percentColumns: shift(PERCENT_WITH_SHARE, 4)
106220
- }
106221
- ]
106222
- },
106223
- {
106224
- name: "\u641C\u7D22\u5B57\u8BCD\u62A5\u544A",
106225
- title: `\u641C\u7D22\u5B57\u8BCD\uFF08${range}\uFF09`,
106226
- subtitle,
106227
- colWidths: [12, 28, 12, 24, 12, 26, 20, ...metricWidthsNoShare],
106228
- notes: input.note?.trim() ? [input.note.trim()] : [],
106229
- tables: [
106230
- {
106231
- heading: "\u6BCF\u65E5 \xD7 \u641C\u7D22\u5B57\u8BCD",
106232
- headers: [
106233
- "\u5929",
106234
- "\u641C\u7D22\u5B57\u8BCD",
106235
- "\u5339\u914D\u7C7B\u578B",
106236
- "\u641C\u7D22\u5E7F\u544A\u5173\u952E\u5B57",
106237
- "\u5DF2\u6DFB\u52A0/\u5DF2\u6392\u9664",
106238
- "\u5E7F\u544A\u7CFB\u5217",
106239
- "\u5E7F\u544A\u7EC4",
106240
- ...METRIC_HEADERS
106241
- ],
106242
- rows: searchTermRows2,
106243
- percentColumns: shift(PERCENT_NO_SHARE, 7)
106244
- }
106245
- ]
106246
- },
106247
- {
106248
- name: "\u5173\u952E\u8BCD",
106249
- title: `\u5173\u952E\u8BCD\uFF08${range}\uFF09`,
106250
- subtitle,
106251
- colWidths: [12, 26, 20, 24, 12, ...metricWidthsNoShare],
106252
- notes: [],
106253
- tables: [
106254
- {
106255
- heading: "\u6BCF\u65E5 \xD7 \u5173\u952E\u8BCD",
106256
- headers: ["\u5929", "\u5E7F\u544A\u7CFB\u5217", "\u5E7F\u544A\u7EC4", "\u641C\u7D22\u5E7F\u544A\u5173\u952E\u5B57", "\u5339\u914D\u7C7B\u578B", ...METRIC_HEADERS],
106257
- rows: keywordRows2,
106258
- percentColumns: shift(PERCENT_NO_SHARE, 5)
106259
- }
106260
- ]
106261
- }
106262
- ];
106263
- }
106264
- function writeDailyReportExcel(outPath, input) {
106265
- const wb = createExcelWorkbook({ accent: "google" });
106266
- for (const draft of buildDailyReportDrafts(input)) {
106267
- const sheet = wb.addSheet(draft.name);
106268
- const span = Math.max(...draft.tables.map((t) => t.headers.length));
106269
- sheet.setColWidths(draft.colWidths);
106270
- sheet.titleBar(draft.title, { span });
106271
- sheet.subtitleBar(draft.subtitle, { span });
106272
- if (draft.notes.length) {
106273
- sheet.blankRow();
106274
- sheet.sectionBar("\u4F18\u5316\u52A8\u4F5C", { span });
106275
- for (const line of draft.notes) sheet.noteRow(line, span);
106276
- }
106277
- for (const table of draft.tables) {
106278
- sheet.blankRow();
106279
- sheet.sectionBar(table.heading, { span });
106280
- sheet.tableHeader(table.headers);
106281
- for (const row of table.rows) {
106282
- sheet.dataRow(row, { percentColumns: table.percentColumns });
106283
- }
106284
- }
106285
- }
106286
- return wb.writeFile(outPath);
106287
- }
106288
- var DASH, CHANNEL_TYPE_ZH, METRIC_HEADERS_WITH_SHARE, METRIC_HEADERS, PERCENT_WITH_SHARE, PERCENT_NO_SHARE;
106289
- var init_daily_report_excel = __esm({
106290
- "src/commands/google-analysis/daily-report-excel.ts"() {
106291
- "use strict";
106292
- init_xlsx_style_engine();
106293
- DASH = "\u2014";
106294
- CHANNEL_TYPE_ZH = {
106295
- SEARCH: "\u641C\u7D22",
106296
- DEMAND_GEN: "\u9700\u6C42\u5F00\u53D1",
106297
- DISCOVERY: "\u53D1\u73B0",
106298
- PERFORMANCE_MAX: "\u6548\u679C\u6700\u5927\u5316",
106299
- DISPLAY: "\u5C55\u793A",
106300
- VIDEO: "\u89C6\u9891",
106301
- SHOPPING: "\u8D2D\u7269",
106302
- MULTI_CHANNEL: "\u5E94\u7528",
106303
- SMART: "\u667A\u80FD",
106304
- LOCAL: "\u672C\u5730",
106305
- LOCAL_SERVICES: "\u672C\u5730\u670D\u52A1",
106306
- HOTEL: "\u9152\u5E97",
106307
- TRAVEL: "\u65C5\u6E38"
106308
- };
106309
- METRIC_HEADERS_WITH_SHARE = [
106310
- "\u70B9\u51FB\u6B21\u6570",
106311
- "\u5C55\u793A\u6B21\u6570",
106312
- "\u70B9\u51FB\u7387",
106313
- "\u8D27\u5E01\u4EE3\u7801",
106314
- "\u5E73\u5747\u6BCF\u6B21\u70B9\u51FB\u8D39\u7528",
106315
- "\u8D39\u7528",
106316
- "\u7EDD\u5BF9\u9875\u9996\u5C55\u793A\u4EFD\u989D",
106317
- "\u9875\u9996\u5C55\u793A\u4EFD\u989D",
106318
- "\u8F6C\u5316\u6B21\u6570",
106319
- "\u6BCF\u6B21\u8F6C\u5316\u8D39\u7528",
106320
- "\u8F6C\u5316\u7387"
106321
- ];
106322
- METRIC_HEADERS = METRIC_HEADERS_WITH_SHARE.filter((h) => !h.includes("\u4EFD\u989D"));
106323
- PERCENT_WITH_SHARE = [2, 6, 7, 10];
106324
- PERCENT_NO_SHARE = [2, 8];
106325
- }
106326
- });
106327
-
106328
- // src/commands/google-analysis/daily-render.ts
106329
- import fs34 from "fs/promises";
106330
- import path39 from "path";
106331
- function dailyRenderPullCommand(accountId, start, end) {
106332
- return `siluzan-tso google-analysis -a ${accountId} --start ${start} --end ${end} --sections overview,campaigns,keywords,search-terms --by-date --json-out <dir>`;
106333
- }
106334
- async function readJson2(file) {
106335
- return JSON.parse(await fs34.readFile(file, "utf8"));
106336
- }
106337
- async function findManifest(dir) {
106338
- const names = (await fs34.readdir(dir)).filter((n) => /^manifest.*\.json$/.test(n)).sort();
106339
- for (const name2 of names) {
106340
- try {
106341
- const m = await readJson2(path39.join(dir, name2));
106342
- if (m.googleAnalysis?.accountId) return m;
106343
- } catch {
106344
- }
106345
- }
106346
- throw new Error(`\u672A\u5728 ${dir} \u627E\u5230 google-analysis \u7684 manifest*.json\uFF0C\u8BF7\u5148\u7528 --json-out \u62C9\u6570`);
106347
- }
106348
- function rowsOf(envelope) {
106349
- const items3 = envelope?.items;
106350
- return Array.isArray(items3) ? items3.filter((r) => r && typeof r === "object") : [];
106351
- }
106352
- function hasDate(row) {
106353
- return typeof row.date === "string" && /^\d{4}-\d{2}-\d{2}/.test(row.date);
106354
- }
106355
- async function loadDailyReportSnapshot(snapshotDir) {
106356
- const dir = path39.resolve(snapshotDir);
106357
- const manifest = await findManifest(dir);
106358
- const accountId = manifest.googleAnalysis.accountId;
106359
- const range = manifest.googleAnalysis?.dateRange;
106360
- if (!range?.start || !range.end) throw new Error("manifest \u7F3A\u5C11 dateRange.start / end");
106361
- const { start, end } = range;
106362
- const dateTag = `${start.replace(/-/g, "")}-${end.replace(/-/g, "")}`;
106363
- const entries = await fs34.readdir(dir);
106364
- const fileOf = (section) => manifest.artifacts?.find((a) => a.section === section)?.file ?? pickSectionSnapshotFile(entries, section, accountId, dateTag);
106365
- const missing = REQUIRED_SECTIONS.filter((s) => !fileOf(s));
106366
- if (missing.length) {
106367
- throw new Error(
106368
- `\u5FEB\u7167\u7F3A\u5C11 ${missing.join(", ")}\u3002\u8BF7\u4E00\u6B21\u62C9\u9F50\uFF1A
106369
- ${dailyRenderPullCommand(accountId, start, end)}`
106370
- );
106371
- }
106372
- const sections = {};
106373
- for (const section of REQUIRED_SECTIONS) {
106374
- const rows = rowsOf(await readJson2(path39.join(dir, fileOf(section))));
106375
- if (rows.some((r) => !hasDate(r))) {
106376
- throw new Error(
106377
- `${section} \u4E0D\u662F\u6309\u65E5\u6570\u636E\uFF08\u884C\u4E0A\u6CA1\u6709 date\uFF09\u3002\u8BF7\u52A0 --by-date \u91CD\u62C9\uFF0C\u7981\u6B62\u6309\u5929\u5FAA\u73AF\uFF1A
106378
- ${dailyRenderPullCommand(accountId, start, end)}`
106379
- );
106380
- }
106381
- sections[section] = rows;
106382
- }
106383
- let currency;
106384
- const overviewFile = fileOf("overview");
106385
- if (overviewFile) {
106386
- const record2 = (await readJson2(path39.join(dir, overviewFile))).record;
106387
- const current = record2?.currentPeriod;
106388
- const code = record2?.currencyCode ?? current?.currencyCode;
106389
- if (typeof code === "string" && code) currency = code;
106390
- }
106391
- return { accountId, startDate: start, endDate: end, currency, sections };
106392
- }
106393
- async function runGoogleAnalysisDailyRender(opts) {
106394
- const snap = await loadDailyReportSnapshot(opts.snapshotDir);
106395
- const currency = opts.currency?.trim() || snap.currency || "\u2014";
106396
- const input = {
106397
- accountId: snap.accountId,
106398
- startDate: snap.startDate,
106399
- endDate: snap.endDate,
106400
- currency,
106401
- title: opts.title,
106402
- note: opts.note,
106403
- campaigns: snap.sections.campaigns,
106404
- keywords: snap.sections.keywords,
106405
- searchTerms: snap.sections["search-terms"]
106406
- };
106407
- const outPath = path39.resolve(
106408
- opts.out ?? path39.join(
106409
- opts.snapshotDir,
106410
- `google-daily-report-${snap.accountId}_${snap.startDate.replace(/-/g, "")}-${snap.endDate.replace(/-/g, "")}.xlsx`
106411
- )
106412
- );
106413
- const written = writeDailyReportExcel(outPath, input);
106414
- const drafts = buildDailyReportDrafts(input);
106415
- const accountSheet = drafts[0];
106416
- const totalRow = accountSheet.tables[0].rows.at(-1) ?? [];
106417
- const dailyRows = drafts[1].tables[0].rows;
106418
- const summary = {
106419
- kind: "siluzan-tso-google-daily-report",
106420
- file: written,
106421
- accountId: snap.accountId,
106422
- dateRange: { start: snap.startDate, end: snap.endDate },
106423
- currency,
106424
- daysWithData: dailyRows.length,
106425
- latestDay: dailyRows[0]?.[0] ?? null,
106426
- daysWithoutData: enumerateDays(snap.startDate, snap.endDate).filter(
106427
- (d) => !dailyRows.some((r) => r[0] === d)
106428
- ),
106429
- totals: {
106430
- clicks: totalRow[1],
106431
- impressions: totalRow[2],
106432
- spend: totalRow[6],
106433
- conversions: totalRow[9]
106434
- },
106435
- rows: Object.fromEntries(
106436
- drafts.map((d) => [d.name, d.tables.reduce((n, t) => n + t.rows.length, 0)])
106437
- )
106438
- };
106439
- if (!snap.currency && !opts.currency) {
106440
- console.error("\u26A0\uFE0F \u5FEB\u7167\u91CC\u6CA1\u6709 overview\uFF0C\u8D27\u5E01\u4EE3\u7801\u5217\u5199\u6210\u300C\u2014\u300D\u3002\u53EF\u52A0 --currency \u6216\u5728\u62C9\u6570\u65F6\u5E26\u4E0A overview\u3002");
106441
- }
106442
- console.log(JSON.stringify(summary));
106443
- }
106444
- var REQUIRED_SECTIONS;
106445
- var init_daily_render = __esm({
106446
- "src/commands/google-analysis/daily-render.ts"() {
106447
- "use strict";
106448
- init_by_date();
106449
- init_merge_snapshot();
106450
- init_daily_report_excel();
106451
- REQUIRED_SECTIONS = ["campaigns", "keywords", "search-terms"];
106452
- }
106453
- });
106454
-
106455
- // src/commands/google-analysis/okki-pmax-search-terms.ts
106456
- import * as fs35 from "fs/promises";
106457
- import * as path40 from "path";
106458
105591
  function buildPmaxSearchTermsEnvelope(items3, failedCampaigns) {
106459
105592
  return {
106460
105593
  schemaVersion: 3,
@@ -106466,11 +105599,11 @@ function buildPmaxSearchTermsEnvelope(items3, failedCampaigns) {
106466
105599
  fetchFailed: failedCampaigns.length > 0
106467
105600
  };
106468
105601
  }
106469
- function asRecord21(value) {
105602
+ function asRecord20(value) {
106470
105603
  if (value && typeof value === "object" && !Array.isArray(value)) return value;
106471
105604
  return null;
106472
105605
  }
106473
- function num5(value) {
105606
+ function num3(value) {
106474
105607
  if (typeof value === "number" && Number.isFinite(value)) return value;
106475
105608
  if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) {
106476
105609
  return Number(value);
@@ -106485,22 +105618,22 @@ function text4(row, ...keys) {
106485
105618
  }
106486
105619
  return "";
106487
105620
  }
106488
- function round25(value) {
105621
+ function round23(value) {
106489
105622
  return Math.round(value * 100) / 100;
106490
105623
  }
106491
- function round42(value) {
105624
+ function round4(value) {
106492
105625
  return Math.round(value * 1e4) / 1e4;
106493
105626
  }
106494
105627
  function selectPmaxCampaignsWithTraffic(rows) {
106495
105628
  const out = [];
106496
105629
  const seen = /* @__PURE__ */ new Set();
106497
105630
  for (const row of rows) {
106498
- const rec = asRecord21(row);
105631
+ const rec = asRecord20(row);
106499
105632
  if (!rec) continue;
106500
105633
  const channel = text4(rec, "channelTypeV2", "channelType").toUpperCase();
106501
105634
  if (!channel.includes("PERFORMANCE_MAX")) continue;
106502
- const spend = num5(rec.spend) ?? 0;
106503
- const impressions = num5(rec.impressions) ?? 0;
105635
+ const spend = num3(rec.spend) ?? 0;
105636
+ const impressions = num3(rec.impressions) ?? 0;
106504
105637
  if (spend <= 0 && impressions <= 0) continue;
106505
105638
  const campaignId = text4(rec, "campaignId");
106506
105639
  if (!/^\d+$/.test(campaignId) || seen.has(campaignId)) continue;
@@ -106527,41 +105660,41 @@ function normalizePmaxSearchTermRows(reports, namesById) {
106527
105660
  for (const report of reports) {
106528
105661
  const campaignId = String(report.campaignId ?? report.CampaignId ?? "").trim();
106529
105662
  const reportedName = typeof report.campaignName === "string" ? report.campaignName.trim() : typeof report.CampaignName === "string" ? report.CampaignName.trim() : "";
106530
- const campaignName = reportedName || namesById.get(campaignId) || DASH2;
105663
+ const campaignName = reportedName || namesById.get(campaignId) || DASH;
106531
105664
  for (const term of termList(report)) {
106532
- const rec = asRecord21(term);
105665
+ const rec = asRecord20(term);
106533
105666
  if (!rec) continue;
106534
105667
  const searchTermText = text4(rec, "searchTerm", "SearchTerm");
106535
- const spend = num5(rec.spend ?? rec.Spend);
105668
+ const spend = num3(rec.spend ?? rec.Spend);
106536
105669
  if (!searchTermText || spend == null || spend <= 0) continue;
106537
- const impressions = num5(rec.impressions ?? rec.Impressions) ?? 0;
106538
- const clicks = num5(rec.clicks ?? rec.Clicks) ?? 0;
106539
- const conversions = num5(rec.conversions ?? rec.Conversions) ?? 0;
105670
+ const impressions = num3(rec.impressions ?? rec.Impressions) ?? 0;
105671
+ const clicks = num3(rec.clicks ?? rec.Clicks) ?? 0;
105672
+ const conversions = num3(rec.conversions ?? rec.Conversions) ?? 0;
106540
105673
  const row = {
106541
105674
  searchTermText,
106542
105675
  matchTypeZh: MATCH_ZH,
106543
105676
  matchType: MATCH_EN,
106544
- queryTargetingStatusZh: DASH2,
106545
- queryTargetingStatus: DASH2,
105677
+ queryTargetingStatusZh: DASH,
105678
+ queryTargetingStatus: DASH,
106546
105679
  campaignId,
106547
105680
  campaignName,
106548
- adGroupName: DASH2,
106549
- keywordText: DASH2,
105681
+ adGroupName: DASH,
105682
+ keywordText: DASH,
106550
105683
  impressions,
106551
105684
  clicks,
106552
- spend: round25(spend),
105685
+ spend: round23(spend),
106553
105686
  conversions
106554
105687
  };
106555
- if (impressions > 0) row.ctr = round42(clicks / impressions);
105688
+ if (impressions > 0) row.ctr = round4(clicks / impressions);
106556
105689
  if (clicks > 0) {
106557
- row.averageCpc = round25(spend / clicks);
106558
- row.conversionRate = round42(conversions / clicks);
105690
+ row.averageCpc = round23(spend / clicks);
105691
+ row.conversionRate = round4(conversions / clicks);
106559
105692
  }
106560
- if (conversions > 0) row.costPerConversion = round25(spend / conversions);
105693
+ if (conversions > 0) row.costPerConversion = round23(spend / conversions);
106561
105694
  const rawValue = rec.conversionsValue ?? rec.ConversionsValue;
106562
105695
  if (rawValue != null && rawValue !== "") {
106563
- const value = num5(rawValue);
106564
- if (value != null) row.conversionsValue = round25(value);
105696
+ const value = num3(rawValue);
105697
+ if (value != null) row.conversionsValue = round23(value);
106565
105698
  }
106566
105699
  rows.push(row);
106567
105700
  }
@@ -106583,10 +105716,10 @@ async function mapPool(items3, limit, fn) {
106583
105716
  );
106584
105717
  return out;
106585
105718
  }
106586
- async function readManifest2(snapshotDir, accountId) {
105719
+ async function readManifest(snapshotDir, accountId) {
106587
105720
  try {
106588
- const raw = await fs35.readFile(
106589
- path40.join(snapshotDir, googleAnalysisManifestFile(accountId)),
105721
+ const raw = await fs33.readFile(
105722
+ path38.join(snapshotDir, googleAnalysisManifestFile(accountId)),
106590
105723
  "utf8"
106591
105724
  );
106592
105725
  const parsed = JSON.parse(raw);
@@ -106605,8 +105738,8 @@ function dateRangeOf(manifest) {
106605
105738
  return { start: range.start, end: range.end };
106606
105739
  }
106607
105740
  async function writePmaxSearchTermsSnapshot(opts) {
106608
- const absDir = path40.resolve(opts.snapshotDir);
106609
- const manifest = await readManifest2(absDir, opts.accountId);
105741
+ const absDir = path38.resolve(opts.snapshotDir);
105742
+ const manifest = await readManifest(absDir, opts.accountId);
106610
105743
  const range = manifest ? dateRangeOf(manifest) : null;
106611
105744
  if (!manifest || !range) return null;
106612
105745
  const dateTag = `${range.start.replace(/-/g, "")}-${range.end.replace(/-/g, "")}`;
@@ -106614,7 +105747,7 @@ async function writePmaxSearchTermsSnapshot(opts) {
106614
105747
  const campaignArt = campaignArts.find((art) => art.file.includes(dateTag)) ?? campaignArts.at(-1);
106615
105748
  if (!campaignArt) return null;
106616
105749
  const campaignRaw = JSON.parse(
106617
- await fs35.readFile(path40.join(absDir, campaignArt.file), "utf8")
105750
+ await fs33.readFile(path38.join(absDir, campaignArt.file), "utf8")
106618
105751
  );
106619
105752
  const campaigns = selectPmaxCampaignsWithTraffic(
106620
105753
  Array.isArray(campaignRaw.items) ? campaignRaw.items : []
@@ -106657,11 +105790,11 @@ async function writePmaxSearchTermsSnapshot(opts) {
106657
105790
  dateRange
106658
105791
  );
106659
105792
  const envelope = buildPmaxSearchTermsEnvelope(items3, failedCampaigns);
106660
- await fs35.writeFile(path40.join(absDir, fileName), `${JSON.stringify(envelope, null, 2)}
105793
+ await fs33.writeFile(path38.join(absDir, fileName), `${JSON.stringify(envelope, null, 2)}
106661
105794
  `, "utf8");
106662
- const manifestPath = path40.join(absDir, googleAnalysisManifestFile(opts.accountId));
105795
+ const manifestPath = path38.join(absDir, googleAnalysisManifestFile(opts.accountId));
106663
105796
  await withAsyncLock(manifestPath, async () => {
106664
- const existing = await readManifest2(absDir, opts.accountId);
105797
+ const existing = await readManifest(absDir, opts.accountId);
106665
105798
  const merged = mergeGoogleAnalysisManifest(existing, {
106666
105799
  accountId: opts.accountId,
106667
105800
  dateRange,
@@ -106673,7 +105806,7 @@ async function writePmaxSearchTermsSnapshot(opts) {
106673
105806
  endpointHint: "campaign/pmax/{campaignId}/reports/search"
106674
105807
  }
106675
105808
  });
106676
- await fs35.writeFile(manifestPath, `${JSON.stringify(merged, null, 2)}
105809
+ await fs33.writeFile(manifestPath, `${JSON.stringify(merged, null, 2)}
106677
105810
  `, "utf8");
106678
105811
  });
106679
105812
  return {
@@ -106683,7 +105816,7 @@ async function writePmaxSearchTermsSnapshot(opts) {
106683
105816
  failedCampaigns
106684
105817
  };
106685
105818
  }
106686
- var PMAX_SEARCH_TERMS_SECTION, PMAX_SEARCH_TERM_LIMIT, PMAX_FETCH_CONCURRENCY, MATCH_ZH, MATCH_EN, DASH2;
105819
+ var PMAX_SEARCH_TERMS_SECTION, PMAX_SEARCH_TERM_LIMIT, PMAX_FETCH_CONCURRENCY, MATCH_ZH, MATCH_EN, DASH;
106687
105820
  var init_okki_pmax_search_terms = __esm({
106688
105821
  "src/commands/google-analysis/okki-pmax-search-terms.ts"() {
106689
105822
  "use strict";
@@ -106695,16 +105828,16 @@ var init_okki_pmax_search_terms = __esm({
106695
105828
  PMAX_FETCH_CONCURRENCY = 4;
106696
105829
  MATCH_ZH = "\u6548\u679C\u6700\u5927\u5316";
106697
105830
  MATCH_EN = "Performance Max";
106698
- DASH2 = "\u2014";
105831
+ DASH = "\u2014";
106699
105832
  }
106700
105833
  });
106701
105834
 
106702
105835
  // src/commands/google-analysis/okki-display.ts
106703
- function num6(value) {
105836
+ function num4(value) {
106704
105837
  const n = typeof value === "number" ? value : Number(value);
106705
105838
  return Number.isFinite(n) ? n : 0;
106706
105839
  }
106707
- function round26(value) {
105840
+ function round24(value) {
106708
105841
  return Math.round(value * 100) / 100;
106709
105842
  }
106710
105843
  function share(part, total) {
@@ -106754,9 +105887,9 @@ function classifyDeviceKind(value) {
106754
105887
  return "other";
106755
105888
  }
106756
105889
  function okkiGeoInteractionCount(row) {
106757
- const interactions = num6(row.interactions);
105890
+ const interactions = num4(row.interactions);
106758
105891
  if (interactions > 0) return interactions;
106759
- const clicks = num6(row.clicks);
105892
+ const clicks = num4(row.clicks);
106760
105893
  return clicks > 0 ? clicks : 0;
106761
105894
  }
106762
105895
  function summarizeOkkiDeviceSpend(rows) {
@@ -106764,14 +105897,14 @@ function summarizeOkkiDeviceSpend(rows) {
106764
105897
  const conv = { desktop: 0, mobile: 0, tablet: 0, other: 0 };
106765
105898
  for (const row of rows) {
106766
105899
  const kind = classifyDeviceKind(row.deviceType);
106767
- acc[kind] += num6(row.spend);
106768
- conv[kind] += num6(row.conversions);
106769
- }
106770
- const desktop = round26(acc.desktop);
106771
- const mobile = round26(acc.mobile);
106772
- const tablet = round26(acc.tablet);
106773
- const other = round26(acc.other);
106774
- const total = round26(desktop + mobile + tablet + other);
105900
+ acc[kind] += num4(row.spend);
105901
+ conv[kind] += num4(row.conversions);
105902
+ }
105903
+ const desktop = round24(acc.desktop);
105904
+ const mobile = round24(acc.mobile);
105905
+ const tablet = round24(acc.tablet);
105906
+ const other = round24(acc.other);
105907
+ const total = round24(desktop + mobile + tablet + other);
106775
105908
  return {
106776
105909
  desktop,
106777
105910
  mobile,
@@ -106793,7 +105926,7 @@ function narrativeClaimsMobileSpendLeads(text5) {
106793
105926
  if (!t.includes("\u79FB\u52A8")) return false;
106794
105927
  return /移动(?:端|设备)?(?:为|是)主要消耗/.test(t) || /移动(?:端|设备)?为主要(?:消耗)?设备/.test(t) || /移动(?:端|设备)?(?:消耗|花费|费用|流量)?占比高/.test(t);
106795
105928
  }
106796
- function asRecord22(value) {
105929
+ function asRecord21(value) {
106797
105930
  if (value && typeof value === "object" && !Array.isArray(value)) return value;
106798
105931
  return null;
106799
105932
  }
@@ -106801,16 +105934,16 @@ function stringList(value) {
106801
105934
  return (Array.isArray(value) ? value : []).map((item) => typeof item === "string" ? item.trim() : "").filter(Boolean);
106802
105935
  }
106803
105936
  function collectOkkiNarrativeText(data) {
106804
- const narrative = asRecord22(data.narrative) ?? {};
105937
+ const narrative = asRecord21(data.narrative) ?? {};
106805
105938
  const parts = [];
106806
- const sheetAnalysis = asRecord22(narrative.sheetAnalysis) ?? {};
105939
+ const sheetAnalysis = asRecord21(narrative.sheetAnalysis) ?? {};
106807
105940
  for (const block of Object.values(sheetAnalysis)) {
106808
- const rec = asRecord22(block);
105941
+ const rec = asRecord21(block);
106809
105942
  parts.push(...stringList(rec?.summary), ...stringList(rec?.suggestions));
106810
105943
  }
106811
- const review = asRecord22(narrative.review) ?? {};
105944
+ const review = asRecord21(narrative.review) ?? {};
106812
105945
  for (const block of Object.values(review)) {
106813
- const rec = asRecord22(block);
105946
+ const rec = asRecord21(block);
106814
105947
  for (const key of ["overview", "summary", "suggestion"]) {
106815
105948
  const value = rec?.[key];
106816
105949
  if (typeof value === "string" && value.trim()) parts.push(value.trim());
@@ -106824,6 +105957,363 @@ var init_okki_display = __esm({
106824
105957
  }
106825
105958
  });
106826
105959
 
105960
+ // src/commands/google-analysis/merge-snapshot.ts
105961
+ import * as fs34 from "fs/promises";
105962
+ import * as path39 from "path";
105963
+ function asRecord22(value) {
105964
+ if (value && typeof value === "object" && !Array.isArray(value)) {
105965
+ return value;
105966
+ }
105967
+ return null;
105968
+ }
105969
+ function num5(value) {
105970
+ const n = Number(value);
105971
+ return Number.isFinite(n) ? n : void 0;
105972
+ }
105973
+ function round25(value) {
105974
+ return value == null ? void 0 : Math.round(value * 100) / 100;
105975
+ }
105976
+ async function readManifest2(snapshotDir, accountId) {
105977
+ const candidates = [];
105978
+ if (accountId) candidates.push(googleAnalysisManifestFile(accountId));
105979
+ try {
105980
+ const entries = await fs34.readdir(snapshotDir);
105981
+ const manifestNames = entries.filter((n) => n.startsWith("manifest") && n.endsWith(".json"));
105982
+ for (const name2 of manifestNames) {
105983
+ if (!candidates.includes(name2)) candidates.push(name2);
105984
+ }
105985
+ } catch {
105986
+ }
105987
+ for (const name2 of candidates) {
105988
+ try {
105989
+ const raw = await fs34.readFile(path39.join(snapshotDir, name2), "utf8");
105990
+ const parsed = JSON.parse(raw);
105991
+ if (Array.isArray(parsed.artifacts) && parsed.artifacts.length > 0) return parsed;
105992
+ } catch {
105993
+ }
105994
+ }
105995
+ return null;
105996
+ }
105997
+ async function loadSectionFile(snapshotDir, file) {
105998
+ try {
105999
+ const raw = await fs34.readFile(path39.join(snapshotDir, file), "utf8");
106000
+ const parsed = JSON.parse(raw);
106001
+ if (parsed && typeof parsed === "object") return parsed;
106002
+ return null;
106003
+ } catch {
106004
+ return null;
106005
+ }
106006
+ }
106007
+ function negativeKeywordText(row) {
106008
+ const text5 = row.keywordText;
106009
+ if (Array.isArray(text5)) {
106010
+ const parts = text5.map((part) => String(part).trim()).filter(Boolean);
106011
+ if (parts.length > 0) return parts.join(", ");
106012
+ }
106013
+ if (typeof text5 === "string" && text5.trim()) return text5.trim();
106014
+ if (typeof row.keyword === "string" && row.keyword.trim()) return row.keyword.trim();
106015
+ return "\u2014";
106016
+ }
106017
+ function mapNegativeKeywordRows(rows) {
106018
+ const seen = /* @__PURE__ */ new Set();
106019
+ const mapped = [];
106020
+ for (const row of rows) {
106021
+ const id = row.id == null ? "" : String(row.id);
106022
+ if (id && seen.has(id)) continue;
106023
+ if (id) seen.add(id);
106024
+ const level = String(row.negativeLevel ?? "").trim();
106025
+ const campaignId = String(row.campaignId ?? "").trim();
106026
+ const adGroupId = String(row.adGroupId ?? "").trim();
106027
+ const campaignName = String(row.campaignName ?? "").trim();
106028
+ const adGroupName = String(row.adGroupName ?? "").trim();
106029
+ mapped.push({
106030
+ keyword: negativeKeywordText(row),
106031
+ matchType: String(row.matchTypeV2 ?? row.matchType ?? "\u2014"),
106032
+ level: level || "\u2014",
106033
+ levelZh: NEGATIVE_LEVEL_ZH[level] ?? (level || "\u2014"),
106034
+ campaignId: campaignId || "\u2014",
106035
+ adGroupId: adGroupId || "\u2014",
106036
+ campaignName: campaignName || "\u2014",
106037
+ adGroupName: adGroupName || "\u2014"
106038
+ });
106039
+ }
106040
+ return mapped;
106041
+ }
106042
+ function dateTagFromRange(dateRange) {
106043
+ if (!dateRange || dateRange.mode !== "range") return void 0;
106044
+ return `${dateRange.start.replace(/-/g, "")}-${dateRange.end.replace(/-/g, "")}`;
106045
+ }
106046
+ function dateTagFromMeta(meta) {
106047
+ const start = typeof meta?.startDate === "string" ? meta.startDate : "";
106048
+ const end = typeof meta?.endDate === "string" ? meta.endDate : "";
106049
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) return void 0;
106050
+ return `${start.replace(/-/g, "")}-${end.replace(/-/g, "")}`;
106051
+ }
106052
+ function pickSectionSnapshotFile(files, section, accountId, preferredDateTag) {
106053
+ const escapedSection = section.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
106054
+ const escapedId = accountId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
106055
+ const re = new RegExp(`^${escapedSection}-${escapedId}(?:_(\\d{8}-\\d{8}))?\\.json$`);
106056
+ const matches = files.filter((f) => re.test(f));
106057
+ if (matches.length === 0) return null;
106058
+ if (preferredDateTag) {
106059
+ const preferred = matches.find((f) => f.endsWith(`_${preferredDateTag}.json`));
106060
+ if (preferred) return preferred;
106061
+ }
106062
+ return [...matches].sort().at(-1) ?? null;
106063
+ }
106064
+ async function recoverMissingReportSections(sectionMap, absDir, accountId, preferredDateTag) {
106065
+ if (!accountId) return;
106066
+ let entries;
106067
+ try {
106068
+ entries = await fs34.readdir(absDir);
106069
+ } catch {
106070
+ return;
106071
+ }
106072
+ for (const section of REPORT_MERGE_SECTIONS) {
106073
+ if (sectionMap.has(section)) continue;
106074
+ const file = pickSectionSnapshotFile(entries, section, accountId, preferredDateTag);
106075
+ if (!file) continue;
106076
+ const data = await loadSectionFile(absDir, file);
106077
+ if (data) sectionMap.set(section, data);
106078
+ }
106079
+ }
106080
+ function periodMetricsFromRow(row) {
106081
+ if (!row) return null;
106082
+ return {
106083
+ cost: num5(row.spend),
106084
+ impressions: num5(row.impressions),
106085
+ clicks: num5(row.clicks),
106086
+ conversions: num5(row.conversions),
106087
+ ctr: num5(row.ctr),
106088
+ averageCpc: num5(row.averageCpc),
106089
+ costPerConversion: num5(row.costPerConversion)
106090
+ };
106091
+ }
106092
+ function items(envelope) {
106093
+ if (!envelope || !Array.isArray(envelope.items)) return [];
106094
+ return envelope.items.filter((row) => asRecord22(row) !== null);
106095
+ }
106096
+ function record(envelope) {
106097
+ return envelope?.record ?? null;
106098
+ }
106099
+ function pickMetricRow(row, extraFields) {
106100
+ const base2 = {
106101
+ spend: num5(row.spend) ?? 0,
106102
+ impressions: num5(row.impressions) ?? 0,
106103
+ clicks: num5(row.clicks) ?? 0,
106104
+ ctr: num5(row.ctr),
106105
+ averageCpc: num5(row.averageCpc),
106106
+ conversions: num5(row.conversions) ?? 0,
106107
+ costPerConversion: num5(row.costPerConversion)
106108
+ };
106109
+ for (const f of extraFields) {
106110
+ if (row[f] !== void 0) base2[f] = row[f];
106111
+ }
106112
+ return base2;
106113
+ }
106114
+ function sumCampaignRowsToPeriodKpis(rows) {
106115
+ if (rows.length === 0) return null;
106116
+ let cost = 0;
106117
+ let impressions = 0;
106118
+ let clicks = 0;
106119
+ let conversions = 0;
106120
+ for (const row of rows) {
106121
+ cost += num5(row.spend) ?? 0;
106122
+ impressions += num5(row.impressions) ?? 0;
106123
+ clicks += num5(row.clicks) ?? 0;
106124
+ conversions += num5(row.conversions) ?? 0;
106125
+ }
106126
+ const ctr = impressions > 0 ? clicks / impressions : void 0;
106127
+ const averageCpc = clicks > 0 ? cost / clicks : void 0;
106128
+ const costPerConversion = conversions > 0 ? cost / conversions : void 0;
106129
+ return {
106130
+ cost: round25(cost),
106131
+ impressions: Math.round(impressions),
106132
+ clicks: Math.round(clicks),
106133
+ conversions: round25(conversions),
106134
+ ctr,
106135
+ averageCpc: round25(averageCpc),
106136
+ costPerConversion: round25(costPerConversion)
106137
+ };
106138
+ }
106139
+ async function mergeGoogleAnalysisSnapshotIntoReport(payload, snapshotDir) {
106140
+ const absDir = path39.resolve(snapshotDir);
106141
+ const metaAccountId = typeof asRecord22(payload.meta)?.accountId === "string" ? asRecord22(payload.meta)?.accountId : void 0;
106142
+ const manifest = await readManifest2(snapshotDir, metaAccountId);
106143
+ if (!manifest) {
106144
+ throw new Error(`\u672A\u5728 ${absDir} \u627E\u5230 manifest*.json\uFF0C\u8BF7\u5148\u6267\u884C google-analysis --json-out`);
106145
+ }
106146
+ const accountId = manifest.googleAnalysis?.accountId ?? metaAccountId;
106147
+ const dateRange = manifest.googleAnalysis?.dateRange;
106148
+ const preferredDateTag = dateTagFromRange(dateRange) ?? dateTagFromMeta(asRecord22(payload.meta) ?? void 0);
106149
+ const sectionMap = /* @__PURE__ */ new Map();
106150
+ for (const art of manifest.artifacts ?? []) {
106151
+ const data = await loadSectionFile(absDir, art.file);
106152
+ if (data) sectionMap.set(art.section, data);
106153
+ }
106154
+ await recoverMissingReportSections(sectionMap, absDir, accountId, preferredDateTag);
106155
+ const overviewRecord = record(sectionMap.get("overview"));
106156
+ const currentPeriod = asRecord22(overviewRecord?.currentPeriod);
106157
+ const previousPeriod = asRecord22(overviewRecord?.previousPeriod);
106158
+ const meta = { ...payload.meta ?? {} };
106159
+ if (!meta.accountId && accountId) meta.accountId = accountId;
106160
+ if (!meta.currency) {
106161
+ const currency = overviewRecord?.currencyCode ?? currentPeriod?.currencyCode;
106162
+ if (typeof currency === "string" && currency) meta.currency = currency;
106163
+ }
106164
+ if (!meta.startDate && dateRange && dateRange.mode === "range") meta.startDate = dateRange.start;
106165
+ if (!meta.endDate && dateRange && dateRange.mode === "range") meta.endDate = dateRange.end;
106166
+ if (!meta.generatedAt) meta.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
106167
+ const campaignRows3 = items(sectionMap.get("campaigns"));
106168
+ const campaignKpis = sumCampaignRowsToPeriodKpis(campaignRows3);
106169
+ const dimensionSummaryRecord = record(sectionMap.get("dimension-summary"));
106170
+ const kpis = { ...payload.kpis ?? {} };
106171
+ const currentKpiSource = campaignKpis ?? periodMetricsFromRow(currentPeriod) ?? periodMetricsFromRow(dimensionSummaryRecord);
106172
+ if (currentKpiSource) {
106173
+ if (currentKpiSource.cost != null) kpis.cost = currentKpiSource.cost;
106174
+ if (currentKpiSource.impressions != null) kpis.impressions = currentKpiSource.impressions;
106175
+ if (currentKpiSource.clicks != null) kpis.clicks = currentKpiSource.clicks;
106176
+ if (currentKpiSource.conversions != null) kpis.conversions = currentKpiSource.conversions;
106177
+ if (currentKpiSource.ctr != null) kpis.ctr = currentKpiSource.ctr;
106178
+ if (currentKpiSource.averageCpc != null) kpis.averageCpc = currentKpiSource.averageCpc;
106179
+ if (currentKpiSource.costPerConversion != null) {
106180
+ kpis.costPerConversion = currentKpiSource.costPerConversion;
106181
+ }
106182
+ }
106183
+ if (overviewRecord) {
106184
+ const activeDays = num5(overviewRecord.activeDays);
106185
+ if (activeDays != null) kpis.activeDays = Math.round(activeDays);
106186
+ const averageDailyCost = num5(overviewRecord.averageDailyCost);
106187
+ if (averageDailyCost != null) kpis.averageDailyCost = round25(averageDailyCost);
106188
+ }
106189
+ if (previousPeriod) {
106190
+ kpis.previousPeriod = {
106191
+ cost: num5(previousPeriod.spend),
106192
+ impressions: num5(previousPeriod.impressions),
106193
+ clicks: num5(previousPeriod.clicks),
106194
+ conversions: num5(previousPeriod.conversions),
106195
+ ctr: num5(previousPeriod.ctr),
106196
+ averageCpc: num5(previousPeriod.averageCpc),
106197
+ costPerConversion: num5(previousPeriod.costPerConversion)
106198
+ };
106199
+ }
106200
+ const charts = { ...payload.charts ?? {} };
106201
+ {
106202
+ const dailyRows = items(sectionMap.get("daily-metrics"));
106203
+ if (dailyRows.length > 0) {
106204
+ const sorted = [...dailyRows].sort(
106205
+ (a, b) => String(a.date ?? "").localeCompare(String(b.date ?? ""))
106206
+ );
106207
+ charts.dailyTrend = {
106208
+ dates: sorted.map((r) => String(r.date ?? "\u2014")),
106209
+ cost: sorted.map((r) => round25(num5(r.spend)) ?? 0),
106210
+ conversions: sorted.map((r) => Math.round(num5(r.conversions) ?? 0)),
106211
+ conversionsValue: sorted.map((r) => round25(num5(r.conversionsValue)) ?? 0),
106212
+ cpa: sorted.map((r) => round25(num5(r.costPerConversion)) ?? 0)
106213
+ };
106214
+ }
106215
+ }
106216
+ const tables = { ...payload.tables ?? {} };
106217
+ if (dimensionSummaryRecord) {
106218
+ tables.dimensionSummary = {
106219
+ cost: num5(dimensionSummaryRecord.spend),
106220
+ impressions: num5(dimensionSummaryRecord.impressions),
106221
+ clicks: num5(dimensionSummaryRecord.clicks),
106222
+ conversions: num5(dimensionSummaryRecord.conversions),
106223
+ ctr: num5(dimensionSummaryRecord.ctr),
106224
+ averageCpc: num5(dimensionSummaryRecord.averageCpc),
106225
+ costPerConversion: num5(dimensionSummaryRecord.costPerConversion),
106226
+ searchImpressionShare: num5(dimensionSummaryRecord.searchImpressionShare),
106227
+ searchBudgetLostImpressionShare: num5(dimensionSummaryRecord.searchBudgetLostImpressionShare),
106228
+ searchRankLostImpressionShare: num5(dimensionSummaryRecord.searchRankLostImpressionShare)
106229
+ };
106230
+ }
106231
+ if (campaignRows3.length > 0) {
106232
+ tables.campaigns = campaignRows3.map((r) => ({
106233
+ ...pickMetricRow(r, ["campaignName", "campaignStatusDisplay", "channelTypeV2"]),
106234
+ budgetAmountYuan: r.budgetAmountYuan ?? null
106235
+ }));
106236
+ }
106237
+ {
106238
+ const rows = items(sectionMap.get("devices"));
106239
+ if (rows.length > 0) {
106240
+ tables.devices = rows.map((r) => pickMetricRow(r, ["deviceType", "conversionsValue"]));
106241
+ }
106242
+ }
106243
+ {
106244
+ const rows = items(sectionMap.get("geographic"));
106245
+ if (rows.length > 0) {
106246
+ tables.geographic = rows.map(
106247
+ (r) => pickMetricRow(r, [
106248
+ "countryOrRegion",
106249
+ "countryOrRegionZh",
106250
+ "countryNameZh",
106251
+ "conversionsValue"
106252
+ ])
106253
+ );
106254
+ }
106255
+ }
106256
+ {
106257
+ const rows = items(sectionMap.get("audience"));
106258
+ if (rows.length > 0) {
106259
+ tables.audience = rows.map((r) => {
106260
+ const mapped = pickMetricRow(r, [
106261
+ "audience",
106262
+ "audienceName",
106263
+ "audienceType",
106264
+ "campaignName"
106265
+ ]);
106266
+ if (mapped.audience == null && mapped.audienceName != null) {
106267
+ mapped.audience = mapped.audienceName;
106268
+ }
106269
+ return mapped;
106270
+ });
106271
+ }
106272
+ }
106273
+ {
106274
+ const rows = items(sectionMap.get("keywords"));
106275
+ if (rows.length > 0) {
106276
+ tables.keywords = rows.map(
106277
+ (r) => pickMetricRow(r, ["keyword", "keywordMatchType", "keywordMatchTypeZh", "campaignName"])
106278
+ );
106279
+ }
106280
+ }
106281
+ if (sectionMap.has("negative-keywords")) {
106282
+ tables.negativeKeywords = mapNegativeKeywordRows(items(sectionMap.get("negative-keywords")));
106283
+ }
106284
+ return {
106285
+ ...payload,
106286
+ meta,
106287
+ kpis,
106288
+ charts,
106289
+ tables
106290
+ };
106291
+ }
106292
+ var REPORT_MERGE_SECTIONS, NEGATIVE_LEVEL_ZH;
106293
+ var init_merge_snapshot = __esm({
106294
+ "src/commands/google-analysis/merge-snapshot.ts"() {
106295
+ "use strict";
106296
+ init_google_analysis();
106297
+ REPORT_MERGE_SECTIONS = [
106298
+ "overview",
106299
+ "daily-metrics",
106300
+ "dimension-summary",
106301
+ "campaigns",
106302
+ "devices",
106303
+ "geographic",
106304
+ "audience",
106305
+ "keywords",
106306
+ "negative-keywords"
106307
+ ];
106308
+ NEGATIVE_LEVEL_ZH = {
106309
+ Account: "\u8D26\u6237",
106310
+ Campaign: "\u7CFB\u5217",
106311
+ AdGroup: "\u5E7F\u544A\u7EC4",
106312
+ "Ad group": "\u5E7F\u544A\u7EC4"
106313
+ };
106314
+ }
106315
+ });
106316
+
106827
106317
  // src/commands/google-analysis/okki-report-content.ts
106828
106318
  function textLen(value) {
106829
106319
  return typeof value === "string" ? value.trim().length : 0;
@@ -107014,13 +106504,13 @@ var init_okki_report_content = __esm({
107014
106504
  });
107015
106505
 
107016
106506
  // src/commands/google-analysis/okki-merge-snapshot.ts
107017
- import * as fs36 from "fs/promises";
107018
- import * as path41 from "path";
107019
- function num7(value) {
106507
+ import * as fs35 from "fs/promises";
106508
+ import * as path40 from "path";
106509
+ function num6(value) {
107020
106510
  const n = Number(value);
107021
106511
  return Number.isFinite(n) ? n : void 0;
107022
106512
  }
107023
- function round27(value) {
106513
+ function round26(value) {
107024
106514
  return value == null ? void 0 : Math.round(value * 100) / 100;
107025
106515
  }
107026
106516
  function items2(envelope) {
@@ -107041,7 +106531,7 @@ async function readManifest3(snapshotDir, accountId) {
107041
106531
  const candidates = [];
107042
106532
  if (accountId) candidates.push(googleAnalysisManifestFile(accountId));
107043
106533
  try {
107044
- const entries = await fs36.readdir(snapshotDir);
106534
+ const entries = await fs35.readdir(snapshotDir);
107045
106535
  for (const name2 of entries.filter((n) => n.startsWith("manifest") && n.endsWith(".json"))) {
107046
106536
  if (!candidates.includes(name2)) candidates.push(name2);
107047
106537
  }
@@ -107049,7 +106539,7 @@ async function readManifest3(snapshotDir, accountId) {
107049
106539
  }
107050
106540
  for (const name2 of candidates) {
107051
106541
  try {
107052
- const raw = await fs36.readFile(path41.join(snapshotDir, name2), "utf8");
106542
+ const raw = await fs35.readFile(path40.join(snapshotDir, name2), "utf8");
107053
106543
  const parsed = JSON.parse(raw);
107054
106544
  if (Array.isArray(parsed.artifacts) && parsed.artifacts.length > 0) return parsed;
107055
106545
  } catch {
@@ -107059,7 +106549,7 @@ async function readManifest3(snapshotDir, accountId) {
107059
106549
  }
107060
106550
  async function loadSectionFile2(snapshotDir, file) {
107061
106551
  try {
107062
- const raw = await fs36.readFile(path41.join(snapshotDir, file), "utf8");
106552
+ const raw = await fs35.readFile(path40.join(snapshotDir, file), "utf8");
107063
106553
  const parsed = JSON.parse(raw);
107064
106554
  if (parsed && typeof parsed === "object") return parsed;
107065
106555
  return null;
@@ -107068,7 +106558,7 @@ async function loadSectionFile2(snapshotDir, file) {
107068
106558
  }
107069
106559
  }
107070
106560
  async function mergeOkkiSnapshotIntoReport(payload, snapshotDir) {
107071
- const absDir = path41.resolve(snapshotDir);
106561
+ const absDir = path40.resolve(snapshotDir);
107072
106562
  const metaAccountId = typeof asRecord23(payload.meta)?.accountId === "string" ? asRecord23(payload.meta)?.accountId : void 0;
107073
106563
  const manifest = await readManifest3(absDir, metaAccountId);
107074
106564
  if (!manifest) {
@@ -107085,7 +106575,7 @@ async function mergeOkkiSnapshotIntoReport(payload, snapshotDir) {
107085
106575
  if (accountId) {
107086
106576
  let entries = [];
107087
106577
  try {
107088
- entries = await fs36.readdir(absDir);
106578
+ entries = await fs35.readdir(absDir);
107089
106579
  } catch {
107090
106580
  entries = [];
107091
106581
  }
@@ -107116,13 +106606,13 @@ async function mergeOkkiSnapshotIntoReport(payload, snapshotDir) {
107116
106606
  const campaignKpis = sumCampaignRowsToPeriodKpis(campaignRows3);
107117
106607
  const kpis = { ...payload.kpis ?? {} };
107118
106608
  const kpiSource = campaignKpis ?? (currentPeriod ? {
107119
- cost: num7(currentPeriod.spend),
107120
- impressions: num7(currentPeriod.impressions),
107121
- clicks: num7(currentPeriod.clicks),
107122
- conversions: num7(currentPeriod.conversions),
107123
- ctr: num7(currentPeriod.ctr),
107124
- averageCpc: num7(currentPeriod.averageCpc),
107125
- costPerConversion: num7(currentPeriod.costPerConversion)
106609
+ cost: num6(currentPeriod.spend),
106610
+ impressions: num6(currentPeriod.impressions),
106611
+ clicks: num6(currentPeriod.clicks),
106612
+ conversions: num6(currentPeriod.conversions),
106613
+ ctr: num6(currentPeriod.ctr),
106614
+ averageCpc: num6(currentPeriod.averageCpc),
106615
+ costPerConversion: num6(currentPeriod.costPerConversion)
107126
106616
  } : null);
107127
106617
  if (kpiSource) {
107128
106618
  if (kpiSource.cost != null) kpis.cost = kpiSource.cost;
@@ -107134,10 +106624,10 @@ async function mergeOkkiSnapshotIntoReport(payload, snapshotDir) {
107134
106624
  if (kpiSource.costPerConversion != null) kpis.costPerConversion = kpiSource.costPerConversion;
107135
106625
  }
107136
106626
  if (overviewRecord) {
107137
- const activeDays = num7(overviewRecord.activeDays);
106627
+ const activeDays = num6(overviewRecord.activeDays);
107138
106628
  if (activeDays != null) kpis.activeDays = Math.round(activeDays);
107139
- const averageDailyCost = num7(overviewRecord.averageDailyCost);
107140
- if (averageDailyCost != null) kpis.averageDailyCost = round27(averageDailyCost);
106629
+ const averageDailyCost = num6(overviewRecord.averageDailyCost);
106630
+ if (averageDailyCost != null) kpis.averageDailyCost = round26(averageDailyCost);
107141
106631
  }
107142
106632
  return {
107143
106633
  ...payload,
@@ -107170,33 +106660,33 @@ var init_okki_merge_snapshot = __esm({
107170
106660
  });
107171
106661
 
107172
106662
  // src/commands/google-analysis/okki-render-excel.ts
107173
- function num8(value) {
106663
+ function num7(value) {
107174
106664
  if (value == null || value === "") return void 0;
107175
106665
  const n = typeof value === "number" ? value : Number(value);
107176
106666
  return Number.isFinite(n) ? n : void 0;
107177
106667
  }
107178
- function round28(value) {
106668
+ function round27(value) {
107179
106669
  return Math.round(value * 100) / 100;
107180
106670
  }
107181
106671
  function money2(value) {
107182
- return round28(num8(value) ?? 0);
106672
+ return round27(num7(value) ?? 0);
107183
106673
  }
107184
106674
  function count(value) {
107185
- const n = num8(value) ?? 0;
107186
- return Number.isInteger(n) ? n : round28(n);
106675
+ const n = num7(value) ?? 0;
106676
+ return Number.isInteger(n) ? n : round27(n);
107187
106677
  }
107188
106678
  function rate(value) {
107189
- return num8(value) ?? 0;
106679
+ return num7(value) ?? 0;
107190
106680
  }
107191
106681
  function dashOrRate(numer, denom) {
107192
106682
  if (denom <= 0) return "\u2014";
107193
- return round28(numer / denom);
106683
+ return round27(numer / denom);
107194
106684
  }
107195
106685
  function dashOrMoney(numer, denom) {
107196
106686
  if (denom <= 0) return "\u2014";
107197
- return round28(numer / denom);
106687
+ return round27(numer / denom);
107198
106688
  }
107199
- function str2(value, fallback = "\u2014") {
106689
+ function str(value, fallback = "\u2014") {
107200
106690
  if (typeof value === "string" && value.trim()) return value.trim();
107201
106691
  if (typeof value === "number" && Number.isFinite(value)) return String(value);
107202
106692
  return fallback;
@@ -107228,7 +106718,7 @@ function formatOkkiDateRange(start, end, lang) {
107228
106718
  return `${iso(a)} \u2013 ${iso(b)}`;
107229
106719
  }
107230
106720
  function deviceLabel(value, lang) {
107231
- const raw = str2(value);
106721
+ const raw = str(value);
107232
106722
  if (lang === "en") return raw || "\u2014";
107233
106723
  return DEVICE_TYPE_ZH[raw] ?? raw;
107234
106724
  }
@@ -107238,22 +106728,22 @@ function targetingStatus(row, lang = "zh") {
107238
106728
  if (textLen(raw2)) return String(raw2).trim();
107239
106729
  }
107240
106730
  if (textLen(row.queryTargetingStatusZh)) return String(row.queryTargetingStatusZh).trim();
107241
- const raw = str2(row.queryTargetingStatus, "");
106731
+ const raw = str(row.queryTargetingStatus, "");
107242
106732
  return TARGETING_STATUS_ZH[raw] ?? (raw || "\u2014");
107243
106733
  }
107244
106734
  function conversionsPair(row) {
107245
- const conv = num8(row.conversions) ?? 0;
107246
- const all = num8(row.allConversions);
106735
+ const conv = num7(row.conversions) ?? 0;
106736
+ const all = num7(row.allConversions);
107247
106737
  return { all: all ?? conv, conv };
107248
106738
  }
107249
106739
  function interactionRateOf(row, impressions, interactions) {
107250
106740
  if (interactions <= 0) return "\u2014";
107251
- const parsed = typeof row.interactionRate === "string" ? Number.parseFloat(row.interactionRate) : num8(row.interactionRate);
106741
+ const parsed = typeof row.interactionRate === "string" ? Number.parseFloat(row.interactionRate) : num7(row.interactionRate);
107252
106742
  if (parsed != null) return parsed;
107253
106743
  return dashOrRate(interactions, impressions);
107254
106744
  }
107255
106745
  function sortBySpendDesc(rows) {
107256
- return [...rows].sort((a, b) => (num8(b.spend) ?? 0) - (num8(a.spend) ?? 0));
106746
+ return [...rows].sort((a, b) => (num7(b.spend) ?? 0) - (num7(a.spend) ?? 0));
107257
106747
  }
107258
106748
  function prefixLines(items3, firstPrefix) {
107259
106749
  return items3.map((text5, idx) => {
@@ -107274,9 +106764,9 @@ function reviewLines(data) {
107274
106764
  const lines = [];
107275
106765
  OKKI_REVIEW_KEYS.forEach((key, idx) => {
107276
106766
  const block = asRecord23(review[key]) ?? {};
107277
- lines.push(`${idx + 1}\u3001${REVIEW_LABELS2[key]}\uFF1A${str2(block.overview, "")}`);
107278
- lines.push(` \u603B\u7ED3\uFF1A${str2(block.summary, "")}`);
107279
- lines.push(` \u5EFA\u8BAE\uFF1A${str2(block.suggestion, "")}`);
106767
+ lines.push(`${idx + 1}\u3001${REVIEW_LABELS2[key]}\uFF1A${str(block.overview, "")}`);
106768
+ lines.push(` \u603B\u7ED3\uFF1A${str(block.summary, "")}`);
106769
+ lines.push(` \u5EFA\u8BAE\uFF1A${str(block.suggestion, "")}`);
107280
106770
  });
107281
106771
  return lines;
107282
106772
  }
@@ -107289,13 +106779,13 @@ function campaignRows(data) {
107289
106779
  let conv = 0;
107290
106780
  const body = rows.map((row) => {
107291
106781
  const pair = conversionsPair(row);
107292
- spend += num8(row.spend) ?? 0;
107293
- impressions += num8(row.impressions) ?? 0;
107294
- clicks += num8(row.clicks) ?? 0;
106782
+ spend += num7(row.spend) ?? 0;
106783
+ impressions += num7(row.impressions) ?? 0;
106784
+ clicks += num7(row.clicks) ?? 0;
107295
106785
  allConv += pair.all;
107296
106786
  conv += pair.conv;
107297
106787
  return [
107298
- str2(row.campaignName),
106788
+ str(row.campaignName),
107299
106789
  money2(row.budgetAmountYuan),
107300
106790
  money2(row.spend),
107301
106791
  count(row.impressions),
@@ -107304,7 +106794,7 @@ function campaignRows(data) {
107304
106794
  money2(row.averageCpc),
107305
106795
  count(pair.all),
107306
106796
  count(pair.conv),
107307
- num8(row.costPerConversion) == null && pair.conv <= 0 ? "\u2014" : money2(row.costPerConversion),
106797
+ num7(row.costPerConversion) == null && pair.conv <= 0 ? "\u2014" : money2(row.costPerConversion),
107308
106798
  rate(row.conversionRate)
107309
106799
  ];
107310
106800
  });
@@ -107313,7 +106803,7 @@ function campaignRows(data) {
107313
106803
  total: [
107314
106804
  "\u603B\u8BA1",
107315
106805
  "--",
107316
- round28(spend),
106806
+ round27(spend),
107317
106807
  Math.round(impressions),
107318
106808
  Math.round(clicks),
107319
106809
  dashOrRate(clicks, impressions),
@@ -107329,26 +106819,26 @@ function keywordRows(data, lang = "zh") {
107329
106819
  const matchOf = (row) => lang === "en" ? row.keywordMatchType || row.keywordMatchTypeZh : row.keywordMatchTypeZh || row.keywordMatchType;
107330
106820
  return sortBySpendDesc(data.tables?.keywords ?? []).map((row) => [
107331
106821
  formatOkkiKeywordDisplay(row.keyword, matchOf(row)),
107332
- str2(matchOf(row)),
107333
- str2(row.campaignName),
107334
- str2(row.adGroupName),
106822
+ str(matchOf(row)),
106823
+ str(row.campaignName),
106824
+ str(row.adGroupName),
107335
106825
  money2(row.spend),
107336
106826
  count(row.impressions),
107337
106827
  count(row.clicks),
107338
106828
  rate(row.ctr),
107339
106829
  money2(row.averageCpc),
107340
106830
  count(row.conversions),
107341
- num8(row.costPerConversion) == null && (num8(row.conversions) ?? 0) <= 0 ? "\u2014" : money2(row.costPerConversion),
106831
+ num7(row.costPerConversion) == null && (num7(row.conversions) ?? 0) <= 0 ? "\u2014" : money2(row.costPerConversion),
107342
106832
  rate(row.conversionRate)
107343
106833
  ]);
107344
106834
  }
107345
106835
  function searchTermRows(data, lang = "zh") {
107346
106836
  return sortBySpendDesc(data.tables?.searchTerms ?? []).map((row) => [
107347
- str2(row.searchTermText),
107348
- str2(lang === "en" ? row.matchType || row.matchTypeZh : row.matchTypeZh || row.matchType),
106837
+ str(row.searchTermText),
106838
+ str(lang === "en" ? row.matchType || row.matchTypeZh : row.matchTypeZh || row.matchType),
107349
106839
  targetingStatus(row, lang),
107350
- str2(row.campaignName),
107351
- str2(row.adGroupName),
106840
+ str(row.campaignName),
106841
+ str(row.adGroupName),
107352
106842
  formatOkkiKeywordDisplay(
107353
106843
  row.keywordText || row.keyword,
107354
106844
  lang === "en" ? row.keywordMatchType || row.keywordMatchTypeZh || row.matchType || row.matchTypeZh : row.keywordMatchTypeZh || row.keywordMatchType || row.matchTypeZh || row.matchType
@@ -107359,7 +106849,7 @@ function searchTermRows(data, lang = "zh") {
107359
106849
  money2(row.averageCpc),
107360
106850
  money2(row.spend),
107361
106851
  count(row.conversions),
107362
- num8(row.costPerConversion) == null && (num8(row.conversions) ?? 0) <= 0 ? "\u2014" : money2(row.costPerConversion),
106852
+ num7(row.costPerConversion) == null && (num7(row.conversions) ?? 0) <= 0 ? "\u2014" : money2(row.costPerConversion),
107363
106853
  rate(row.conversionRate)
107364
106854
  ]);
107365
106855
  }
@@ -107369,8 +106859,8 @@ function deviceRows(data, lang = "zh") {
107369
106859
  return [
107370
106860
  deviceLabel(row.deviceType, lang),
107371
106861
  "\u5E7F\u544A\u7CFB\u5217",
107372
- str2(row.campaignName),
107373
- str2(row.bidModifierDisplay, "\u2014"),
106862
+ str(row.campaignName),
106863
+ str(row.bidModifierDisplay, "\u2014"),
107374
106864
  count(row.impressions),
107375
106865
  count(row.clicks),
107376
106866
  rate(row.ctr),
@@ -107379,7 +106869,7 @@ function deviceRows(data, lang = "zh") {
107379
106869
  count(pair.all),
107380
106870
  count(pair.conv),
107381
106871
  money2(row.conversionsValue),
107382
- num8(row.costPerConversion) == null && pair.conv <= 0 ? "\u2014" : money2(row.costPerConversion),
106872
+ num7(row.costPerConversion) == null && pair.conv <= 0 ? "\u2014" : money2(row.costPerConversion),
107383
106873
  rate(row.conversionRate)
107384
106874
  ];
107385
106875
  });
@@ -107387,31 +106877,31 @@ function deviceRows(data, lang = "zh") {
107387
106877
  function geoRows(data, lang = "zh") {
107388
106878
  return sortBySpendDesc(data.tables?.geo ?? []).map((row) => {
107389
106879
  const pair = conversionsPair(row);
107390
- const impressions = num8(row.impressions) ?? 0;
106880
+ const impressions = num7(row.impressions) ?? 0;
107391
106881
  const interactions = okkiGeoInteractionCount(row);
107392
106882
  return [
107393
- str2(
106883
+ str(
107394
106884
  lang === "en" ? row.countryOrRegion || row.countryNameZh : row.countryOrRegionZh || row.countryNameZh || row.countryOrRegion
107395
106885
  ),
107396
- str2(row.campaignName),
106886
+ str(row.campaignName),
107397
106887
  count(row.impressions),
107398
106888
  interactions > 0 ? count(interactions) : 0,
107399
106889
  interactionRateOf(row, impressions, interactions),
107400
106890
  money2(row.spend),
107401
- dashOrMoney(num8(row.spend) ?? 0, interactions),
106891
+ dashOrMoney(num7(row.spend) ?? 0, interactions),
107402
106892
  count(row.clicks),
107403
106893
  rate(row.ctr),
107404
106894
  count(pair.all),
107405
106895
  count(pair.conv),
107406
106896
  money2(row.conversionsValue),
107407
- num8(row.costPerConversion) == null && pair.conv <= 0 ? "\u2014" : money2(row.costPerConversion),
106897
+ num7(row.costPerConversion) == null && pair.conv <= 0 ? "\u2014" : money2(row.costPerConversion),
107408
106898
  rate(row.conversionRate)
107409
106899
  ];
107410
106900
  });
107411
106901
  }
107412
106902
  function buildOkkiWeeklySheetDrafts(data, lang = "zh") {
107413
106903
  const meta = asRecord23(data.meta) ?? {};
107414
- const period = formatOkkiDateRange(str2(meta.startDate, ""), str2(meta.endDate, ""), lang);
106904
+ const period = formatOkkiDateRange(str(meta.startDate, ""), str(meta.endDate, ""), lang);
107415
106905
  const campaigns = campaignRows(data);
107416
106906
  const drafts = {
107417
106907
  campaigns: {
@@ -107435,7 +106925,7 @@ function buildOkkiWeeklySheetDrafts(data, lang = "zh") {
107435
106925
  dataRows: campaigns.body,
107436
106926
  totalRow: campaigns.total,
107437
106927
  analysisLines: analysisLines(data, "campaigns"),
107438
- reviewTitle: formatOkkiReviewTitle(str2(meta.endDate, ""), lang),
106928
+ reviewTitle: formatOkkiReviewTitle(str(meta.endDate, ""), lang),
107439
106929
  reviewLines: reviewLines(data)
107440
106930
  },
107441
106931
  keywords: {
@@ -107615,10 +107105,10 @@ var init_okki_render_excel = __esm({
107615
107105
  });
107616
107106
 
107617
107107
  // src/commands/google-analysis/okki-render-report.ts
107618
- import fs37 from "fs/promises";
107619
- import path42 from "path";
107108
+ import fs36 from "fs/promises";
107109
+ import path41 from "path";
107620
107110
  async function readJsonFile3(filePath) {
107621
- const text5 = await fs37.readFile(filePath, "utf8");
107111
+ const text5 = await fs36.readFile(filePath, "utf8");
107622
107112
  try {
107623
107113
  return JSON.parse(text5);
107624
107114
  } catch {
@@ -107632,7 +107122,7 @@ function asPayload(value) {
107632
107122
  throw new Error("\u62A5\u544A\u6570\u636E\u987B\u4E3A JSON \u5BF9\u8C61");
107633
107123
  }
107634
107124
  async function runGoogleAnalysisOkkiRender(opts) {
107635
- const dataPath = path42.resolve(opts.dataFile);
107125
+ const dataPath = path41.resolve(opts.dataFile);
107636
107126
  const snapshotDir = opts.snapshotDir?.trim();
107637
107127
  if (!snapshotDir) {
107638
107128
  console.error("\n\u274C okki-render \u5FC5\u987B\u4F20 --snapshot-dir\uFF08google-analysis --json-out \u76EE\u5F55\uFF09\n");
@@ -107640,7 +107130,7 @@ async function runGoogleAnalysisOkkiRender(opts) {
107640
107130
  }
107641
107131
  let data = asPayload(await readJsonFile3(dataPath));
107642
107132
  try {
107643
- data = await mergeOkkiSnapshotIntoReport(data, path42.resolve(snapshotDir));
107133
+ data = await mergeOkkiSnapshotIntoReport(data, path41.resolve(snapshotDir));
107644
107134
  } catch (err) {
107645
107135
  console.error(`
107646
107136
  \u274C ${err instanceof Error ? err.message : String(err)}
@@ -107660,10 +107150,10 @@ async function runGoogleAnalysisOkkiRender(opts) {
107660
107150
  );
107661
107151
  process.exit(1);
107662
107152
  }
107663
- const outPath = path42.resolve(
107664
- opts.out ?? path42.join(path42.dirname(dataPath), "okki-weekly-report.xlsx")
107153
+ const outPath = path41.resolve(
107154
+ opts.out ?? path41.join(path41.dirname(dataPath), "okki-weekly-report.xlsx")
107665
107155
  );
107666
- await fs37.mkdir(path42.dirname(outPath), { recursive: true });
107156
+ await fs36.mkdir(path41.dirname(outPath), { recursive: true });
107667
107157
  writeOkkiWeeklyExcel(outPath, data, lang);
107668
107158
  console.log(`
107669
107159
  \u2705 OKKI \u5468\u62A5\u5DF2\u751F\u6210\uFF1A${outPath}
@@ -107836,19 +107326,19 @@ var init_report_content = __esm({
107836
107326
  });
107837
107327
 
107838
107328
  // src/commands/google-analysis/render-report.ts
107839
- import fs38 from "fs";
107329
+ import fs37 from "fs";
107840
107330
  import fsPromises3 from "fs/promises";
107841
- import path43 from "path";
107331
+ import path42 from "path";
107842
107332
  import { fileURLToPath as fileURLToPath10 } from "url";
107843
107333
  function resolveSkillTemplatePath4(basename14) {
107844
- const dir = path43.dirname(fileURLToPath10(import.meta.url));
107334
+ const dir = path42.dirname(fileURLToPath10(import.meta.url));
107845
107335
  const candidates = [
107846
- path43.join(dir, "skill", "report-templates", basename14),
107847
- path43.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
107848
- path43.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
107336
+ path42.join(dir, "skill", "report-templates", basename14),
107337
+ path42.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
107338
+ path42.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
107849
107339
  ];
107850
107340
  for (const p of candidates) {
107851
- if (fs38.existsSync(p)) return p;
107341
+ if (fs37.existsSync(p)) return p;
107852
107342
  }
107853
107343
  return candidates[0];
107854
107344
  }
@@ -107878,10 +107368,10 @@ function injectReportData2(html, payload, lang) {
107878
107368
  return localized.replace(INJECT_MARKER, `window.__GOOGLE_PERIOD_REPORT__ = ${json};`);
107879
107369
  }
107880
107370
  async function runGoogleAnalysisRender(opts) {
107881
- const dataPath = path43.resolve(opts.dataFile);
107371
+ const dataPath = path42.resolve(opts.dataFile);
107882
107372
  let data = asRecord25(await readJsonFile4(dataPath));
107883
107373
  if (opts.snapshotDir?.trim()) {
107884
- data = await mergeGoogleAnalysisSnapshotIntoReport(data, path43.resolve(opts.snapshotDir));
107374
+ data = await mergeGoogleAnalysisSnapshotIntoReport(data, path42.resolve(opts.snapshotDir));
107885
107375
  }
107886
107376
  const lang = readReportLangOrExit({ flag: opts.lang, meta: data.meta });
107887
107377
  const contentCheck = validateGooglePeriodReportContent(data);
@@ -107908,10 +107398,10 @@ async function runGoogleAnalysisRender(opts) {
107908
107398
  `);
107909
107399
  process.exit(1);
107910
107400
  }
107911
- const outPath = path43.resolve(
107912
- opts.out ?? path43.join(path43.dirname(dataPath), "google-period-report.html")
107401
+ const outPath = path42.resolve(
107402
+ opts.out ?? path42.join(path42.dirname(dataPath), "google-period-report.html")
107913
107403
  );
107914
- const outDir = path43.dirname(outPath);
107404
+ const outDir = path42.dirname(outPath);
107915
107405
  await fsPromises3.mkdir(outDir, { recursive: true });
107916
107406
  await fsPromises3.writeFile(outPath, injectReportData2(html, data, lang), "utf8");
107917
107407
  const { stats } = contentCheck;
@@ -107943,8 +107433,8 @@ var init_render_report = __esm({
107943
107433
 
107944
107434
  // src/utils/batch-runner.ts
107945
107435
  import { performance as performance2 } from "perf_hooks";
107946
- import * as path44 from "path";
107947
- import * as fs39 from "fs/promises";
107436
+ import * as path43 from "path";
107437
+ import * as fs38 from "fs/promises";
107948
107438
  async function runPool(items3, concurrencyRef, worker, signal) {
107949
107439
  let cursor = 0;
107950
107440
  const launch = () => {
@@ -108084,7 +107574,7 @@ async function runBatch(opts) {
108084
107574
  }
108085
107575
  const inner = {
108086
107576
  ...emptyProgress(
108087
- opts.paths.runDir.split(path44.sep).pop() ?? "run",
107577
+ opts.paths.runDir.split(path43.sep).pop() ?? "run",
108088
107578
  allTasks.length,
108089
107579
  opts.accountConcurrency,
108090
107580
  opts.sectionConcurrency
@@ -108215,7 +107705,7 @@ async function runBatch(opts) {
108215
107705
  signal: aborterToken.signal
108216
107706
  });
108217
107707
  await writer({
108218
- snapshotDir: path44.join(opts.paths.resultsDir, sanitizeAccountSegment(task.accountId)),
107708
+ snapshotDir: path43.join(opts.paths.resultsDir, sanitizeAccountSegment(task.accountId)),
108219
107709
  section: task.section,
108220
107710
  accountId: task.accountId,
108221
107711
  dateRange: result.dateRange,
@@ -108312,7 +107802,7 @@ async function runBatch(opts) {
108312
107802
  };
108313
107803
  }
108314
107804
  async function writeTaskError(paths, errorsDir, task, err, cls) {
108315
- const file = path44.join(errorsDir, `${sanitizeSection(task.section)}.error.json`);
107805
+ const file = path43.join(errorsDir, `${sanitizeSection(task.section)}.error.json`);
108316
107806
  const payload = {
108317
107807
  schemaVersion: 1,
108318
107808
  taskId: task.id,
@@ -108359,10 +107849,10 @@ async function persistRunMetadata(input) {
108359
107849
  accountsTotal: input.accounts.length,
108360
107850
  invocation: input.invocation
108361
107851
  };
108362
- await fs39.mkdir(paths.runDir, { recursive: true });
108363
- await fs39.mkdir(paths.stateDir, { recursive: true });
108364
- await fs39.mkdir(paths.resultsDir, { recursive: true });
108365
- await fs39.mkdir(paths.errorsDir, { recursive: true });
107852
+ await fs38.mkdir(paths.runDir, { recursive: true });
107853
+ await fs38.mkdir(paths.stateDir, { recursive: true });
107854
+ await fs38.mkdir(paths.resultsDir, { recursive: true });
107855
+ await fs38.mkdir(paths.errorsDir, { recursive: true });
108366
107856
  await writeRunManifest(paths, manifest);
108367
107857
  await writeAccounts(paths, input.accounts);
108368
107858
  return paths;
@@ -108429,7 +107919,7 @@ __export(google_analysis_batch_exports, {
108429
107919
  registerGoogleAnalysisBatchCommands: () => registerGoogleAnalysisBatchCommands,
108430
107920
  resolveBatchAccounts: () => resolveBatchAccounts
108431
107921
  });
108432
- import * as path45 from "path";
107922
+ import * as path44 from "path";
108433
107923
  import { performance as performance3 } from "perf_hooks";
108434
107924
  function parseSections(input) {
108435
107925
  if (!input || !input.trim()) return DEFAULT_SECTIONS;
@@ -109060,7 +108550,7 @@ var init_google_analysis_batch = __esm({
109060
108550
  });
109061
108551
 
109062
108552
  // src/commands/google-analysis/register-cli.ts
109063
- import * as path46 from "path";
108553
+ import * as path45 from "path";
109064
108554
  import { performance as performance4 } from "perf_hooks";
109065
108555
  import { Command } from "commander";
109066
108556
  function normalizeAnalysisDateOpts(opts) {
@@ -109237,7 +108727,7 @@ async function runAllSections(opts) {
109237
108727
  }
109238
108728
  const succeeded = results.filter((r) => r.ok).length;
109239
108729
  const failed = results.length - succeeded;
109240
- const absoluteSnapshotDir = path46.resolve(opts.jsonOut);
108730
+ const absoluteSnapshotDir = path45.resolve(opts.jsonOut);
109241
108731
  const summary = {
109242
108732
  kind: "siluzan-tso-google-analysis-snapshot-batch",
109243
108733
  absoluteSnapshotDir,
@@ -109440,7 +108930,7 @@ ${fixHint}
109440
108930
  }
109441
108931
  function registerGoogleAnalysisCommands(program2) {
109442
108932
  const root = program2.command("google-analysis").description(
109443
- "Google \u8D26\u6237\u5206\u6790\uFF1A\u6279\u91CF\u62C9\u53D6\u4E00\u4E2A\u6216\u591A\u4E2A\u7EF4\u5EA6\uFF08\u9ED8\u8BA4\uFF09\uFF0C\u6216\u7531 render \u751F\u6210\u5468\u671F HTML / okki-render \u751F\u6210 OKKI \u5468\u62A5 xlsx / daily-render \u751F\u6210\u6309\u65E5\u6295\u653E\u65E5\u62A5 xlsx / demand-gen-render \u751F\u6210 Demand Gen \u6C47\u603B HTML"
108933
+ "Google \u8D26\u6237\u5206\u6790\uFF1A\u6279\u91CF\u62C9\u53D6\u4E00\u4E2A\u6216\u591A\u4E2A\u7EF4\u5EA6\uFF08\u9ED8\u8BA4\uFF09\uFF0C\u6216\u7531 render \u751F\u6210\u5468\u671F HTML / okki-render \u751F\u6210 OKKI \u5468\u62A5 xlsx / demand-gen-render \u751F\u6210 Demand Gen \u6C47\u603B HTML"
109444
108934
  );
109445
108935
  root.addCommand(registerRunCommand(), { isDefault: true });
109446
108936
  root.command("render").description(
@@ -109469,23 +108959,6 @@ function registerGoogleAnalysisCommands(program2) {
109469
108959
  lang: opts.lang
109470
108960
  });
109471
108961
  });
109472
- root.command("daily-render").description(
109473
- "\u628A --by-date \u5FEB\u7167\u5199\u6210 Google \u6295\u653E\u65E5\u62A5 xlsx\uFF08\u8D26\u6237\u6982\u89C8 / \u6BCF\u65E5\u6570\u636E / \u5206\u8BA1\u5212\u6570\u636E / \u641C\u7D22\u5B57\u8BCD\u62A5\u544A / \u5173\u952E\u8BCD\uFF09\uFF0C\u4E0D\u9700\u8981\u53D9\u4E8B JSON"
109474
- ).requiredOption(
109475
- "--snapshot-dir <dir>",
109476
- "google-analysis --sections overview,campaigns,keywords,search-terms --by-date --json-out \u7684\u76EE\u5F55"
109477
- ).option("--out <file>", "\u8F93\u51FA xlsx \u8DEF\u5F84\uFF08\u9ED8\u8BA4\u5199\u5728\u5FEB\u7167\u76EE\u5F55\uFF09").option("--title <text>", "\u9996\u4E2A Sheet \u6807\u9898\uFF0C\u5982\u300CXX \u5BA2\u6237 \xB7 \u6295\u653E\u65E5\u62A5\u300D").option("--note <text>", "\u5199\u5728\u300C\u641C\u7D22\u5B57\u8BCD\u62A5\u544A\u300D\u4E0A\u65B9\u7684\u4F18\u5316\u52A8\u4F5C\u8BF4\u660E\uFF08\u53EF\u6CBF\u7528\u65E7\u65E5\u62A5\u91CC\u7684\u539F\u6587\uFF09").option("--currency <code>", "\u8D27\u5E01\u4EE3\u7801\u5217\uFF1B\u9ED8\u8BA4\u53D6\u5FEB\u7167 overview \u7684\u5E01\u79CD").action(
109478
- async (opts) => {
109479
- try {
109480
- await runGoogleAnalysisDailyRender(opts);
109481
- } catch (err) {
109482
- console.error(`
109483
- \u274C ${err instanceof Error ? err.message : String(err)}
109484
- `);
109485
- process.exit(1);
109486
- }
109487
- }
109488
- );
109489
108962
  root.command("demand-gen-render").description(
109490
108963
  "\u6839\u636E Agent \u64B0\u5199\u7684 Demand Gen \u6C47\u603B JSON \u751F\u6210 8 \u8282 HTML\uFF08\u4E0D\u5408\u5E76\u5FEB\u7167\uFF1BExcel \u4E0D\u8D70\u672C\u547D\u4EE4\uFF09"
109491
108964
  ).requiredOption("--data <file>", "Agent \u4EA7\u51FA\u7684 demand-gen-analysis-report.json").option("--out <file>", "\u8F93\u51FA HTML \u8DEF\u5F84\uFF08\u9ED8\u8BA4\u540C --data \u76EE\u5F55\uFF09").option("--lang <lang>", "\u7EC8\u7A3F\u8BED\u8A00\uFF1Azh \u6216 en\u3002\u8986\u76D6 JSON meta.lang").action(async (opts) => {
@@ -109510,7 +108983,6 @@ var init_register_cli = __esm({
109510
108983
  init_sections();
109511
108984
  init_fetch();
109512
108985
  init_demand_gen_render();
109513
- init_daily_render();
109514
108986
  init_okki_pmax_search_terms();
109515
108987
  init_okki_render_report();
109516
108988
  init_render_report();
@@ -109544,8 +109016,8 @@ var init_google_analysis3 = __esm({
109544
109016
  // src/index.ts
109545
109017
  init_dist();
109546
109018
  init_dist();
109547
- import * as fs50 from "fs";
109548
- import * as path61 from "path";
109019
+ import * as fs49 from "fs";
109020
+ import * as path60 from "path";
109549
109021
  import { fileURLToPath as fileURLToPath16 } from "url";
109550
109022
  import { Command as Command6 } from "commander";
109551
109023
 
@@ -110035,8 +109507,8 @@ function deriveWebUrl(apiBaseUrl) {
110035
109507
  }
110036
109508
  var TSO_UMI_ROUTE_PREFIX = "/v3umijs/tso";
110037
109509
  function buildTsoPageWebUrl(webUrl, tsoSubRoute, extraQuery) {
110038
- const path62 = tsoSubRoute.replace(/^\/+/, "");
110039
- const umiPath = `${TSO_UMI_ROUTE_PREFIX}/${path62}`;
109510
+ const path61 = tsoSubRoute.replace(/^\/+/, "");
109511
+ const umiPath = `${TSO_UMI_ROUTE_PREFIX}/${path61}`;
110040
109512
  const q = new URLSearchParams({ tso: umiPath });
110041
109513
  if (extraQuery) {
110042
109514
  for (const [key, value] of Object.entries(extraQuery)) {
@@ -110044,7 +109516,7 @@ function buildTsoPageWebUrl(webUrl, tsoSubRoute, extraQuery) {
110044
109516
  if (v) q.set(key, v);
110045
109517
  }
110046
109518
  }
110047
- return `${webUrl.replace(/\/+$/, "")}/v3/foreign_trade/tso/${path62}?${q.toString()}`;
109519
+ return `${webUrl.replace(/\/+$/, "")}/v3/foreign_trade/tso/${path61}?${q.toString()}`;
110048
109520
  }
110049
109521
  function cmdConfigShow() {
110050
109522
  const shared = readSharedConfig();
@@ -117902,10 +117374,10 @@ async function runAdKeywordDelete(opts) {
117902
117374
  }
117903
117375
  function findKeywordEditMismatches(requested, returned, changed) {
117904
117376
  const mismatches = [];
117905
- const str4 = (v) => typeof v === "string" ? v.trim() : "";
117906
- if (changed.finalUrl !== void 0 && str4(returned["finalURL"]) !== str4(requested["finalURL"])) {
117377
+ const str3 = (v) => typeof v === "string" ? v.trim() : "";
117378
+ if (changed.finalUrl !== void 0 && str3(returned["finalURL"]) !== str3(requested["finalURL"])) {
117907
117379
  mismatches.push(
117908
- `finalURL\uFF1A\u671F\u671B ${str4(requested["finalURL"]) || "(\u7A7A)"}\uFF0C\u5B9E\u9645 ${str4(returned["finalURL"]) || "(\u7A7A)"}`
117380
+ `finalURL\uFF1A\u671F\u671B ${str3(requested["finalURL"]) || "(\u7A7A)"}\uFF0C\u5B9E\u9645 ${str3(returned["finalURL"]) || "(\u7A7A)"}`
117909
117381
  );
117910
117382
  }
117911
117383
  if (changed.maxCpc !== void 0 && typeof returned["maxCPC"] === "number" && returned["maxCPC"] !== Number(requested["maxCPC"])) {
@@ -117915,8 +117387,8 @@ function findKeywordEditMismatches(requested, returned, changed) {
117915
117387
  `maxCPC\uFF1A\u671F\u671B ${expectedCents / 100} \u5143\uFF0C\u5217\u8868\u4ECD\u662F ${actualCents / 100} \u5143\u3002\u5173\u952E\u8BCD\u5217\u8868\u6309\u8D26\u6237\u548C\u65E5\u671F\u7F13\u5B58\u7EA6 60 \u79D2\uFF0C\u4E14\u6CA1\u6709 --fresh\uFF0C\u8FD9\u6B21\u56DE\u8BFB\u53EF\u80FD\u4ECD\u662F\u5199\u5165\u524D\u7684\u503C\u3002\u4E0D\u8981\u7ACB\u523B\u91CD\u8DD1 keyword-edit\uFF0C\u4E5F\u4E0D\u8981\u5220\u8BCD\u91CD\u5EFA\u3002\u7EA6 60 \u79D2\u540E\u7528 ad keywords --json-out \u770B\u8BE5 id \u7684 maxCPCYuan\uFF0C\u5DF2\u7ECF\u662F\u76EE\u6807\u503C\u5C31\u5F53\u6210\u529F\u3002`
117916
117388
  );
117917
117389
  }
117918
- if (changed.status !== void 0 && typeof returned["userStatusV2"] === "string" && str4(returned["userStatusV2"]).toLowerCase() !== changed.status.toLowerCase()) {
117919
- mismatches.push(`userStatusV2\uFF1A\u671F\u671B ${changed.status}\uFF0C\u5B9E\u9645 ${str4(returned["userStatusV2"])}`);
117390
+ if (changed.status !== void 0 && typeof returned["userStatusV2"] === "string" && str3(returned["userStatusV2"]).toLowerCase() !== changed.status.toLowerCase()) {
117391
+ mismatches.push(`userStatusV2\uFF1A\u671F\u671B ${changed.status}\uFF0C\u5B9E\u9645 ${str3(returned["userStatusV2"])}`);
117920
117392
  }
117921
117393
  return mismatches;
117922
117394
  }
@@ -118249,7 +117721,7 @@ function cloneKeywordBlockShell(block) {
118249
117721
  delete shell["matchTypeV2"];
118250
117722
  return shell;
118251
117723
  }
118252
- function splitKeywordsForBatchJobBlockIfMixed(block, path62, warnings) {
117724
+ function splitKeywordsForBatchJobBlockIfMixed(block, path61, warnings) {
118253
117725
  const declaredUi = matchTypeV2ToUi(readBlockMatchTypeRaw(block));
118254
117726
  const entries = collectKeywordEntriesFromBlock(block);
118255
117727
  if (entries.length === 0) return [block];
@@ -118268,7 +117740,7 @@ function splitKeywordsForBatchJobBlockIfMixed(block, path62, warnings) {
118268
117740
  (ui) => matchTypeUiToV2(ui)
118269
117741
  );
118270
117742
  warnings.push(
118271
- `${path62} \u542B\u591A\u79CD\u5339\u914D\u7C7B\u578B\uFF0C\u5DF2\u81EA\u52A8\u62C6\u5206\u4E3A ${groups.size} \u4E2A KeywordsForBatchJob \u5757\uFF08${labels.join("\u3001")}\uFF09`
117743
+ `${path61} \u542B\u591A\u79CD\u5339\u914D\u7C7B\u578B\uFF0C\u5DF2\u81EA\u52A8\u62C6\u5206\u4E3A ${groups.size} \u4E2A KeywordsForBatchJob \u5757\uFF08${labels.join("\u3001")}\uFF09`
118272
117744
  );
118273
117745
  const shell = cloneKeywordBlockShell(block);
118274
117746
  const splitBlocks = [];
@@ -118288,16 +117760,16 @@ function splitKeywordsForBatchJobBlockIfMixed(block, path62, warnings) {
118288
117760
  }
118289
117761
  return splitBlocks;
118290
117762
  }
118291
- function validateKeywordCore(core, path62, errors, lengthViolations) {
117763
+ function validateKeywordCore(core, path61, errors, lengthViolations) {
118292
117764
  const trimmed = core.trim();
118293
117765
  if (!trimmed) {
118294
- errors.push(`${path62} \u5173\u952E\u8BCD\u8BCD\u5E72\u4E0D\u80FD\u4E3A\u7A7A`);
117766
+ errors.push(`${path61} \u5173\u952E\u8BCD\u8BCD\u5E72\u4E0D\u80FD\u4E3A\u7A7A`);
118295
117767
  return false;
118296
117768
  }
118297
117769
  if (trimmed.length > GOOGLE_KEYWORD_MAX_CORE_LENGTH) {
118298
117770
  if (lengthViolations) {
118299
117771
  pushLengthViolation(lengthViolations, {
118300
- path: path62,
117772
+ path: path61,
118301
117773
  field: "KeywordText",
118302
117774
  kind: "keyword_core",
118303
117775
  limit: GOOGLE_KEYWORD_MAX_CORE_LENGTH,
@@ -118307,13 +117779,13 @@ function validateKeywordCore(core, path62, errors, lengthViolations) {
118307
117779
  });
118308
117780
  }
118309
117781
  errors.push(
118310
- `${path62} \u5173\u952E\u8BCD\u8BCD\u5E72\u8D85\u8FC7 ${GOOGLE_KEYWORD_MAX_CORE_LENGTH} \u5B57\u7B26\uFF08\u5F53\u524D ${trimmed.length}\uFF09\uFF1A"${trimmed}"`
117782
+ `${path61} \u5173\u952E\u8BCD\u8BCD\u5E72\u8D85\u8FC7 ${GOOGLE_KEYWORD_MAX_CORE_LENGTH} \u5B57\u7B26\uFF08\u5F53\u524D ${trimmed.length}\uFF09\uFF1A"${trimmed}"`
118311
117783
  );
118312
117784
  return false;
118313
117785
  }
118314
117786
  if (!VALID_CORE_REGEX.test(trimmed)) {
118315
117787
  errors.push(
118316
- `${path62} \u542B Google \u4E0D\u5141\u8BB8\u7684\u5B57\u7B26\uFF08\u8BCD\u5E72\u4EC5\u5141\u8BB8\u5B57\u6BCD/\u6570\u5B57/\u7A7A\u683C/\u8FDE\u5B57\u7B26/\u53E5\u70B9\uFF09\uFF1A"${trimmed.slice(0, 40)}${trimmed.length > 40 ? "\u2026" : ""}"`
117788
+ `${path61} \u542B Google \u4E0D\u5141\u8BB8\u7684\u5B57\u7B26\uFF08\u8BCD\u5E72\u4EC5\u5141\u8BB8\u5B57\u6BCD/\u6570\u5B57/\u7A7A\u683C/\u8FDE\u5B57\u7B26/\u53E5\u70B9\uFF09\uFF1A"${trimmed.slice(0, 40)}${trimmed.length > 40 ? "\u2026" : ""}"`
118317
117789
  );
118318
117790
  return false;
118319
117791
  }
@@ -118370,10 +117842,10 @@ function canonicalizeKeywordBatchBlock(block, resolvedMatchV2, normalizedTexts,
118370
117842
  }
118371
117843
  }
118372
117844
  }
118373
- function pushKeywordAutoFixWarning(warnings, path62, fieldLabel, trimmedRaw, formatted, declaredUi, beforeUi, matchType, inferredMatchType) {
117845
+ function pushKeywordAutoFixWarning(warnings, path61, fieldLabel, trimmedRaw, formatted, declaredUi, beforeUi, matchType, inferredMatchType) {
118374
117846
  if (inferredMatchType) {
118375
117847
  warnings.push(
118376
- `${path62}.${fieldLabel} \u672A\u6307\u5B9A MatchTypeV2\uFF0C\u5DF2\u6309\u8BCD\u9762\u63A8\u65AD\u4E3A ${matchTypeUiToV2(matchType)}`
117848
+ `${path61}.${fieldLabel} \u672A\u6307\u5B9A MatchTypeV2\uFF0C\u5DF2\u6309\u8BCD\u9762\u63A8\u65AD\u4E3A ${matchTypeUiToV2(matchType)}`
118377
117849
  );
118378
117850
  return false;
118379
117851
  }
@@ -118382,16 +117854,16 @@ function pushKeywordAutoFixWarning(warnings, path62, fieldLabel, trimmedRaw, for
118382
117854
  }
118383
117855
  if (declaredUi && beforeUi !== declaredUi) {
118384
117856
  warnings.push(
118385
- `${path62}.${fieldLabel} MatchTypeV2=${matchTypeUiToV2(declaredUi)} \u4E0E\u8BCD\u9762\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u81EA\u52A8\u4FEE\u590D\u4E3A\uFF1A${formatted}`
117857
+ `${path61}.${fieldLabel} MatchTypeV2=${matchTypeUiToV2(declaredUi)} \u4E0E\u8BCD\u9762\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u81EA\u52A8\u4FEE\u590D\u4E3A\uFF1A${formatted}`
118386
117858
  );
118387
117859
  return false;
118388
117860
  }
118389
117861
  if (formatted !== trimmedRaw) {
118390
- warnings.push(`${path62}.${fieldLabel} \u5DF2\u81EA\u52A8\u4FEE\u590D\u8BCD\u9762\uFF1A${trimmedRaw} \u2192 ${formatted}`);
117862
+ warnings.push(`${path61}.${fieldLabel} \u5DF2\u81EA\u52A8\u4FEE\u590D\u8BCD\u9762\uFF1A${trimmedRaw} \u2192 ${formatted}`);
118391
117863
  }
118392
117864
  return false;
118393
117865
  }
118394
- function normalizeKeywordTextList(texts, matchTypeRaw, path62, fieldLabel, errors, warnings, lengthViolations) {
117866
+ function normalizeKeywordTextList(texts, matchTypeRaw, path61, fieldLabel, errors, warnings, lengthViolations) {
118395
117867
  const declaredUi = matchTypeV2ToUi(matchTypeRaw);
118396
117868
  const normalized = [];
118397
117869
  const seen = /* @__PURE__ */ new Set();
@@ -118400,7 +117872,7 @@ function normalizeKeywordTextList(texts, matchTypeRaw, path62, fieldLabel, error
118400
117872
  for (let k = 0; k < texts.length; k++) {
118401
117873
  const raw = texts[k];
118402
117874
  if (typeof raw !== "string" || !raw.trim()) {
118403
- errors.push(`${path62}.${fieldLabel}[${k}] \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`);
117875
+ errors.push(`${path61}.${fieldLabel}[${k}] \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`);
118404
117876
  continue;
118405
117877
  }
118406
117878
  const trimmedRaw = collapseDuplicateSpacesInKeywordText(raw.trim());
@@ -118411,7 +117883,7 @@ function normalizeKeywordTextList(texts, matchTypeRaw, path62, fieldLabel, error
118411
117883
  );
118412
117884
  if (pushKeywordAutoFixWarning(
118413
117885
  warnings,
118414
- path62,
117886
+ path61,
118415
117887
  fieldLabel,
118416
117888
  trimmedRaw,
118417
117889
  formatted,
@@ -118423,11 +117895,11 @@ function normalizeKeywordTextList(texts, matchTypeRaw, path62, fieldLabel, error
118423
117895
  bareWrapped++;
118424
117896
  }
118425
117897
  const core = unwrapKeywordDisplayTextForEdit(formatted);
118426
- if (!validateKeywordCore(core, `${path62}.${fieldLabel}[${k}]`, errors, lengthViolations))
117898
+ if (!validateKeywordCore(core, `${path61}.${fieldLabel}[${k}]`, errors, lengthViolations))
118427
117899
  continue;
118428
117900
  const dedupeKey = `${matchTypeUiToV2(matchType)}:${core.toLowerCase()}`;
118429
117901
  if (seen.has(dedupeKey)) {
118430
- warnings.push(`${path62}.${fieldLabel}[${k}] \u4E0E\u540C\u7EC4\u91CD\u590D\uFF0C\u5DF2\u8DF3\u8FC7\uFF1A${formatted}`);
117902
+ warnings.push(`${path61}.${fieldLabel}[${k}] \u4E0E\u540C\u7EC4\u91CD\u590D\uFF0C\u5DF2\u8DF3\u8FC7\uFF1A${formatted}`);
118431
117903
  continue;
118432
117904
  }
118433
117905
  seen.add(dedupeKey);
@@ -118436,17 +117908,17 @@ function normalizeKeywordTextList(texts, matchTypeRaw, path62, fieldLabel, error
118436
117908
  }
118437
117909
  if (bareWrapped > 0 && declaredUi) {
118438
117910
  warnings.push(
118439
- `${path62}.${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`
117911
+ `${path61}.${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`
118440
117912
  );
118441
117913
  }
118442
117914
  return { normalized, resolvedUi };
118443
117915
  }
118444
- function normalizeKeywordsForBatchJobBlock(block, path62, errors, warnings, lengthViolations) {
117916
+ function normalizeKeywordsForBatchJobBlock(block, path61, errors, warnings, lengthViolations) {
118445
117917
  const matchTypeRaw = readBlockMatchTypeRaw(block);
118446
117918
  const declaredUi = matchTypeV2ToUi(matchTypeRaw);
118447
117919
  if (matchTypeRaw !== void 0 && declaredUi === null) {
118448
117920
  errors.push(
118449
- `${path62}.MatchTypeV2 \u65E0\u6548\uFF08${String(matchTypeRaw)}\uFF09\uFF0C\u5408\u6CD5\u503C\uFF1ABROAD | PHRASE | EXACT`
117921
+ `${path61}.MatchTypeV2 \u65E0\u6548\uFF08${String(matchTypeRaw)}\uFF09\uFF0C\u5408\u6CD5\u503C\uFF1ABROAD | PHRASE | EXACT`
118450
117922
  );
118451
117923
  return;
118452
117924
  }
@@ -118461,7 +117933,7 @@ function normalizeKeywordsForBatchJobBlock(block, path62, errors, warnings, leng
118461
117933
  const result = normalizeKeywordTextList(
118462
117934
  texts,
118463
117935
  matchTypeRaw,
118464
- path62,
117936
+ path61,
118465
117937
  "KeywordText",
118466
117938
  errors,
118467
117939
  warnings,
@@ -118470,7 +117942,7 @@ function normalizeKeywordsForBatchJobBlock(block, path62, errors, warnings, leng
118470
117942
  normalizedTexts = result.normalized;
118471
117943
  if (result.resolvedUi) resolvedUi = result.resolvedUi;
118472
117944
  if (normalizedTexts.length === 0 && texts.length > 0) {
118473
- errors.push(`${path62}.KeywordText \u7ECF\u6821\u9A8C\u540E\u65E0\u6709\u6548\u5173\u952E\u8BCD\uFF0C\u8BF7\u4FEE\u6B63\u8BCD\u9762\u6216 MatchTypeV2`);
117945
+ errors.push(`${path61}.KeywordText \u7ECF\u6821\u9A8C\u540E\u65E0\u6709\u6548\u5173\u952E\u8BCD\uFF0C\u8BF7\u4FEE\u6B63\u8BCD\u9762\u6216 MatchTypeV2`);
118474
117946
  }
118475
117947
  }
118476
117948
  if (hasItems && items3) {
@@ -118478,12 +117950,12 @@ function normalizeKeywordsForBatchJobBlock(block, path62, errors, warnings, leng
118478
117950
  for (let k = 0; k < items3.length; k++) {
118479
117951
  const item = items3[k];
118480
117952
  if (!item || typeof item !== "object") {
118481
- errors.push(`${path62}.Items[${k}] \u5FC5\u987B\u662F\u5BF9\u8C61`);
117953
+ errors.push(`${path61}.Items[${k}] \u5FC5\u987B\u662F\u5BF9\u8C61`);
118482
117954
  continue;
118483
117955
  }
118484
117956
  const raw = readItemText(item);
118485
117957
  if (raw === null || !raw.trim()) {
118486
- errors.push(`${path62}.Items[${k}].Text \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`);
117958
+ errors.push(`${path61}.Items[${k}].Text \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`);
118487
117959
  continue;
118488
117960
  }
118489
117961
  const trimmedRaw = collapseDuplicateSpacesInKeywordText(raw.trim());
@@ -118494,7 +117966,7 @@ function normalizeKeywordsForBatchJobBlock(block, path62, errors, warnings, leng
118494
117966
  );
118495
117967
  if (pushKeywordAutoFixWarning(
118496
117968
  warnings,
118497
- path62,
117969
+ path61,
118498
117970
  `Items[${k}].Text`,
118499
117971
  trimmedRaw,
118500
117972
  formatted,
@@ -118503,14 +117975,14 @@ function normalizeKeywordsForBatchJobBlock(block, path62, errors, warnings, leng
118503
117975
  matchType,
118504
117976
  inferredMatchType
118505
117977
  )) {
118506
- warnings.push(`${path62}.Items[${k}].Text \u5DF2\u6309\u5757\u7EA7\u5339\u914D\u7C7B\u578B\u81EA\u52A8\u4FEE\u590D\u4E3A\uFF1A${formatted}`);
117978
+ warnings.push(`${path61}.Items[${k}].Text \u5DF2\u6309\u5757\u7EA7\u5339\u914D\u7C7B\u578B\u81EA\u52A8\u4FEE\u590D\u4E3A\uFF1A${formatted}`);
118507
117979
  }
118508
117980
  const core = unwrapKeywordDisplayTextForEdit(formatted);
118509
- if (!validateKeywordCore(core, `${path62}.Items[${k}].Text`, errors, lengthViolations))
117981
+ if (!validateKeywordCore(core, `${path61}.Items[${k}].Text`, errors, lengthViolations))
118510
117982
  continue;
118511
117983
  const dedupeKey = `${matchTypeUiToV2(matchType)}:${core.toLowerCase()}`;
118512
117984
  if (seen.has(dedupeKey)) {
118513
- warnings.push(`${path62}.Items[${k}].Text \u4E0E\u540C\u7EC4\u91CD\u590D\uFF0C\u5DF2\u8DF3\u8FC7\uFF1A${formatted}`);
117985
+ warnings.push(`${path61}.Items[${k}].Text \u4E0E\u540C\u7EC4\u91CD\u590D\uFF0C\u5DF2\u8DF3\u8FC7\uFF1A${formatted}`);
118514
117986
  continue;
118515
117987
  }
118516
117988
  seen.add(dedupeKey);
@@ -118656,16 +118128,16 @@ function warnIfNegativeKeywordsInPositiveKeywords(campaign, warnings) {
118656
118128
  const raw = texts[ki];
118657
118129
  if (typeof raw !== "string" || !raw.trim()) continue;
118658
118130
  const core = normalizeKeywordCoreForNegativeCheck(raw);
118659
- const path62 = `campaign.AdGroupsForBatchJob[${gi}].KeywordsForBatchJob[${bi}].KeywordText[${ki}]`;
118131
+ const path61 = `campaign.AdGroupsForBatchJob[${gi}].KeywordsForBatchJob[${bi}].KeywordText[${ki}]`;
118660
118132
  if (plannedNegCores.has(core)) {
118661
118133
  warnings.push(
118662
- `${path62} \u8BCD\u9762\u300C${raw}\u300D\u5DF2\u51FA\u73B0\u5728 campaign.NegativeKeywordsForBatchJob\uFF0C\u4E0D\u5E94\u91CD\u590D\u5199\u5165\u6B63\u5411 KeywordsForBatchJob\uFF1B\u5426\u8BCD\u53EA\u653E NegativeKeywordsForBatchJob`
118134
+ `${path61} \u8BCD\u9762\u300C${raw}\u300D\u5DF2\u51FA\u73B0\u5728 campaign.NegativeKeywordsForBatchJob\uFF0C\u4E0D\u5E94\u91CD\u590D\u5199\u5165\u6B63\u5411 KeywordsForBatchJob\uFF1B\u5426\u8BCD\u53EA\u653E NegativeKeywordsForBatchJob`
118663
118135
  );
118664
118136
  continue;
118665
118137
  }
118666
118138
  if (looksLikeStandaloneNegativeKeyword(core)) {
118667
118139
  warnings.push(
118668
- `${path62} \u8BCD\u9762\u300C${raw}\u300D\u7591\u4F3C\u5426\u5B9A\u5173\u952E\u8BCD\uFF08\u5E38\u89C1\u5426\u8BCD\u8BCD\u6839\uFF09\uFF0C\u5E94\u5199\u5165 campaign.NegativeKeywordsForBatchJob\uFF08MatchTypeV2: BROAD\uFF09\uFF0C\u52FF\u653E\u5165 KeywordsForBatchJob`
118140
+ `${path61} \u8BCD\u9762\u300C${raw}\u300D\u7591\u4F3C\u5426\u5B9A\u5173\u952E\u8BCD\uFF08\u5E38\u89C1\u5426\u8BCD\u8BCD\u6839\uFF09\uFF0C\u5E94\u5199\u5165 campaign.NegativeKeywordsForBatchJob\uFF08MatchTypeV2: BROAD\uFF09\uFF0C\u52FF\u653E\u5165 KeywordsForBatchJob`
118669
118141
  );
118670
118142
  }
118671
118143
  }
@@ -121065,8 +120537,8 @@ function normalizePlacementUrl(raw) {
121065
120537
  if (parts.length > 2) {
121066
120538
  throw new Error("\u7248\u4F4D\u7F51\u5740\u6700\u591A\u4E24\u7EA7\u8DEF\u5F84\uFF0C\u4F8B\u5982 http://www.domain.com/news/2024");
121067
120539
  }
121068
- const path62 = parts.length > 0 ? `/${parts.join("/")}` : "";
121069
- return `${url.protocol}//${host}${path62}`;
120540
+ const path61 = parts.length > 0 ? `/${parts.join("/")}` : "";
120541
+ return `${url.protocol}//${host}${path61}`;
121070
120542
  }
121071
120543
  var GROUP_LABEL = {
121072
120544
  sensitive: "\u654F\u611F\u5185\u5BB9",
@@ -121812,7 +121284,7 @@ async function runAdPmaxBrandsDetach(opts) {
121812
121284
  \u2705 \u5DF2\u4ECE\u7CFB\u5217 ${campaignId} \u5378\u4E0B\u54C1\u724C\u5217\u8868 ${criterionId}
121813
121285
  `);
121814
121286
  }
121815
- async function listCampaignRows(opts, path62, label2) {
121287
+ async function listCampaignRows(opts, path61, label2) {
121816
121288
  let campaignId;
121817
121289
  try {
121818
121290
  campaignId = requireCampaignId(opts.campaignId, label2);
@@ -121820,7 +121292,7 @@ async function listCampaignRows(opts, path62, label2) {
121820
121292
  fail(err, "\u53C2\u6570");
121821
121293
  }
121822
121294
  const { config, base: base2, account } = accountBase(opts);
121823
- const url = `${base2}/campaignmanagement/accounts/${account}/${path62}?campaignId=${campaignId}`;
121295
+ const url = `${base2}/campaignmanagement/accounts/${account}/${path61}?campaignId=${campaignId}`;
121824
121296
  let items3;
121825
121297
  try {
121826
121298
  items3 = unwrapItems(await apiFetch2(url, config, {}, opts.verbose));
@@ -121929,17 +121401,17 @@ async function runAdPmaxUrlsAdd(opts) {
121929
121401
  async function runAdPmaxUrlsRemove(opts) {
121930
121402
  await removeCampaignCriterion(opts, "pmax-urls", "\u7F51\u5740\u6392\u9664");
121931
121403
  }
121932
- async function removeCampaignCriterion(opts, path62, label2) {
121404
+ async function removeCampaignCriterion(opts, path61, label2) {
121933
121405
  let campaignId;
121934
121406
  let criterionId;
121935
121407
  try {
121936
- campaignId = requireCampaignId(opts.campaignId, path62);
121408
+ campaignId = requireCampaignId(opts.campaignId, path61);
121937
121409
  criterionId = requireDigits(opts.criterionId, "--criterion-id");
121938
121410
  } catch (err) {
121939
121411
  fail(err, "\u53C2\u6570");
121940
121412
  }
121941
121413
  const { config, base: base2, account } = accountBase(opts);
121942
- const url = `${base2}/campaignmanagement/accounts/${account}/${path62}/${criterionId}?campaignId=${campaignId}`;
121414
+ const url = `${base2}/campaignmanagement/accounts/${account}/${path61}/${criterionId}?campaignId=${campaignId}`;
121943
121415
  try {
121944
121416
  await apiDeleteRaw(url, config, { verbose: opts.verbose });
121945
121417
  } catch (err) {
@@ -123901,7 +123373,7 @@ function buildBatchOperationSlots(cfg) {
123901
123373
  const campaign = asRecord3(cfg.campaign) ?? {};
123902
123374
  const names = Array.isArray(cfg.locations) ? cfg.locations : [];
123903
123375
  const slots = [];
123904
- const push = (kind, path62, label2) => slots.push({ index: slots.length, kind, path: path62, label: label2 });
123376
+ const push = (kind, path61, label2) => slots.push({ index: slots.length, kind, path: path61, label: label2 });
123905
123377
  push("campaign_budget", "campaign.Budget", "\u7CFB\u5217\u9884\u7B97");
123906
123378
  push("campaign", "campaign.Name", `\u7CFB\u5217\u300C${pickText(campaign, "Name", "name") || "\u2014"}\u300D`);
123907
123379
  pickArray(campaign, "targetedLocations", "TargetedLocations").forEach((loc, i) => {
@@ -124480,13 +123952,13 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124480
123952
  for (let ki = 0; ki < texts.length; ki++) {
124481
123953
  const t = texts[ki];
124482
123954
  if (typeof t !== "string" || !t.trim()) continue;
124483
- const path62 = `${groupPath}.KeywordsForBatchJob[${bi}].KeywordText[${ki}]`;
123955
+ const path61 = `${groupPath}.KeywordsForBatchJob[${bi}].KeywordText[${ki}]`;
124484
123956
  const key = keywordKey(t, matchTypeV2);
124485
123957
  const plannedContent = `\u8BCD\u9762: ${t} | \u5339\u914D: ${matchTypeV2}`;
124486
123958
  if (groupAbsent) {
124487
123959
  pushItem(items3, {
124488
123960
  layer: "keyword",
124489
- path: path62,
123961
+ path: path61,
124490
123962
  adGroupName: groupName,
124491
123963
  plannedContent,
124492
123964
  status: "skipped",
@@ -124498,7 +123970,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124498
123970
  if (!liveKwKeys.has(key)) {
124499
123971
  pushItem(items3, {
124500
123972
  layer: "keyword",
124501
- path: path62,
123973
+ path: path61,
124502
123974
  adGroupName: groupName,
124503
123975
  plannedContent,
124504
123976
  status: "missing",
@@ -124508,7 +123980,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124508
123980
  } else {
124509
123981
  pushItem(items3, {
124510
123982
  layer: "keyword",
124511
- path: path62,
123983
+ path: path61,
124512
123984
  adGroupName: groupName,
124513
123985
  plannedContent,
124514
123986
  status: "ok",
@@ -124528,7 +124000,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124528
124000
  for (let ai = 0; ai < ads.length; ai++) {
124529
124001
  const ad = asRecord4(ads[ai]);
124530
124002
  if (!ad) continue;
124531
- const path62 = `${groupPath}.AdsForBatchJob[${ai}]`;
124003
+ const path61 = `${groupPath}.AdsForBatchJob[${ai}]`;
124532
124004
  const primary = pickString2(ad["headlinePart1"], ad["AdTitle"]);
124533
124005
  const finalUrl = pickString2(ad["Finalurl"], ad["DestinationUrl"], ad["finalUrl"]);
124534
124006
  const rsaAssets = listPlannedRsaAssets(ad, groupPath, ai, groupName);
@@ -124537,7 +124009,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124537
124009
  if (groupAbsent) {
124538
124010
  pushItem(items3, {
124539
124011
  layer: "ad",
124540
- path: path62,
124012
+ path: path61,
124541
124013
  adGroupName: groupName,
124542
124014
  adLabel,
124543
124015
  plannedContent: primary ? `RSA \u9996\u6807\u9898: ${primary}${finalUrl ? ` | \u843D\u5730\u9875: ${finalUrl}` : ""}` : `AdsForBatchJob[${ai}]\uFF08\u7F3A\u5C11 headlinePart1\uFF09`,
@@ -124566,7 +124038,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124566
124038
  if (!primary) {
124567
124039
  pushItem(items3, {
124568
124040
  layer: "ad",
124569
- path: path62,
124041
+ path: path61,
124570
124042
  adGroupName: groupName,
124571
124043
  adLabel,
124572
124044
  plannedContent: `AdsForBatchJob[${ai}]\uFF08\u7F3A\u5C11 headlinePart1\uFF0C\u65E0\u6CD5\u6BD4\u5BF9\u6574\u6761 RSA\uFF09`,
@@ -124594,7 +124066,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124594
124066
  const rsaFound = matchedLive != null && liveAdHasHeadline(matchedLive, primary);
124595
124067
  pushItem(items3, {
124596
124068
  layer: "ad",
124597
- path: path62,
124069
+ path: path61,
124598
124070
  adGroupName: groupName,
124599
124071
  adLabel,
124600
124072
  plannedContent: `RSA \u9996\u6807\u9898: ${primary}${finalUrl ? ` | \u843D\u5730\u9875: ${finalUrl}` : ""}`,
@@ -124668,14 +124140,14 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124668
124140
  for (let ei = 0; ei < extBlocks.length; ei++) {
124669
124141
  const ext = asRecord4(extBlocks[ei]);
124670
124142
  const plannedContent = formatExtensionPlanned(ext);
124671
- const path62 = `campaign.ExtensionsForBatchJob[${ei}]`;
124143
+ const path61 = `campaign.ExtensionsForBatchJob[${ei}]`;
124672
124144
  const key = ext ? extensionContentKey(ext) : "";
124673
124145
  const plannedEntry = plannedExtByKey.get(key);
124674
124146
  plannedExtByKey.set(key, { count: (plannedEntry?.count ?? 0) + 1, plannedContent });
124675
124147
  if (campaignMissing) {
124676
124148
  pushItem(items3, {
124677
124149
  layer: "extension",
124678
- path: path62,
124150
+ path: path61,
124679
124151
  plannedContent,
124680
124152
  status: "skipped",
124681
124153
  liveNote: "\u7CFB\u5217\u672A\u627E\u5230\uFF0C\u8DF3\u8FC7\u9644\u52A0\u4FE1\u606F\u6BD4\u5BF9",
@@ -124686,7 +124158,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124686
124158
  if (live.extensionsError) {
124687
124159
  pushItem(items3, {
124688
124160
  layer: "extension",
124689
- path: path62,
124161
+ path: path61,
124690
124162
  plannedContent,
124691
124163
  status: "skipped",
124692
124164
  liveNote: `\u9644\u52A0\u4FE1\u606F\u67E5\u8BE2\u5931\u8D25\uFF0C\u672A\u6BD4\u5BF9\uFF1A${live.extensionsError}`,
@@ -124701,7 +124173,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124701
124173
  if (!found && live.extensionsSource === "account-fallback") {
124702
124174
  pushItem(items3, {
124703
124175
  layer: "extension",
124704
- path: path62,
124176
+ path: path61,
124705
124177
  plannedContent,
124706
124178
  status: "skipped",
124707
124179
  liveNote: `\u6574\u6237\u5217\u8868\u53EA\u542B\u8FD1 30 \u5929\u6709\u5C55\u793A\u7684\u9644\u52A0\u4FE1\u606F\uFF0C\u67E5\u5230 ${liveExt}/${plannedExt} \u6761\uFF0C\u5176\u4F59\u65E0\u6CD5\u786E\u8BA4`,
@@ -124712,7 +124184,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124712
124184
  const remediateCommand = !found && ext && accountId && campaignId ? buildExtensionRemediateCommandLine({ accountId, campaignId, ext }) ?? void 0 : void 0;
124713
124185
  pushItem(items3, {
124714
124186
  layer: "extension",
124715
- path: path62,
124187
+ path: path61,
124716
124188
  plannedContent,
124717
124189
  status: found ? "ok" : "missing",
124718
124190
  liveNote: `\u7CFB\u5217\u4E0A\u540C\u5185\u5BB9 ${sameContent} \u6761\uFF08\u7CFB\u5217\u7EA7\u9644\u52A0\u4FE1\u606F\u5171 ${liveExt} \u6761\uFF0C\u8BA1\u5212 ${plannedExt} \u6761\uFF09`,
@@ -124752,11 +124224,11 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124752
124224
  if (!id) continue;
124753
124225
  const displayName = locationNames[li] || pickString2(loc["locationName"], loc["name"], loc["countryOrRegion"]) || "";
124754
124226
  const plannedContent = `locationId: ${id}${displayName ? ` | \u540D\u79F0: ${displayName}` : ""}`;
124755
- const path62 = `campaign.targetedLocations[${li}]`;
124227
+ const path61 = `campaign.targetedLocations[${li}]`;
124756
124228
  if (campaignMissing) {
124757
124229
  pushItem(items3, {
124758
124230
  layer: "location",
124759
- path: path62,
124231
+ path: path61,
124760
124232
  plannedContent,
124761
124233
  status: "skipped",
124762
124234
  liveNote: "\u7CFB\u5217\u672A\u627E\u5230\uFF0C\u8DF3\u8FC7\u5730\u57DF\u6BD4\u5BF9",
@@ -124768,7 +124240,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124768
124240
  const remediateCommand = !found && accountId && campaignId ? buildGeoRemediateCommandLine({ accountId, campaignId, locationId: id }) : void 0;
124769
124241
  pushItem(items3, {
124770
124242
  layer: "location",
124771
- path: path62,
124243
+ path: path61,
124772
124244
  plannedContent,
124773
124245
  status: found ? "ok" : "missing",
124774
124246
  liveNote: `\u7CFB\u5217\u5DF2\u5B9A\u5411 ${liveLocIds.size}/${plannedLocCount} \u4E2A\u5730\u57DF`,
@@ -124811,12 +124283,12 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124811
124283
  const loc = asRecord4(plannedExcl[li]);
124812
124284
  const id = loc ? pickString2(loc["id"], loc["Id"]) : "";
124813
124285
  if (!id) continue;
124814
- const path62 = `campaign.excludedLocations[${li}]`;
124286
+ const path61 = `campaign.excludedLocations[${li}]`;
124815
124287
  const plannedContent = `\u6392\u9664 locationId: ${id}`;
124816
124288
  if (campaignMissing) {
124817
124289
  pushItem(items3, {
124818
124290
  layer: "excluded_location",
124819
- path: path62,
124291
+ path: path61,
124820
124292
  plannedContent,
124821
124293
  status: "skipped",
124822
124294
  liveNote: "\u7CFB\u5217\u672A\u627E\u5230\uFF0C\u8DF3\u8FC7\u6392\u9664\u5730\u57DF\u6BD4\u5BF9",
@@ -124827,7 +124299,7 @@ function compareCampaignCreateToLive(cfg, campaignId, live, meta) {
124827
124299
  const found = liveExclIds.has(id);
124828
124300
  pushItem(items3, {
124829
124301
  layer: "excluded_location",
124830
- path: path62,
124302
+ path: path61,
124831
124303
  plannedContent,
124832
124304
  status: found ? "ok" : "missing",
124833
124305
  liveNote: `\u7CFB\u5217\u5DF2\u6392\u9664 ${liveExclIds.size}/${plannedExclCount} \u4E2A\u5730\u57DF`,
@@ -126571,8 +126043,8 @@ function pmaxChannelTypesUrl(googleApiUrl) {
126571
126043
  }
126572
126044
  function pmaxCampaignUrl(googleApiUrl, accountId, campaignId) {
126573
126045
  const base2 = googleApiUrl.replace(/\/$/, "");
126574
- const path62 = `${base2}/accounts/${accountId}/campaign/pmax`;
126575
- return campaignId ? `${path62}/${campaignId}` : path62;
126046
+ const path61 = `${base2}/accounts/${accountId}/campaign/pmax`;
126047
+ return campaignId ? `${path61}/${campaignId}` : path61;
126576
126048
  }
126577
126049
  function pmaxBrandAssetsUrl(googleApiUrl, accountId, campaignId) {
126578
126050
  return `${pmaxCampaignUrl(googleApiUrl, accountId, campaignId)}/brand-assets`;
@@ -126582,8 +126054,8 @@ function pmaxBrandGuidelinesEnableUrl(googleApiUrl, accountId, campaignId) {
126582
126054
  }
126583
126055
  function pmaxAssetGroupUrl(googleApiUrl, accountId, assetGroupId, suffix) {
126584
126056
  const base2 = googleApiUrl.replace(/\/$/, "");
126585
- const path62 = `${base2}/accounts/${accountId}/campaign/pmax/asset-group/${assetGroupId}`;
126586
- return suffix ? `${path62}/${suffix.replace(/^\//, "")}` : path62;
126057
+ const path61 = `${base2}/accounts/${accountId}/campaign/pmax/asset-group/${assetGroupId}`;
126058
+ return suffix ? `${path61}/${suffix.replace(/^\//, "")}` : path61;
126587
126059
  }
126588
126060
  function pmaxCampaignAssetGroupUrl(googleApiUrl, accountId, campaignId) {
126589
126061
  const base2 = googleApiUrl.replace(/\/$/, "");
@@ -129565,8 +129037,8 @@ async function runAdPmaxImageConvert(opts) {
129565
129037
  }
129566
129038
 
129567
129039
  // src/commands/ad/pmax-brand-mgmt.ts
129568
- function loadBrandConfig(path62, accountId, campaignId) {
129569
- const cfg = loadPmaxJsonFile(path62);
129040
+ function loadBrandConfig(path61, accountId, campaignId) {
129041
+ const cfg = loadPmaxJsonFile(path61);
129570
129042
  return {
129571
129043
  ...cfg,
129572
129044
  account: String(cfg["account"] ?? accountId).trim(),
@@ -130335,12 +129807,12 @@ function demandGenConversionsValidateUrl(googleApiUrl, accountId) {
130335
129807
  return `${demandGenCollectionUrl(googleApiUrl, accountId)}/conversions/validate`;
130336
129808
  }
130337
129809
  function demandGenAdGroupUrl(googleApiUrl, accountId, campaignId, adGroupId, suffix) {
130338
- const path62 = `${demandGenCampaignUrl(googleApiUrl, accountId, campaignId)}/ad-groups/${adGroupId}`;
130339
- return suffix ? `${path62}/${suffix.replace(/^\//, "")}` : path62;
129810
+ const path61 = `${demandGenCampaignUrl(googleApiUrl, accountId, campaignId)}/ad-groups/${adGroupId}`;
129811
+ return suffix ? `${path61}/${suffix.replace(/^\//, "")}` : path61;
130340
129812
  }
130341
129813
  function demandGenAdUrl(googleApiUrl, accountId, campaignId, adGroupId, adId, suffix) {
130342
- const path62 = `${demandGenAdGroupUrl(googleApiUrl, accountId, campaignId, adGroupId)}/ads/${adId}`;
130343
- return suffix ? `${path62}/${suffix.replace(/^\//, "")}` : path62;
129814
+ const path61 = `${demandGenAdGroupUrl(googleApiUrl, accountId, campaignId, adGroupId)}/ads/${adId}`;
129815
+ return suffix ? `${path61}/${suffix.replace(/^\//, "")}` : path61;
130344
129816
  }
130345
129817
  function demandGenChannelReportUrl(googleApiUrl, accountId, campaignId, startDate, endDate) {
130346
129818
  const params = new URLSearchParams({ startDate, endDate });
@@ -130444,7 +129916,7 @@ function explainCreateError(err) {
130444
129916
  if (failure) return demandGenResumeHint(failure);
130445
129917
  return err instanceof Error ? err.message : String(err);
130446
129918
  }
130447
- async function postCreate(opts, path62, commandLabel) {
129919
+ async function postCreate(opts, path61, commandLabel) {
130448
129920
  const accountId = requireAccountId(opts.account);
130449
129921
  const raw = loadBody(opts.configFile);
130450
129922
  await withGoogleApi(opts, async (config, googleApiUrl) => {
@@ -130456,7 +129928,7 @@ async function postCreate(opts, path62, commandLabel) {
130456
129928
  fail4(err instanceof Error ? err.message : String(err));
130457
129929
  }
130458
129930
  printIssues(demandGenCreateIssues(body));
130459
- const url = path62 ? `${demandGenCollectionUrl(googleApiUrl, accountId)}/${path62}` : demandGenCollectionUrl(googleApiUrl, accountId);
129931
+ const url = path61 ? `${demandGenCollectionUrl(googleApiUrl, accountId)}/${path61}` : demandGenCollectionUrl(googleApiUrl, accountId);
130460
129932
  let data;
130461
129933
  try {
130462
129934
  data = await pmaxApiFetch(
@@ -130469,7 +129941,7 @@ async function postCreate(opts, path62, commandLabel) {
130469
129941
  fail4(explainCreateError(err));
130470
129942
  }
130471
129943
  const payload = decorateDemandGenRead(data);
130472
- if (await emit({ ...opts, account: accountId }, `ad-demand-gen-${path62 || "create"}`, commandLabel, payload, accountId)) {
129944
+ if (await emit({ ...opts, account: accountId }, `ad-demand-gen-${path61 || "create"}`, commandLabel, payload, accountId)) {
130473
129945
  return;
130474
129946
  }
130475
129947
  console.log(`
@@ -131133,8 +130605,8 @@ function coverageRefusal(kind) {
131133
130605
  const normalized = (kind ?? "").trim().toLowerCase();
131134
130606
  return COVERAGE_REFUSED[normalized];
131135
130607
  }
131136
- function coverageUrl(googleApiUrl, accountId, path62) {
131137
- return `${googleApiUrl.replace(/\/$/, "")}/accounts/${accountId}/ads-coverage/${path62}`;
130608
+ function coverageUrl(googleApiUrl, accountId, path61) {
130609
+ return `${googleApiUrl.replace(/\/$/, "")}/accounts/${accountId}/ads-coverage/${path61}`;
131138
130610
  }
131139
130611
  function fail5(message) {
131140
130612
  console.error(`
@@ -131142,7 +130614,7 @@ function fail5(message) {
131142
130614
  `);
131143
130615
  process.exit(1);
131144
130616
  }
131145
- async function postCoverage(opts, path62, section, commandLabel) {
130617
+ async function postCoverage(opts, path61, section, commandLabel) {
131146
130618
  const accountId = requireAccountId(opts.account);
131147
130619
  const raw = loadPmaxJsonFile(opts.configFile);
131148
130620
  const kind = String(opts.kind ?? raw["kind"] ?? "");
@@ -131153,7 +130625,7 @@ async function postCoverage(opts, path62, section, commandLabel) {
131153
130625
  let data;
131154
130626
  try {
131155
130627
  data = await pmaxApiFetch(
131156
- coverageUrl(googleApiUrl, accountId, path62),
130628
+ coverageUrl(googleApiUrl, accountId, path61),
131157
130629
  config,
131158
130630
  { method: "POST", body: JSON.stringify(body) },
131159
130631
  opts.verbose
@@ -133030,9 +132502,9 @@ function metaAdContext(token) {
133030
132502
  const config = loadConfig(token);
133031
132503
  return { config, facebookApiUrl: requireFacebookApi(config) };
133032
132504
  }
133033
- function adsUrl(facebookApiUrl, account, path62) {
132505
+ function adsUrl(facebookApiUrl, account, path61) {
133034
132506
  const base2 = metaAdsBaseUrl(facebookApiUrl, account);
133035
- const p = path62.startsWith("/") ? path62 : `/${path62}`;
132507
+ const p = path61.startsWith("/") ? path61 : `/${path61}`;
133036
132508
  return `${base2}${p}`;
133037
132509
  }
133038
132510
  async function metaAdGet(url, config, verbose, action) {
@@ -134245,9 +133717,9 @@ async function runMetaAdForms(opts) {
134245
133717
  if (opts.after) params.set("after", opts.after);
134246
133718
  if (opts.before) params.set("before", opts.before);
134247
133719
  const qs = params.toString();
134248
- const path62 = `/pages/${encodeURIComponent(opts.pageId)}/forms${qs ? `?${qs}` : ""}`;
133720
+ const path61 = `/pages/${encodeURIComponent(opts.pageId)}/forms${qs ? `?${qs}` : ""}`;
134249
133721
  const raw = await metaAdGet(
134250
- adsUrl(facebookApiUrl, digits, path62),
133722
+ adsUrl(facebookApiUrl, digits, path61),
134251
133723
  config,
134252
133724
  opts.verbose,
134253
133725
  "\u5217\u8868\u5355\u5931\u8D25"
@@ -134729,10 +134201,10 @@ async function saveNamedFile(fileUrl, dir, id, kind, maxBytes) {
134729
134201
  const temp = join14(dir, `${id}.part`);
134730
134202
  const saved = await downloadPublicFile(fileUrl, temp, maxBytes);
134731
134203
  const ext = extensionForMedia(saved.contentType, saved.head, kind);
134732
- const path62 = join14(dir, `${id}.${ext}`);
134733
- await rm3(path62, { force: true });
134734
- await rename2(temp, path62);
134735
- return { path: path62, bytes: saved.bytes };
134204
+ const path61 = join14(dir, `${id}.${ext}`);
134205
+ await rm3(path61, { force: true });
134206
+ await rename2(temp, path61);
134207
+ return { path: path61, bytes: saved.bytes };
134736
134208
  }
134737
134209
  function startsWith(head, magic) {
134738
134210
  if (head.length < magic.length) return false;
@@ -144127,9 +143599,9 @@ function asRecord12(value) {
144127
143599
  }
144128
143600
  return null;
144129
143601
  }
144130
- function getNestedValue(root, path62) {
143602
+ function getNestedValue(root, path61) {
144131
143603
  let cur = root;
144132
- for (const key of path62) {
143604
+ for (const key of path61) {
144133
143605
  const rec = asRecord12(cur);
144134
143606
  if (!rec) return void 0;
144135
143607
  cur = rec[key];
@@ -146421,14 +145893,14 @@ var FACEBOOK_SECTION_ALIASES = {
146421
145893
  import { Command as Command2 } from "commander";
146422
145894
 
146423
145895
  // src/commands/facebook-analysis/render-report.ts
146424
- import fs41 from "fs";
145896
+ import fs40 from "fs";
146425
145897
  import fsPromises4 from "fs/promises";
146426
- import path48 from "path";
145898
+ import path47 from "path";
146427
145899
  import { fileURLToPath as fileURLToPath11 } from "url";
146428
145900
 
146429
145901
  // src/commands/facebook-analysis/merge-snapshot.ts
146430
- import * as fs40 from "fs/promises";
146431
- import * as path47 from "path";
145902
+ import * as fs39 from "fs/promises";
145903
+ import * as path46 from "path";
146432
145904
 
146433
145905
  // src/commands/facebook-analysis/report-metrics.ts
146434
145906
  function asRecord26(value) {
@@ -146437,11 +145909,11 @@ function asRecord26(value) {
146437
145909
  }
146438
145910
  return null;
146439
145911
  }
146440
- function num9(value) {
145912
+ function num8(value) {
146441
145913
  const n = Number(value);
146442
145914
  return Number.isFinite(n) ? n : void 0;
146443
145915
  }
146444
- function str3(value) {
145916
+ function str2(value) {
146445
145917
  if (value == null) return "";
146446
145918
  return String(value).trim();
146447
145919
  }
@@ -146462,28 +145934,28 @@ function normalizeInsightDate(value) {
146462
145934
  }
146463
145935
  function pickMetricFields(row) {
146464
145936
  return {
146465
- reach: num9(row.reach),
146466
- impressions: num9(row.impressions),
146467
- frequency: num9(row.frequency),
146468
- attributionSetting: str3(row.attributionSetting) || void 0,
146469
- resultType: str3(row.resultType) || void 0,
146470
- results: num9(row.results),
146471
- spend: num9(row.spend),
146472
- costPerResult: num9(row.costPerResult)
145937
+ reach: num8(row.reach),
145938
+ impressions: num8(row.impressions),
145939
+ frequency: num8(row.frequency),
145940
+ attributionSetting: str2(row.attributionSetting) || void 0,
145941
+ resultType: str2(row.resultType) || void 0,
145942
+ results: num8(row.results),
145943
+ spend: num8(row.spend),
145944
+ costPerResult: num8(row.costPerResult)
146473
145945
  };
146474
145946
  }
146475
145947
  function audienceLabel(age, gender) {
146476
- const a = str3(age) || "\u2014";
146477
- const g = str3(gender);
145948
+ const a = str2(age) || "\u2014";
145949
+ const g = str2(gender);
146478
145950
  if (!g) return a;
146479
145951
  const zh = g.toLowerCase() === "male" ? "\u7537" : g.toLowerCase() === "female" ? "\u5973" : g;
146480
145952
  return `${a} \xB7 ${zh}`;
146481
145953
  }
146482
145954
  function genderLabel(gender) {
146483
- const g = str3(gender).toLowerCase();
145955
+ const g = str2(gender).toLowerCase();
146484
145956
  if (g === "male") return "male";
146485
145957
  if (g === "female") return "female";
146486
- return str3(gender) || "unknown";
145958
+ return str2(gender) || "unknown";
146487
145959
  }
146488
145960
  function enumKey(raw) {
146489
145961
  return raw.toLowerCase().replace(/[\s_\-./]+/g, "");
@@ -146523,7 +145995,7 @@ var OBJECTIVE_ZH = {
146523
145995
  catalogsales: "\u76EE\u5F55\u9500\u552E"
146524
145996
  };
146525
145997
  function displayResultType(raw) {
146526
- const v = str3(raw);
145998
+ const v = str2(raw);
146527
145999
  if (!v) return "";
146528
146000
  const key = enumKey(v);
146529
146001
  if (key === "lead" || key === "leads" || key.includes("leadgrouped") || key.includes("instantform") || key === "onsiteconversionleadgrouped") {
@@ -146532,12 +146004,12 @@ function displayResultType(raw) {
146532
146004
  return RESULT_TYPE_ZH[key] ?? v;
146533
146005
  }
146534
146006
  function displayObjective(raw) {
146535
- const v = str3(raw);
146007
+ const v = str2(raw);
146536
146008
  if (!v) return "";
146537
146009
  return OBJECTIVE_ZH[enumKey(v)] ?? v;
146538
146010
  }
146539
146011
  function displayAttribution(raw) {
146540
- const v = str3(raw);
146012
+ const v = str2(raw);
146541
146013
  if (!v) return "";
146542
146014
  const key = enumKey(v);
146543
146015
  if (key === "multiple" || key === "7dclick" || key === "7dclick1dview" || key.includes("7dclick") || key.includes("7dayclick")) {
@@ -146574,13 +146046,13 @@ function localizeFacebookReportLabels(payload) {
146574
146046
  return payload;
146575
146047
  }
146576
146048
  function hasResults(row) {
146577
- const n = num9(row.results);
146049
+ const n = num8(row.results);
146578
146050
  return n != null && n > 0;
146579
146051
  }
146580
146052
 
146581
146053
  // src/commands/facebook-analysis/merge-snapshot.ts
146582
146054
  async function readManifest4(snapshotDir) {
146583
- const entries = await fs40.readdir(snapshotDir);
146055
+ const entries = await fs39.readdir(snapshotDir);
146584
146056
  const manifestNames = entries.filter(
146585
146057
  (n) => n.startsWith("report-manifest") && n.endsWith(".json")
146586
146058
  );
@@ -146590,7 +146062,7 @@ async function readManifest4(snapshotDir) {
146590
146062
  ];
146591
146063
  for (const name2 of ordered) {
146592
146064
  try {
146593
- const raw = await fs40.readFile(path47.join(snapshotDir, name2), "utf8");
146065
+ const raw = await fs39.readFile(path46.join(snapshotDir, name2), "utf8");
146594
146066
  const parsed = JSON.parse(raw);
146595
146067
  if (parsed?.artifacts?.length) return parsed;
146596
146068
  } catch {
@@ -146600,7 +146072,7 @@ async function readManifest4(snapshotDir) {
146600
146072
  }
146601
146073
  async function loadSectionFile3(snapshotDir, file) {
146602
146074
  try {
146603
- const raw = await fs40.readFile(path47.join(snapshotDir, file), "utf8");
146075
+ const raw = await fs39.readFile(path46.join(snapshotDir, file), "utf8");
146604
146076
  return asRecord26(JSON.parse(raw));
146605
146077
  } catch {
146606
146078
  return null;
@@ -146614,22 +146086,22 @@ function mapDailyRows(days) {
146614
146086
  }
146615
146087
  function mapCountryRows(countries, campaignName) {
146616
146088
  return [...countries].map((row) => ({
146617
- countryOrRegion: str3(row.countryOrRegion) || "\u2014",
146618
- campaignName: str3(row.campaignName) || campaignName,
146089
+ countryOrRegion: str2(row.countryOrRegion) || "\u2014",
146090
+ campaignName: str2(row.campaignName) || campaignName,
146619
146091
  ...pickMetricFields(row)
146620
146092
  })).sort((a, b) => (b.spend ?? 0) - (a.spend ?? 0));
146621
146093
  }
146622
146094
  function mapCampaignRows(campaigns) {
146623
146095
  return [...campaigns].map((row) => ({
146624
- campaignId: str3(row.campaignId),
146625
- campaignName: str3(row.campaignName) || "\u2014",
146626
- objective: str3(row.objective) || void 0,
146096
+ campaignId: str2(row.campaignId),
146097
+ campaignName: str2(row.campaignName) || "\u2014",
146098
+ objective: str2(row.objective) || void 0,
146627
146099
  ...pickMetricFields(row)
146628
146100
  })).sort((a, b) => (b.spend ?? 0) - (a.spend ?? 0));
146629
146101
  }
146630
146102
  function mapAudienceRows(audiences) {
146631
146103
  return [...audiences].map((row) => ({
146632
- age: str3(row.age) || "\u2014",
146104
+ age: str2(row.age) || "\u2014",
146633
146105
  gender: genderLabel(row.gender),
146634
146106
  label: audienceLabel(row.age, row.gender),
146635
146107
  ...pickMetricFields(row)
@@ -146637,14 +146109,14 @@ function mapAudienceRows(audiences) {
146637
146109
  }
146638
146110
  function mapAdSetRows(groups) {
146639
146111
  return [...groups].map((row) => ({
146640
- adGroupId: str3(row.adGroupId),
146641
- adGroupName: str3(row.adGroupName) || "\u2014",
146642
- campaignName: str3(row.campaignName) || void 0,
146112
+ adGroupId: str2(row.adGroupId),
146113
+ adGroupName: str2(row.adGroupName) || "\u2014",
146114
+ campaignName: str2(row.campaignName) || void 0,
146643
146115
  ...pickMetricFields(row)
146644
146116
  })).sort((a, b) => (b.spend ?? 0) - (a.spend ?? 0));
146645
146117
  }
146646
146118
  async function mergeFacebookSnapshotIntoReport(payload, snapshotDir) {
146647
- const absDir = path47.resolve(snapshotDir);
146119
+ const absDir = path46.resolve(snapshotDir);
146648
146120
  const manifest = await readManifest4(snapshotDir);
146649
146121
  if (!manifest) {
146650
146122
  throw new Error(
@@ -146691,7 +146163,7 @@ async function mergeFacebookSnapshotIntoReport(payload, snapshotDir) {
146691
146163
  meta.campaignName = campaignRows3[0].campaignName;
146692
146164
  }
146693
146165
  }
146694
- const primaryCampaignName = str3(meta.campaignName) || (campaignRows3.length === 1 ? campaignRows3[0].campaignName : void 0);
146166
+ const primaryCampaignName = str2(meta.campaignName) || (campaignRows3.length === 1 ? campaignRows3[0].campaignName : void 0);
146695
146167
  {
146696
146168
  const daily = sectionMap.get("daily");
146697
146169
  const days = Array.isArray(daily?.days) ? daily.days : [];
@@ -146823,22 +146295,22 @@ function metricHeaders(currency, firstCol) {
146823
146295
  ];
146824
146296
  }
146825
146297
  function moneyText(value) {
146826
- const n = num9(value);
146298
+ const n = num8(value);
146827
146299
  if (n == null) return "\u2014";
146828
146300
  return `$${n.toFixed(2)}`;
146829
146301
  }
146830
- function metricCells2(row) {
146831
- const results = num9(row.results);
146302
+ function metricCells(row) {
146303
+ const results = num8(row.results);
146832
146304
  const showResults = hasResults({ results });
146833
146305
  return [
146834
- num9(row.reach) ?? "",
146835
- num9(row.impressions) ?? "",
146836
- num9(row.frequency) ?? "",
146306
+ num8(row.reach) ?? "",
146307
+ num8(row.impressions) ?? "",
146308
+ num8(row.frequency) ?? "",
146837
146309
  displayAttribution(row.attributionSetting),
146838
146310
  showResults ? displayResultType(row.resultType) : "",
146839
146311
  showResults ? results ?? "" : "",
146840
- num9(row.spend) ?? "",
146841
- showResults ? num9(row.costPerResult) ?? "" : ""
146312
+ num8(row.spend) ?? "",
146313
+ showResults ? num8(row.costPerResult) ?? "" : ""
146842
146314
  ];
146843
146315
  }
146844
146316
  function bullets(value) {
@@ -146858,16 +146330,16 @@ function buildSummaryNarrative(data) {
146858
146330
  const kpis = asRecord27(data.kpis) ?? {};
146859
146331
  const meta = asRecord27(data.meta) ?? {};
146860
146332
  const sections = asRecord27(data.sections) ?? {};
146861
- const period = str3(meta.periodLabel) || `${str3(meta.startDate)} ~ ${str3(meta.endDate)}`.trim();
146862
- const account = str3(meta.accountName) || "Facebook \u5E7F\u544A\u8D26\u6237";
146863
- const campaign = str3(meta.campaignName);
146333
+ const period = str2(meta.periodLabel) || `${str2(meta.startDate)} ~ ${str2(meta.endDate)}`.trim();
146334
+ const account = str2(meta.accountName) || "Facebook \u5E7F\u544A\u8D26\u6237";
146335
+ const campaign = str2(meta.campaignName);
146864
146336
  const resultLabel = displayResultType(kpis.resultType ?? meta.resultType) || "\u6210\u6548";
146865
146337
  const resultNoun = /潜在客户|lead/i.test(resultLabel) ? "\u4E2A\u6F5C\u5728\u5BA2\u6237\u8868\u5355" : `\u4E2A${resultLabel}`;
146866
146338
  const firstQuestion = asRecord27(asArray3(data.fourQuestions)[0]);
146867
- const extra = str3(firstQuestion?.verdict);
146339
+ const extra = str2(firstQuestion?.verdict);
146868
146340
  const spendLine = [
146869
146341
  campaign ? `\uFF08\u5E7F\u544A\u7CFB\u5217\uFF1A${campaign}\uFF09` : "",
146870
- `\u5171\u6D88\u8017 ${moneyText(kpis.spend)}\uFF0C\u83B7\u53D6 ${num9(kpis.results) ?? "\u2014"} ${resultNoun}\uFF0C\u5E73\u5747\u5355\u6B21\u83B7\u5BA2\u6210\u672C ${moneyText(kpis.costPerResult)}\u3002`,
146342
+ `\u5171\u6D88\u8017 ${moneyText(kpis.spend)}\uFF0C\u83B7\u53D6 ${num8(kpis.results) ?? "\u2014"} ${resultNoun}\uFF0C\u5E73\u5747\u5355\u6B21\u83B7\u5BA2\u6210\u672C ${moneyText(kpis.costPerResult)}\u3002`,
146871
146343
  extra
146872
146344
  ].filter(Boolean).join("");
146873
146345
  const partOne = [`\u4E00\u3001${account}${period ? ` ${period}` : ""} Facebook \u5E7F\u544A\u8D26\u6237`, spendLine].join(
@@ -146885,7 +146357,7 @@ function buildSummaryNarrative(data) {
146885
146357
  const recBlocks = asArray3(data.recommendations).map((raw, i) => {
146886
146358
  const rec = asRecord27(raw);
146887
146359
  if (!rec) return "";
146888
- const title = [str3(rec.title), str3(rec.tag)].filter(Boolean).join(" \xB7 ");
146360
+ const title = [str2(rec.title), str2(rec.tag)].filter(Boolean).join(" \xB7 ");
146889
146361
  return numberedSection(i + 1, title || "\u4F18\u5316\u5EFA\u8BAE", bullets(rec.items));
146890
146362
  }).filter(Boolean);
146891
146363
  const partThree = ["\u4E09\u3001\u4E0B\u4E00\u6B65\u4F18\u5316\u5EFA\u8BAE", "", recBlocks.join("\n\n") || "\u672C\u671F\u6682\u65E0\u4F18\u5316\u5EFA\u8BAE\u3002"].join(
@@ -146897,14 +146369,14 @@ function buildMetaPeriodExcelSheets(data) {
146897
146369
  const meta = asRecord27(data.meta) ?? {};
146898
146370
  const kpis = asRecord27(data.kpis) ?? {};
146899
146371
  const tables = asRecord27(data.tables) ?? {};
146900
- const currency = str3(meta.currency) || "USD";
146372
+ const currency = str2(meta.currency) || "USD";
146901
146373
  const resultType = displayResultType(kpis.resultType ?? meta.resultType);
146902
146374
  const attribution = displayAttribution(kpis.attributionSetting ?? meta.attributionSetting);
146903
146375
  const summaryRows = [
146904
146376
  metricHeaders(currency, "\u76EE\u6807"),
146905
146377
  [
146906
146378
  resultType,
146907
- ...metricCells2({
146379
+ ...metricCells({
146908
146380
  ...kpis,
146909
146381
  attributionSetting: attribution,
146910
146382
  resultType
@@ -146917,19 +146389,19 @@ function buildMetaPeriodExcelSheets(data) {
146917
146389
  for (const raw of asArray3(tables.daily)) {
146918
146390
  const row = asRecord27(raw);
146919
146391
  if (!row) continue;
146920
- dailyRows.push([normalizeInsightDate(row.date), ...metricCells2(row)]);
146392
+ dailyRows.push([normalizeInsightDate(row.date), ...metricCells(row)]);
146921
146393
  }
146922
146394
  const countryRows = [metricHeaders(currency, "\u56FD\u5BB6/\u5730\u533A")];
146923
146395
  for (const raw of asArray3(tables.countries)) {
146924
146396
  const row = asRecord27(raw);
146925
146397
  if (!row) continue;
146926
- countryRows.push([str3(row.countryOrRegion), ...metricCells2(row)]);
146398
+ countryRows.push([str2(row.countryOrRegion), ...metricCells(row)]);
146927
146399
  }
146928
146400
  const campaignRows3 = [metricHeaders(currency, "\u5E7F\u544A\u7CFB\u5217\u540D\u79F0")];
146929
146401
  for (const raw of asArray3(tables.campaigns)) {
146930
146402
  const row = asRecord27(raw);
146931
146403
  if (!row) continue;
146932
- campaignRows3.push([str3(row.campaignName), ...metricCells2(row)]);
146404
+ campaignRows3.push([str2(row.campaignName), ...metricCells(row)]);
146933
146405
  }
146934
146406
  const audienceRows = [
146935
146407
  [
@@ -146948,7 +146420,7 @@ function buildMetaPeriodExcelSheets(data) {
146948
146420
  for (const raw of asArray3(tables.audiences)) {
146949
146421
  const row = asRecord27(raw);
146950
146422
  if (!row) continue;
146951
- audienceRows.push([str3(row.age), str3(row.gender), ...metricCells2(row)]);
146423
+ audienceRows.push([str2(row.age), str2(row.gender), ...metricCells(row)]);
146952
146424
  }
146953
146425
  return [
146954
146426
  { name: "\u6C47\u603B\u6570\u636E", rows: summaryRows },
@@ -147266,14 +146738,14 @@ var TEMPLATE_BASENAMES2 = {
147266
146738
  };
147267
146739
  var INJECT_MARKER2 = "window.__META_PERIOD_REPORT__ = window.__META_PERIOD_REPORT__ || null;";
147268
146740
  function resolveSkillTemplatePath5(basename14) {
147269
- const dir = path48.dirname(fileURLToPath11(import.meta.url));
146741
+ const dir = path47.dirname(fileURLToPath11(import.meta.url));
147270
146742
  const candidates = [
147271
- path48.join(dir, "skill", "report-templates", basename14),
147272
- path48.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
147273
- path48.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
146743
+ path47.join(dir, "skill", "report-templates", basename14),
146744
+ path47.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
146745
+ path47.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
147274
146746
  ];
147275
146747
  for (const p of candidates) {
147276
- if (fs41.existsSync(p)) return p;
146748
+ if (fs40.existsSync(p)) return p;
147277
146749
  }
147278
146750
  return candidates[0];
147279
146751
  }
@@ -147319,7 +146791,7 @@ function injectReportData3(html, payload, lang) {
147319
146791
  }
147320
146792
  function defaultOutPath(dataPath, format, out) {
147321
146793
  if (out?.trim()) {
147322
- const resolved = path48.resolve(out);
146794
+ const resolved = path47.resolve(out);
147323
146795
  if (format === "xlsx" && !/\.xlsx$/i.test(resolved)) {
147324
146796
  return resolved.replace(/\.(html?)$/i, ".xlsx");
147325
146797
  }
@@ -147328,14 +146800,14 @@ function defaultOutPath(dataPath, format, out) {
147328
146800
  }
147329
146801
  return resolved;
147330
146802
  }
147331
- const dir = path48.dirname(dataPath);
147332
- return path48.join(dir, format === "xlsx" ? "meta-period-report.xlsx" : "meta-period-report.html");
146803
+ const dir = path47.dirname(dataPath);
146804
+ return path47.join(dir, format === "xlsx" ? "meta-period-report.xlsx" : "meta-period-report.html");
147333
146805
  }
147334
146806
  async function runFacebookAnalysisRender(opts) {
147335
- const dataPath = path48.resolve(opts.dataFile);
146807
+ const dataPath = path47.resolve(opts.dataFile);
147336
146808
  let data = asRecord29(await readJsonFile5(dataPath));
147337
146809
  if (opts.snapshotDir?.trim()) {
147338
- data = await mergeFacebookSnapshotIntoReport(data, path48.resolve(opts.snapshotDir));
146810
+ data = await mergeFacebookSnapshotIntoReport(data, path47.resolve(opts.snapshotDir));
147339
146811
  }
147340
146812
  localizeFacebookReportLabels(data);
147341
146813
  const lang = readReportLangOrExit({ flag: opts.lang, meta: data.meta });
@@ -147355,7 +146827,7 @@ async function runFacebookAnalysisRender(opts) {
147355
146827
  const written = [];
147356
146828
  for (const format of formats) {
147357
146829
  const outPath = defaultOutPath(dataPath, format, opts.out);
147358
- await fsPromises4.mkdir(path48.dirname(outPath), { recursive: true });
146830
+ await fsPromises4.mkdir(path47.dirname(outPath), { recursive: true });
147359
146831
  if (format === "xlsx") {
147360
146832
  writeMetaPeriodExcel(outPath, data, lang);
147361
146833
  } else {
@@ -147391,21 +146863,21 @@ async function runFacebookAnalysisRender(opts) {
147391
146863
  }
147392
146864
 
147393
146865
  // src/commands/facebook-analysis/diagnosis-render-report.ts
147394
- import fs43 from "fs";
146866
+ import fs42 from "fs";
147395
146867
  import fsPromises5 from "fs/promises";
147396
- import path50 from "path";
146868
+ import path49 from "path";
147397
146869
  import { fileURLToPath as fileURLToPath12 } from "url";
147398
146870
 
147399
146871
  // src/commands/facebook-analysis/diagnosis-merge-snapshot.ts
147400
- import * as fs42 from "fs/promises";
147401
- import * as path49 from "path";
146872
+ import * as fs41 from "fs/promises";
146873
+ import * as path48 from "path";
147402
146874
  function asRecord30(value) {
147403
146875
  if (value && typeof value === "object" && !Array.isArray(value)) {
147404
146876
  return value;
147405
146877
  }
147406
146878
  return null;
147407
146879
  }
147408
- function num10(value) {
146880
+ function num9(value) {
147409
146881
  const n = Number(value);
147410
146882
  return Number.isFinite(n) ? n : void 0;
147411
146883
  }
@@ -147414,16 +146886,16 @@ function asRows2(value) {
147414
146886
  }
147415
146887
  function pickMetricExtras(row, extras) {
147416
146888
  const out = {
147417
- spend: num10(row.spend) ?? 0,
147418
- impressions: num10(row.impressions) ?? 0,
147419
- clicks: num10(row.clicks) ?? 0,
147420
- results: num10(row.results),
147421
- costPerResult: num10(row.costPerResult),
147422
- reach: num10(row.reach),
147423
- frequency: num10(row.frequency),
147424
- ctr: num10(row.ctr),
147425
- conversions: num10(row.conversions),
147426
- costPerConversion: num10(row.costPerConversion)
146889
+ spend: num9(row.spend) ?? 0,
146890
+ impressions: num9(row.impressions) ?? 0,
146891
+ clicks: num9(row.clicks) ?? 0,
146892
+ results: num9(row.results),
146893
+ costPerResult: num9(row.costPerResult),
146894
+ reach: num9(row.reach),
146895
+ frequency: num9(row.frequency),
146896
+ ctr: num9(row.ctr),
146897
+ conversions: num9(row.conversions),
146898
+ costPerConversion: num9(row.costPerConversion)
147427
146899
  };
147428
146900
  for (const f of extras) {
147429
146901
  if (row[f] !== void 0 && row[f] !== null) out[f] = row[f];
@@ -147434,7 +146906,7 @@ async function readManifest5(snapshotDir, accountId) {
147434
146906
  const candidates = [];
147435
146907
  if (accountId) candidates.push(reportManifestFile(accountId));
147436
146908
  try {
147437
- const entries = await fs42.readdir(snapshotDir);
146909
+ const entries = await fs41.readdir(snapshotDir);
147438
146910
  const manifestNames = entries.filter(
147439
146911
  (n) => n.startsWith("report-manifest") && n.endsWith(".json")
147440
146912
  );
@@ -147448,7 +146920,7 @@ async function readManifest5(snapshotDir, accountId) {
147448
146920
  }
147449
146921
  for (const name2 of candidates) {
147450
146922
  try {
147451
- const raw = await fs42.readFile(path49.join(snapshotDir, name2), "utf8");
146923
+ const raw = await fs41.readFile(path48.join(snapshotDir, name2), "utf8");
147452
146924
  const parsed = JSON.parse(raw);
147453
146925
  if (Array.isArray(parsed.artifacts) && parsed.artifacts.length > 0) return parsed;
147454
146926
  } catch {
@@ -147458,14 +146930,14 @@ async function readManifest5(snapshotDir, accountId) {
147458
146930
  }
147459
146931
  async function loadSectionFile4(snapshotDir, file) {
147460
146932
  try {
147461
- const raw = await fs42.readFile(path49.join(snapshotDir, file), "utf8");
146933
+ const raw = await fs41.readFile(path48.join(snapshotDir, file), "utf8");
147462
146934
  return asRecord30(JSON.parse(raw));
147463
146935
  } catch {
147464
146936
  return null;
147465
146937
  }
147466
146938
  }
147467
146939
  async function mergeMetaDiagnosisSnapshotIntoReport(payload, snapshotDir) {
147468
- const absDir = path49.resolve(snapshotDir);
146940
+ const absDir = path48.resolve(snapshotDir);
147469
146941
  const metaAccountId = typeof asRecord30(payload.meta)?.accountId === "string" ? asRecord30(payload.meta)?.accountId : void 0;
147470
146942
  const manifest = await readManifest5(snapshotDir, metaAccountId);
147471
146943
  if (!manifest) {
@@ -147492,15 +146964,15 @@ async function mergeMetaDiagnosisSnapshotIntoReport(payload, snapshotDir) {
147492
146964
  if (!meta.generatedAt) meta.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
147493
146965
  const kpis = { ...payload.kpis ?? {} };
147494
146966
  if (currentPeriod) {
147495
- const spend = num10(currentPeriod.spend);
147496
- const impressions = num10(currentPeriod.impressions);
147497
- const clicks = num10(currentPeriod.clicks);
147498
- const results = num10(currentPeriod.results);
147499
- const costPerResult = num10(currentPeriod.costPerResult);
147500
- const ctr = num10(currentPeriod.ctr);
147501
- const cpc = num10(currentPeriod.cpc ?? currentPeriod.averageCpc);
147502
- const reach = num10(currentPeriod.reach);
147503
- const frequency = num10(currentPeriod.frequency);
146967
+ const spend = num9(currentPeriod.spend);
146968
+ const impressions = num9(currentPeriod.impressions);
146969
+ const clicks = num9(currentPeriod.clicks);
146970
+ const results = num9(currentPeriod.results);
146971
+ const costPerResult = num9(currentPeriod.costPerResult);
146972
+ const ctr = num9(currentPeriod.ctr);
146973
+ const cpc = num9(currentPeriod.cpc ?? currentPeriod.averageCpc);
146974
+ const reach = num9(currentPeriod.reach);
146975
+ const frequency = num9(currentPeriod.frequency);
147504
146976
  if (spend != null) kpis.spend = spend;
147505
146977
  if (impressions != null) kpis.impressions = impressions;
147506
146978
  if (clicks != null) kpis.clicks = clicks;
@@ -147513,15 +146985,15 @@ async function mergeMetaDiagnosisSnapshotIntoReport(payload, snapshotDir) {
147513
146985
  }
147514
146986
  if (previousPeriod) {
147515
146987
  kpis.previousPeriod = {
147516
- spend: num10(previousPeriod.spend),
147517
- impressions: num10(previousPeriod.impressions),
147518
- clicks: num10(previousPeriod.clicks),
147519
- results: num10(previousPeriod.results),
147520
- costPerResult: num10(previousPeriod.costPerResult),
147521
- ctr: num10(previousPeriod.ctr),
147522
- cpc: num10(previousPeriod.cpc ?? previousPeriod.averageCpc),
147523
- reach: num10(previousPeriod.reach),
147524
- frequency: num10(previousPeriod.frequency)
146988
+ spend: num9(previousPeriod.spend),
146989
+ impressions: num9(previousPeriod.impressions),
146990
+ clicks: num9(previousPeriod.clicks),
146991
+ results: num9(previousPeriod.results),
146992
+ costPerResult: num9(previousPeriod.costPerResult),
146993
+ ctr: num9(previousPeriod.ctr),
146994
+ cpc: num9(previousPeriod.cpc ?? previousPeriod.averageCpc),
146995
+ reach: num9(previousPeriod.reach),
146996
+ frequency: num9(previousPeriod.frequency)
147525
146997
  };
147526
146998
  }
147527
146999
  const tables = { ...payload.tables ?? {} };
@@ -147746,14 +147218,14 @@ init_html();
147746
147218
  var TEMPLATE_BASENAME3 = "meta-account-diagnosis-report.html";
147747
147219
  var INJECT_MARKER3 = "window.__META_DIAGNOSIS_REPORT__ = window.__META_DIAGNOSIS_REPORT__ || null;";
147748
147220
  function resolveSkillTemplatePath6(basename14) {
147749
- const dir = path50.dirname(fileURLToPath12(import.meta.url));
147221
+ const dir = path49.dirname(fileURLToPath12(import.meta.url));
147750
147222
  const candidates = [
147751
- path50.join(dir, "skill", "report-templates", basename14),
147752
- path50.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
147753
- path50.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
147223
+ path49.join(dir, "skill", "report-templates", basename14),
147224
+ path49.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
147225
+ path49.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
147754
147226
  ];
147755
147227
  for (const p of candidates) {
147756
- if (fs43.existsSync(p)) return p;
147228
+ if (fs42.existsSync(p)) return p;
147757
147229
  }
147758
147230
  return candidates[0];
147759
147231
  }
@@ -147783,10 +147255,10 @@ function injectReportData4(html, payload, lang) {
147783
147255
  return localized.replace(INJECT_MARKER3, `window.__META_DIAGNOSIS_REPORT__ = ${json};`);
147784
147256
  }
147785
147257
  async function runFacebookAnalysisDiagnosisRender(opts) {
147786
- const dataPath = path50.resolve(opts.dataFile);
147258
+ const dataPath = path49.resolve(opts.dataFile);
147787
147259
  let data = asRecord32(await readJsonFile6(dataPath));
147788
147260
  if (opts.snapshotDir?.trim()) {
147789
- data = await mergeMetaDiagnosisSnapshotIntoReport(data, path50.resolve(opts.snapshotDir));
147261
+ data = await mergeMetaDiagnosisSnapshotIntoReport(data, path49.resolve(opts.snapshotDir));
147790
147262
  }
147791
147263
  const lang = readReportLangOrExit({ flag: opts.lang, meta: data.meta });
147792
147264
  const contentCheck = validateMetaDiagnosisReportContent(data);
@@ -147813,10 +147285,10 @@ async function runFacebookAnalysisDiagnosisRender(opts) {
147813
147285
  `);
147814
147286
  process.exit(1);
147815
147287
  }
147816
- const outPath = path50.resolve(
147817
- opts.out ?? path50.join(path50.dirname(dataPath), "meta-account-diagnosis-report.html")
147288
+ const outPath = path49.resolve(
147289
+ opts.out ?? path49.join(path49.dirname(dataPath), "meta-account-diagnosis-report.html")
147818
147290
  );
147819
- const outDir = path50.dirname(outPath);
147291
+ const outDir = path49.dirname(outPath);
147820
147292
  await fsPromises5.mkdir(outDir, { recursive: true });
147821
147293
  await fsPromises5.writeFile(outPath, injectReportData4(html, data, lang), "utf8");
147822
147294
  const { stats } = contentCheck;
@@ -147834,7 +147306,7 @@ async function runFacebookAnalysisDiagnosisRender(opts) {
147834
147306
 
147835
147307
  // src/commands/facebook-analysis/run-batch.ts
147836
147308
  init_auth();
147837
- import * as path51 from "path";
147309
+ import * as path50 from "path";
147838
147310
  import { performance as performance5 } from "perf_hooks";
147839
147311
  init_version();
147840
147312
 
@@ -147936,7 +147408,7 @@ async function runAllFacebookSections(opts) {
147936
147408
  const results = await runWithConcurrency3(tasks, concurrency);
147937
147409
  const succeeded = results.filter((r) => r.ok).length;
147938
147410
  const failed = results.length - succeeded;
147939
- const absoluteSnapshotDir = path51.resolve(opts.jsonOut);
147411
+ const absoluteSnapshotDir = path50.resolve(opts.jsonOut);
147940
147412
  const summary = {
147941
147413
  kind: "siluzan-tso-facebook-analysis-snapshot-batch",
147942
147414
  absoluteSnapshotDir,
@@ -148060,9 +147532,9 @@ function parseEffectiveStatusFilter(raw) {
148060
147532
  }
148061
147533
  return canonical.length ? canonical.join(",") : void 0;
148062
147534
  }
148063
- function facebookAdsUrl(facebookApiUrl, digits, path62) {
147535
+ function facebookAdsUrl(facebookApiUrl, digits, path61) {
148064
147536
  const base2 = facebookApiUrl.replace(/\/$/, "");
148065
- const p = path62.startsWith("/") ? path62 : `/${path62}`;
147537
+ const p = path61.startsWith("/") ? path61 : `/${path61}`;
148066
147538
  return `${base2}/api/fb/ads/${digits}${p}`;
148067
147539
  }
148068
147540
  function facebookInsightsUrl(facebookApiUrl, digits, level) {
@@ -148099,7 +147571,7 @@ async function fetchFacebookAccount(config, digits, verbose) {
148099
147571
  verbose
148100
147572
  );
148101
147573
  }
148102
- async function fetchFacebookPagedList(config, digits, path62, opts) {
147574
+ async function fetchFacebookPagedList(config, digits, path61, opts) {
148103
147575
  const base2 = requireFacebookApi(config);
148104
147576
  const items3 = [];
148105
147577
  let after;
@@ -148114,7 +147586,7 @@ async function fetchFacebookPagedList(config, digits, path62, opts) {
148114
147586
  adsetId: opts.adsetId
148115
147587
  });
148116
147588
  const raw = await apiFetch2(
148117
- `${facebookAdsUrl(base2, digits, path62)}?${query}`,
147589
+ `${facebookAdsUrl(base2, digits, path61)}?${query}`,
148118
147590
  config,
148119
147591
  {},
148120
147592
  opts.verbose
@@ -148249,7 +147721,7 @@ async function runFacebookEntityList(opts, kind) {
148249
147721
  }
148250
147722
  const pageSize = resolveFacebookPageSize(opts.pageSize);
148251
147723
  const config = loadConfig(opts.token);
148252
- const path62 = `/${kind}`;
147724
+ const path61 = `/${kind}`;
148253
147725
  const labels = {
148254
147726
  campaigns: {
148255
147727
  section: "facebook-campaign-entities",
@@ -148262,7 +147734,7 @@ async function runFacebookEntityList(opts, kind) {
148262
147734
  const meta = labels[kind];
148263
147735
  let result;
148264
147736
  try {
148265
- result = await fetchFacebookPagedList(config, manifestId, path62, {
147737
+ result = await fetchFacebookPagedList(config, manifestId, path61, {
148266
147738
  pageSize,
148267
147739
  verbose: !!opts.verbose,
148268
147740
  effectiveStatus,
@@ -148694,14 +148166,14 @@ init_auth();
148694
148166
  init_balance();
148695
148167
 
148696
148168
  // src/commands/bing-analysis/normalize-bing-overview.ts
148697
- function num11(v) {
148169
+ function num10(v) {
148698
148170
  return typeof v === "number" && Number.isFinite(v) ? v : void 0;
148699
148171
  }
148700
148172
  function roundMoney(v) {
148701
148173
  return Math.round(v * 100) / 100;
148702
148174
  }
148703
148175
  function countInclusiveCalendarDays(startDate, endDate) {
148704
- const parts = (ymd2) => ymd2.trim().split("-").map((x) => parseInt(x, 10));
148176
+ const parts = (ymd) => ymd.trim().split("-").map((x) => parseInt(x, 10));
148705
148177
  const sp = parts(startDate);
148706
148178
  const ep = parts(endDate);
148707
148179
  if (sp.length !== 3 || ep.length !== 3 || sp.some((n) => !Number.isFinite(n)) || ep.some((n) => !Number.isFinite(n))) {
@@ -148715,19 +148187,19 @@ function countInclusiveCalendarDays(startDate, endDate) {
148715
148187
  }
148716
148188
  function periodSpend(period) {
148717
148189
  if (!period || typeof period !== "object") return void 0;
148718
- return num11(period.spend);
148190
+ return num10(period.spend);
148719
148191
  }
148720
148192
  function enrichBingOverviewDerivedMetrics(record2, startDate, endDate) {
148721
148193
  const out = { ...record2 };
148722
148194
  const currentSpend = periodSpend(out.currentPeriod);
148723
- let totalCost = num11(out.totalCost);
148195
+ let totalCost = num10(out.totalCost);
148724
148196
  if (totalCost == null || totalCost <= 0) {
148725
148197
  if (currentSpend != null && currentSpend > 0) {
148726
148198
  out.totalCost = currentSpend;
148727
148199
  totalCost = currentSpend;
148728
148200
  }
148729
148201
  }
148730
- let activeDays = num11(out.activeDays);
148202
+ let activeDays = num10(out.activeDays);
148731
148203
  if (activeDays == null || activeDays <= 0) {
148732
148204
  const calendarDays = countInclusiveCalendarDays(startDate, endDate);
148733
148205
  if (calendarDays > 0) {
@@ -148735,14 +148207,14 @@ function enrichBingOverviewDerivedMetrics(record2, startDate, endDate) {
148735
148207
  activeDays = calendarDays;
148736
148208
  }
148737
148209
  }
148738
- const averageDailyCost = num11(out.averageDailyCost);
148210
+ const averageDailyCost = num10(out.averageDailyCost);
148739
148211
  if ((averageDailyCost == null || averageDailyCost <= 0) && totalCost != null && totalCost > 0 && activeDays != null && activeDays > 0) {
148740
148212
  out.averageDailyCost = roundMoney(totalCost / activeDays);
148741
148213
  }
148742
148214
  return out;
148743
148215
  }
148744
- function parseYmd2(ymd2) {
148745
- const parts = ymd2.trim().split("-").map((x) => parseInt(x, 10));
148216
+ function parseYmd2(ymd) {
148217
+ const parts = ymd.trim().split("-").map((x) => parseInt(x, 10));
148746
148218
  if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n))) return null;
148747
148219
  const d = new Date(parts[0], parts[1] - 1, parts[2]);
148748
148220
  return Number.isNaN(d.getTime()) ? null : d;
@@ -148767,16 +148239,16 @@ function calcBingPreviousPeriodRange(startDate, endDate) {
148767
148239
  function isBingPeriodBlockEmpty(period) {
148768
148240
  if (!period || typeof period !== "object") return true;
148769
148241
  const p = period;
148770
- const spend = num11(p.spend) ?? 0;
148771
- const impressions = num11(p.impressions) ?? 0;
148772
- const clicks = num11(p.clicks) ?? 0;
148242
+ const spend = num10(p.spend) ?? 0;
148243
+ const impressions = num10(p.impressions) ?? 0;
148244
+ const clicks = num10(p.clicks) ?? 0;
148773
148245
  return spend <= 0 && impressions <= 0 && clicks <= 0;
148774
148246
  }
148775
148247
  function syncOverviewBalanceFields(record2) {
148776
148248
  const out = { ...record2 };
148777
- const budget = num11(out.remainingAccountBudget);
148249
+ const budget = num10(out.remainingAccountBudget);
148778
148250
  if (budget != null && budget >= 0) {
148779
- const balanceField = num11(out.balance);
148251
+ const balanceField = num10(out.balance);
148780
148252
  if (balanceField == null || balanceField <= 0 && budget > 0) {
148781
148253
  out.balance = budget;
148782
148254
  }
@@ -148815,8 +148287,8 @@ var BING_KEYWORD_LIMIT_DEFAULT = 100;
148815
148287
  function stripLocalDate(d) {
148816
148288
  return new Date(d.getFullYear(), d.getMonth(), d.getDate());
148817
148289
  }
148818
- function parseLocalYmd(ymd2) {
148819
- const parts = ymd2.trim().split("-").map((x) => parseInt(x, 10));
148290
+ function parseLocalYmd(ymd) {
148291
+ const parts = ymd.trim().split("-").map((x) => parseInt(x, 10));
148820
148292
  if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n))) {
148821
148293
  return /* @__PURE__ */ new Date(NaN);
148822
148294
  }
@@ -149010,7 +148482,7 @@ function endpointHintForBingSection(def) {
149010
148482
 
149011
148483
  // src/commands/bing-analysis/run-batch.ts
149012
148484
  init_auth();
149013
- import * as path52 from "path";
148485
+ import * as path51 from "path";
149014
148486
  import { performance as performance6 } from "perf_hooks";
149015
148487
  init_version();
149016
148488
  async function runWithConcurrency4(tasks, concurrency) {
@@ -149085,7 +148557,7 @@ async function runAllBingSections(opts) {
149085
148557
  const results = await runWithConcurrency4(tasks, concurrency);
149086
148558
  const succeeded = results.filter((r) => r.ok).length;
149087
148559
  const failed = results.length - succeeded;
149088
- const absoluteSnapshotDir = path52.resolve(opts.jsonOut);
148560
+ const absoluteSnapshotDir = path51.resolve(opts.jsonOut);
149089
148561
  const summary = {
149090
148562
  kind: "siluzan-tso-bing-analysis-snapshot-batch",
149091
148563
  absoluteSnapshotDir,
@@ -149429,25 +148901,25 @@ Bing \u5B98\u65B9\u6708\u6D88\u8017\uFF08${id}\uFF09
149429
148901
  import { Command as Command3 } from "commander";
149430
148902
 
149431
148903
  // src/commands/bing-analysis/render-report.ts
149432
- import fs45 from "fs";
148904
+ import fs44 from "fs";
149433
148905
  import fsPromises6 from "fs/promises";
149434
- import path54 from "path";
148906
+ import path53 from "path";
149435
148907
  import { fileURLToPath as fileURLToPath13 } from "url";
149436
148908
 
149437
148909
  // src/commands/bing-analysis/merge-snapshot.ts
149438
- import * as fs44 from "fs/promises";
149439
- import * as path53 from "path";
148910
+ import * as fs43 from "fs/promises";
148911
+ import * as path52 from "path";
149440
148912
  function asRecord34(value) {
149441
148913
  if (value && typeof value === "object" && !Array.isArray(value)) {
149442
148914
  return value;
149443
148915
  }
149444
148916
  return null;
149445
148917
  }
149446
- function num12(value) {
148918
+ function num11(value) {
149447
148919
  const n = Number(value);
149448
148920
  return Number.isFinite(n) ? n : void 0;
149449
148921
  }
149450
- function round29(value) {
148922
+ function round28(value) {
149451
148923
  return value == null ? void 0 : Math.round(value * 100) / 100;
149452
148924
  }
149453
148925
  function asRows3(value) {
@@ -149458,7 +148930,7 @@ function asRows3(value) {
149458
148930
  }
149459
148931
  async function loadSectionPayload(snapshotDir, file) {
149460
148932
  try {
149461
- const raw = await fs44.readFile(path53.join(snapshotDir, file), "utf8");
148933
+ const raw = await fs43.readFile(path52.join(snapshotDir, file), "utf8");
149462
148934
  return JSON.parse(raw);
149463
148935
  } catch {
149464
148936
  return null;
@@ -149468,7 +148940,7 @@ async function readManifest6(snapshotDir, accountId) {
149468
148940
  const candidates = [];
149469
148941
  if (accountId) candidates.push(reportManifestFile(accountId));
149470
148942
  try {
149471
- const entries = await fs44.readdir(snapshotDir);
148943
+ const entries = await fs43.readdir(snapshotDir);
149472
148944
  const manifestNames = entries.filter(
149473
148945
  (n) => n.startsWith("report-manifest") && n.endsWith(".json")
149474
148946
  );
@@ -149479,7 +148951,7 @@ async function readManifest6(snapshotDir, accountId) {
149479
148951
  }
149480
148952
  for (const name2 of candidates) {
149481
148953
  try {
149482
- const raw = await fs44.readFile(path53.join(snapshotDir, name2), "utf8");
148954
+ const raw = await fs43.readFile(path52.join(snapshotDir, name2), "utf8");
149483
148955
  const parsed = JSON.parse(raw);
149484
148956
  if (Array.isArray(parsed.artifacts) && parsed.artifacts.length > 0) return parsed;
149485
148957
  } catch {
@@ -149489,14 +148961,14 @@ async function readManifest6(snapshotDir, accountId) {
149489
148961
  }
149490
148962
  function pickMetrics(row, extras = []) {
149491
148963
  const out = {
149492
- spend: num12(row.spend) ?? 0,
149493
- impressions: num12(row.impressions) ?? 0,
149494
- clicks: num12(row.clicks) ?? 0,
149495
- ctr: num12(row.ctr),
149496
- averageCpc: num12(row.averageCpc),
149497
- conversions: num12(row.conversions) ?? 0,
149498
- conversionRate: num12(row.conversionRate),
149499
- costPerConversion: num12(row.costPerConversion)
148964
+ spend: num11(row.spend) ?? 0,
148965
+ impressions: num11(row.impressions) ?? 0,
148966
+ clicks: num11(row.clicks) ?? 0,
148967
+ ctr: num11(row.ctr),
148968
+ averageCpc: num11(row.averageCpc),
148969
+ conversions: num11(row.conversions) ?? 0,
148970
+ conversionRate: num11(row.conversionRate),
148971
+ costPerConversion: num11(row.costPerConversion)
149500
148972
  };
149501
148973
  for (const f of extras) {
149502
148974
  if (row[f] !== void 0 && row[f] !== null) out[f] = row[f];
@@ -149510,19 +148982,19 @@ function sumBingCampaignRowsToPeriodKpis(rows) {
149510
148982
  let clicks = 0;
149511
148983
  let conversions = 0;
149512
148984
  for (const row of rows) {
149513
- spend += num12(row.spend) ?? 0;
149514
- impressions += num12(row.impressions) ?? 0;
149515
- clicks += num12(row.clicks) ?? 0;
149516
- conversions += num12(row.conversions) ?? 0;
148985
+ spend += num11(row.spend) ?? 0;
148986
+ impressions += num11(row.impressions) ?? 0;
148987
+ clicks += num11(row.clicks) ?? 0;
148988
+ conversions += num11(row.conversions) ?? 0;
149517
148989
  }
149518
148990
  return {
149519
- spend: round29(spend),
148991
+ spend: round28(spend),
149520
148992
  impressions: Math.round(impressions),
149521
148993
  clicks: Math.round(clicks),
149522
- conversions: round29(conversions),
148994
+ conversions: round28(conversions),
149523
148995
  ctr: impressions > 0 ? clicks / impressions : void 0,
149524
- averageCpc: clicks > 0 ? round29(spend / clicks) : void 0,
149525
- costPerConversion: conversions > 0 ? round29(spend / conversions) : void 0
148996
+ averageCpc: clicks > 0 ? round28(spend / clicks) : void 0,
148997
+ costPerConversion: conversions > 0 ? round28(spend / conversions) : void 0
149526
148998
  };
149527
148999
  }
149528
149000
  function campaignStatusDisplay(status) {
@@ -149646,7 +149118,7 @@ function mapSearchTermRows(payload) {
149646
149118
  );
149647
149119
  }
149648
149120
  async function mergeBingAnalysisSnapshotIntoReport(payload, snapshotDir) {
149649
- const absDir = path53.resolve(snapshotDir);
149121
+ const absDir = path52.resolve(snapshotDir);
149650
149122
  const metaAccountId = typeof asRecord34(payload.meta)?.accountId === "string" ? asRecord34(payload.meta)?.accountId : void 0;
149651
149123
  const manifest = await readManifest6(snapshotDir, metaAccountId);
149652
149124
  if (!manifest) {
@@ -149678,13 +149150,13 @@ async function mergeBingAnalysisSnapshotIntoReport(payload, snapshotDir) {
149678
149150
  if (!meta.generatedAt) meta.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
149679
149151
  const kpis = { ...payload.kpis ?? {} };
149680
149152
  const currentKpiSource = campaignKpis ?? (currentPeriod ? {
149681
- spend: num12(currentPeriod.spend),
149682
- impressions: num12(currentPeriod.impressions),
149683
- clicks: num12(currentPeriod.clicks),
149684
- conversions: num12(currentPeriod.conversions),
149685
- ctr: num12(currentPeriod.ctr),
149686
- averageCpc: num12(currentPeriod.averageCpc),
149687
- costPerConversion: num12(currentPeriod.costPerConversion)
149153
+ spend: num11(currentPeriod.spend),
149154
+ impressions: num11(currentPeriod.impressions),
149155
+ clicks: num11(currentPeriod.clicks),
149156
+ conversions: num11(currentPeriod.conversions),
149157
+ ctr: num11(currentPeriod.ctr),
149158
+ averageCpc: num11(currentPeriod.averageCpc),
149159
+ costPerConversion: num11(currentPeriod.costPerConversion)
149688
149160
  } : null);
149689
149161
  if (currentKpiSource) {
149690
149162
  if (currentKpiSource.spend != null) kpis.spend = currentKpiSource.spend;
@@ -149698,24 +149170,24 @@ async function mergeBingAnalysisSnapshotIntoReport(payload, snapshotDir) {
149698
149170
  }
149699
149171
  }
149700
149172
  if (overview) {
149701
- const avgDaily = num12(overview.averageDailyCost);
149173
+ const avgDaily = num11(overview.averageDailyCost);
149702
149174
  if (avgDaily != null) kpis.averageDailyCost = avgDaily;
149703
- const bal = num12(overview.balance);
149175
+ const bal = num11(overview.balance);
149704
149176
  if (bal != null) kpis.balance = bal;
149705
- const rem = num12(overview.remainingAccountBudget);
149177
+ const rem = num11(overview.remainingAccountBudget);
149706
149178
  if (rem != null) kpis.remainingAccountBudget = rem;
149707
- const opt = num12(overview.optimizationScore);
149179
+ const opt = num11(overview.optimizationScore);
149708
149180
  if (opt != null) kpis.optimizationScore = opt;
149709
149181
  }
149710
149182
  if (previousPeriod) {
149711
149183
  kpis.previousPeriod = {
149712
- spend: num12(previousPeriod.spend),
149713
- impressions: num12(previousPeriod.impressions),
149714
- clicks: num12(previousPeriod.clicks),
149715
- conversions: num12(previousPeriod.conversions),
149716
- ctr: num12(previousPeriod.ctr),
149717
- averageCpc: num12(previousPeriod.averageCpc),
149718
- costPerConversion: num12(previousPeriod.costPerConversion)
149184
+ spend: num11(previousPeriod.spend),
149185
+ impressions: num11(previousPeriod.impressions),
149186
+ clicks: num11(previousPeriod.clicks),
149187
+ conversions: num11(previousPeriod.conversions),
149188
+ ctr: num11(previousPeriod.ctr),
149189
+ averageCpc: num11(previousPeriod.averageCpc),
149190
+ costPerConversion: num11(previousPeriod.costPerConversion)
149719
149191
  };
149720
149192
  }
149721
149193
  const tables = { ...payload.tables ?? {} };
@@ -149884,14 +149356,14 @@ init_html();
149884
149356
  var TEMPLATE_BASENAME4 = "bing-period-report.html";
149885
149357
  var INJECT_MARKER4 = "window.__BING_PERIOD_REPORT__ = window.__BING_PERIOD_REPORT__ || null;";
149886
149358
  function resolveSkillTemplatePath7(basename14) {
149887
- const dir = path54.dirname(fileURLToPath13(import.meta.url));
149359
+ const dir = path53.dirname(fileURLToPath13(import.meta.url));
149888
149360
  const candidates = [
149889
- path54.join(dir, "skill", "report-templates", basename14),
149890
- path54.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
149891
- path54.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
149361
+ path53.join(dir, "skill", "report-templates", basename14),
149362
+ path53.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
149363
+ path53.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
149892
149364
  ];
149893
149365
  for (const p of candidates) {
149894
- if (fs45.existsSync(p)) return p;
149366
+ if (fs44.existsSync(p)) return p;
149895
149367
  }
149896
149368
  return candidates[0];
149897
149369
  }
@@ -149921,10 +149393,10 @@ function injectReportData5(html, payload, lang) {
149921
149393
  return localized.replace(INJECT_MARKER4, `window.__BING_PERIOD_REPORT__ = ${json};`);
149922
149394
  }
149923
149395
  async function runBingAnalysisRender(opts) {
149924
- const dataPath = path54.resolve(opts.dataFile);
149396
+ const dataPath = path53.resolve(opts.dataFile);
149925
149397
  let data = asRecord36(await readJsonFile7(dataPath));
149926
149398
  if (opts.snapshotDir?.trim()) {
149927
- data = await mergeBingAnalysisSnapshotIntoReport(data, path54.resolve(opts.snapshotDir));
149399
+ data = await mergeBingAnalysisSnapshotIntoReport(data, path53.resolve(opts.snapshotDir));
149928
149400
  }
149929
149401
  const lang = readReportLangOrExit({ flag: opts.lang, meta: data.meta });
149930
149402
  const contentCheck = validateBingPeriodReportContent(data);
@@ -149951,10 +149423,10 @@ async function runBingAnalysisRender(opts) {
149951
149423
  `);
149952
149424
  process.exit(1);
149953
149425
  }
149954
- const outPath = path54.resolve(
149955
- opts.out ?? path54.join(path54.dirname(dataPath), "bing-period-report.html")
149426
+ const outPath = path53.resolve(
149427
+ opts.out ?? path53.join(path53.dirname(dataPath), "bing-period-report.html")
149956
149428
  );
149957
- const outDir = path54.dirname(outPath);
149429
+ const outDir = path53.dirname(outPath);
149958
149430
  await fsPromises6.mkdir(outDir, { recursive: true });
149959
149431
  await fsPromises6.writeFile(outPath, injectReportData5(html, data, lang), "utf8");
149960
149432
  const { stats } = contentCheck;
@@ -150403,7 +149875,7 @@ async function fetchTikTokInterestList(config, account, verbose) {
150403
149875
 
150404
149876
  // src/commands/tiktok-analysis/run-batch.ts
150405
149877
  init_auth();
150406
- import * as path55 from "path";
149878
+ import * as path54 from "path";
150407
149879
  import { performance as performance7 } from "perf_hooks";
150408
149880
  init_version();
150409
149881
  async function runWithConcurrency5(tasks, concurrency) {
@@ -150478,7 +149950,7 @@ async function runAllTikTokSections(opts) {
150478
149950
  const results = await runWithConcurrency5(tasks, concurrency);
150479
149951
  const succeeded = results.filter((r) => r.ok).length;
150480
149952
  const failed = results.length - succeeded;
150481
- const absoluteSnapshotDir = path55.resolve(opts.jsonOut);
149953
+ const absoluteSnapshotDir = path54.resolve(opts.jsonOut);
150482
149954
  const summary = {
150483
149955
  kind: "siluzan-tso-tiktok-analysis-snapshot-batch",
150484
149956
  absoluteSnapshotDir,
@@ -150501,30 +149973,30 @@ init_auth();
150501
149973
  import { Command as Command4 } from "commander";
150502
149974
 
150503
149975
  // src/commands/tiktok-analysis/render-report.ts
150504
- import fs47 from "fs";
149976
+ import fs46 from "fs";
150505
149977
  import fsPromises7 from "fs/promises";
150506
- import path57 from "path";
149978
+ import path56 from "path";
150507
149979
  import { fileURLToPath as fileURLToPath14 } from "url";
150508
149980
 
150509
149981
  // src/commands/tiktok-analysis/merge-snapshot.ts
150510
- import * as fs46 from "fs/promises";
150511
- import * as path56 from "path";
149982
+ import * as fs45 from "fs/promises";
149983
+ import * as path55 from "path";
150512
149984
  function asRecord37(value) {
150513
149985
  if (value && typeof value === "object" && !Array.isArray(value)) {
150514
149986
  return value;
150515
149987
  }
150516
149988
  return null;
150517
149989
  }
150518
- function num13(value) {
149990
+ function num12(value) {
150519
149991
  const n = Number(value);
150520
149992
  return Number.isFinite(n) ? n : void 0;
150521
149993
  }
150522
- function round210(value) {
149994
+ function round29(value) {
150523
149995
  return value == null ? void 0 : Math.round(value * 100) / 100;
150524
149996
  }
150525
149997
  async function loadSectionPayload2(snapshotDir, file) {
150526
149998
  try {
150527
- const raw = await fs46.readFile(path56.join(snapshotDir, file), "utf8");
149999
+ const raw = await fs45.readFile(path55.join(snapshotDir, file), "utf8");
150528
150000
  return JSON.parse(raw);
150529
150001
  } catch {
150530
150002
  return null;
@@ -150534,7 +150006,7 @@ async function readManifest7(snapshotDir, accountId) {
150534
150006
  const candidates = [];
150535
150007
  if (accountId) candidates.push(reportManifestFile(accountId));
150536
150008
  try {
150537
- const entries = await fs46.readdir(snapshotDir);
150009
+ const entries = await fs45.readdir(snapshotDir);
150538
150010
  const manifestNames = entries.filter(
150539
150011
  (n) => n.startsWith("report-manifest") && n.endsWith(".json")
150540
150012
  );
@@ -150545,7 +150017,7 @@ async function readManifest7(snapshotDir, accountId) {
150545
150017
  }
150546
150018
  for (const name2 of candidates) {
150547
150019
  try {
150548
- const raw = await fs46.readFile(path56.join(snapshotDir, name2), "utf8");
150020
+ const raw = await fs45.readFile(path55.join(snapshotDir, name2), "utf8");
150549
150021
  const parsed = JSON.parse(raw);
150550
150022
  if (Array.isArray(parsed.artifacts) && parsed.artifacts.length > 0) return parsed;
150551
150023
  } catch {
@@ -150554,16 +150026,16 @@ async function readManifest7(snapshotDir, accountId) {
150554
150026
  return null;
150555
150027
  }
150556
150028
  function normalizeTikTokRate(value) {
150557
- const n = num13(value);
150029
+ const n = num12(value);
150558
150030
  if (n == null) return void 0;
150559
150031
  return n > 1 ? n / 100 : n;
150560
150032
  }
150561
150033
  function normalizeTikTokMetrics(metrics) {
150562
150034
  const m = metrics ?? {};
150563
- const spend = num13(m.spend);
150564
- const impressions = num13(m.impressions);
150565
- const clicks = num13(m.clicks);
150566
- const conversions = num13(m.conversion);
150035
+ const spend = num12(m.spend);
150036
+ const impressions = num12(m.impressions);
150037
+ const clicks = num12(m.clicks);
150038
+ const conversions = num12(m.conversion);
150567
150039
  const ctrFromCounts = impressions != null && impressions > 0 && clicks != null ? clicks / impressions : void 0;
150568
150040
  const cvrFromCounts = clicks != null && clicks > 0 && conversions != null ? conversions / clicks : void 0;
150569
150041
  return {
@@ -150572,8 +150044,8 @@ function normalizeTikTokMetrics(metrics) {
150572
150044
  clicks: clicks ?? 0,
150573
150045
  conversions: conversions == null ? 0 : Math.round(conversions),
150574
150046
  ctr: ctrFromCounts ?? normalizeTikTokRate(m.ctr),
150575
- averageCpc: num13(m.cpc),
150576
- costPerConversion: num13(m.cost_per_conversion),
150047
+ averageCpc: num12(m.cpc),
150048
+ costPerConversion: num12(m.cost_per_conversion),
150577
150049
  conversionRate: cvrFromCounts ?? normalizeTikTokRate(m.conversion_rate)
150578
150050
  };
150579
150051
  }
@@ -150593,19 +150065,19 @@ function sumTikTokCampaignRowsToPeriodKpis(rows) {
150593
150065
  let clicks = 0;
150594
150066
  let conversions = 0;
150595
150067
  for (const row of rows) {
150596
- spend += num13(row.spend) ?? 0;
150597
- impressions += num13(row.impressions) ?? 0;
150598
- clicks += num13(row.clicks) ?? 0;
150599
- conversions += num13(row.conversions) ?? 0;
150068
+ spend += num12(row.spend) ?? 0;
150069
+ impressions += num12(row.impressions) ?? 0;
150070
+ clicks += num12(row.clicks) ?? 0;
150071
+ conversions += num12(row.conversions) ?? 0;
150600
150072
  }
150601
150073
  return {
150602
- spend: round210(spend),
150074
+ spend: round29(spend),
150603
150075
  impressions: Math.round(impressions),
150604
150076
  clicks: Math.round(clicks),
150605
- conversions: round210(conversions),
150077
+ conversions: round29(conversions),
150606
150078
  ctr: impressions > 0 ? clicks / impressions : void 0,
150607
- averageCpc: clicks > 0 ? round210(spend / clicks) : void 0,
150608
- costPerConversion: conversions > 0 ? round210(spend / conversions) : void 0
150079
+ averageCpc: clicks > 0 ? round29(spend / clicks) : void 0,
150080
+ costPerConversion: conversions > 0 ? round29(spend / conversions) : void 0
150609
150081
  };
150610
150082
  }
150611
150083
  function mapCampaignTable(rows) {
@@ -150613,13 +150085,13 @@ function mapCampaignTable(rows) {
150613
150085
  campaignId: r.campaignId,
150614
150086
  campaignName: r.campaignName,
150615
150087
  status: r.campaignStatus,
150616
- spend: num13(r.spend) ?? 0,
150617
- impressions: num13(r.impressions) ?? 0,
150618
- clicks: num13(r.clicks) ?? 0,
150619
- conversions: num13(r.conversions) ?? 0,
150620
- ctr: num13(r.ctr),
150621
- averageCpc: num13(r.averageCpc),
150622
- costPerConversion: num13(r.costPerConversion)
150088
+ spend: num12(r.spend) ?? 0,
150089
+ impressions: num12(r.impressions) ?? 0,
150090
+ clicks: num12(r.clicks) ?? 0,
150091
+ conversions: num12(r.conversions) ?? 0,
150092
+ ctr: num12(r.ctr),
150093
+ averageCpc: num12(r.averageCpc),
150094
+ costPerConversion: num12(r.costPerConversion)
150623
150095
  }));
150624
150096
  }
150625
150097
  function pickTikTokName(item, metricKey, dimensionKey) {
@@ -150686,7 +150158,7 @@ function mapAudienceMerged(payload) {
150686
150158
  };
150687
150159
  }
150688
150160
  async function mergeTikTokAnalysisSnapshotIntoReport(payload, snapshotDir) {
150689
- const absDir = path56.resolve(snapshotDir);
150161
+ const absDir = path55.resolve(snapshotDir);
150690
150162
  const metaAccountId = typeof asRecord37(payload.meta)?.accountId === "string" ? asRecord37(payload.meta)?.accountId : void 0;
150691
150163
  const manifest = await readManifest7(snapshotDir, metaAccountId);
150692
150164
  if (!manifest) {
@@ -150716,13 +150188,13 @@ async function mergeTikTokAnalysisSnapshotIntoReport(payload, snapshotDir) {
150716
150188
  if (!meta.generatedAt) meta.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
150717
150189
  const kpis = { ...payload.kpis ?? {} };
150718
150190
  const currentKpiSource = campaignKpis ?? (currentPeriod ? {
150719
- spend: num13(currentPeriod.spend),
150720
- impressions: num13(currentPeriod.impressions),
150721
- clicks: num13(currentPeriod.clicks),
150722
- conversions: num13(currentPeriod.conversions),
150723
- ctr: num13(currentPeriod.ctr),
150724
- averageCpc: num13(currentPeriod.averageCpc),
150725
- costPerConversion: num13(currentPeriod.costPerConversion)
150191
+ spend: num12(currentPeriod.spend),
150192
+ impressions: num12(currentPeriod.impressions),
150193
+ clicks: num12(currentPeriod.clicks),
150194
+ conversions: num12(currentPeriod.conversions),
150195
+ ctr: num12(currentPeriod.ctr),
150196
+ averageCpc: num12(currentPeriod.averageCpc),
150197
+ costPerConversion: num12(currentPeriod.costPerConversion)
150726
150198
  } : null);
150727
150199
  if (currentKpiSource) {
150728
150200
  if (currentKpiSource.spend != null) kpis.spend = currentKpiSource.spend;
@@ -150737,13 +150209,13 @@ async function mergeTikTokAnalysisSnapshotIntoReport(payload, snapshotDir) {
150737
150209
  }
150738
150210
  if (previousPeriod) {
150739
150211
  kpis.previousPeriod = {
150740
- spend: num13(previousPeriod.spend),
150741
- impressions: num13(previousPeriod.impressions),
150742
- clicks: num13(previousPeriod.clicks),
150743
- conversions: num13(previousPeriod.conversions),
150744
- ctr: num13(previousPeriod.ctr),
150745
- averageCpc: num13(previousPeriod.averageCpc),
150746
- costPerConversion: num13(previousPeriod.costPerConversion)
150212
+ spend: num12(previousPeriod.spend),
150213
+ impressions: num12(previousPeriod.impressions),
150214
+ clicks: num12(previousPeriod.clicks),
150215
+ conversions: num12(previousPeriod.conversions),
150216
+ ctr: num12(previousPeriod.ctr),
150217
+ averageCpc: num12(previousPeriod.averageCpc),
150218
+ costPerConversion: num12(previousPeriod.costPerConversion)
150747
150219
  };
150748
150220
  }
150749
150221
  const tables = { ...payload.tables ?? {} };
@@ -150899,14 +150371,14 @@ init_html();
150899
150371
  var TEMPLATE_BASENAME5 = "tiktok-period-report.html";
150900
150372
  var INJECT_MARKER5 = "window.__TIKTOK_PERIOD_REPORT__ = window.__TIKTOK_PERIOD_REPORT__ || null;";
150901
150373
  function resolveSkillTemplatePath8(basename14) {
150902
- const dir = path57.dirname(fileURLToPath14(import.meta.url));
150374
+ const dir = path56.dirname(fileURLToPath14(import.meta.url));
150903
150375
  const candidates = [
150904
- path57.join(dir, "skill", "report-templates", basename14),
150905
- path57.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
150906
- path57.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
150376
+ path56.join(dir, "skill", "report-templates", basename14),
150377
+ path56.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
150378
+ path56.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
150907
150379
  ];
150908
150380
  for (const p of candidates) {
150909
- if (fs47.existsSync(p)) return p;
150381
+ if (fs46.existsSync(p)) return p;
150910
150382
  }
150911
150383
  return candidates[0];
150912
150384
  }
@@ -150936,10 +150408,10 @@ function injectReportData6(html, payload, lang) {
150936
150408
  return localized.replace(INJECT_MARKER5, `window.__TIKTOK_PERIOD_REPORT__ = ${json};`);
150937
150409
  }
150938
150410
  async function runTikTokAnalysisRender(opts) {
150939
- const dataPath = path57.resolve(opts.dataFile);
150411
+ const dataPath = path56.resolve(opts.dataFile);
150940
150412
  let data = asRecord39(await readJsonFile8(dataPath));
150941
150413
  if (opts.snapshotDir?.trim()) {
150942
- data = await mergeTikTokAnalysisSnapshotIntoReport(data, path57.resolve(opts.snapshotDir));
150414
+ data = await mergeTikTokAnalysisSnapshotIntoReport(data, path56.resolve(opts.snapshotDir));
150943
150415
  }
150944
150416
  const lang = readReportLangOrExit({ flag: opts.lang, meta: data.meta });
150945
150417
  const contentCheck = validateTikTokPeriodReportContent(data);
@@ -150966,10 +150438,10 @@ async function runTikTokAnalysisRender(opts) {
150966
150438
  `);
150967
150439
  process.exit(1);
150968
150440
  }
150969
- const outPath = path57.resolve(
150970
- opts.out ?? path57.join(path57.dirname(dataPath), "tiktok-period-report.html")
150441
+ const outPath = path56.resolve(
150442
+ opts.out ?? path56.join(path56.dirname(dataPath), "tiktok-period-report.html")
150971
150443
  );
150972
- const outDir = path57.dirname(outPath);
150444
+ const outDir = path56.dirname(outPath);
150973
150445
  await fsPromises7.mkdir(outDir, { recursive: true });
150974
150446
  await fsPromises7.writeFile(outPath, injectReportData6(html, data, lang), "utf8");
150975
150447
  const { stats } = contentCheck;
@@ -151131,8 +150603,8 @@ function isInfiniteOrCboBudget(row) {
151131
150603
  const cbo = row.budget_optimize_on;
151132
150604
  return cbo === true || cbo === "true" || cbo === 1 || cbo === "1";
151133
150605
  }
151134
- function parseLocalYmd2(ymd2) {
151135
- const parts = ymd2.trim().split("-").map((x) => parseInt(x, 10));
150606
+ function parseLocalYmd2(ymd) {
150607
+ const parts = ymd.trim().split("-").map((x) => parseInt(x, 10));
151136
150608
  if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n))) {
151137
150609
  return /* @__PURE__ */ new Date(NaN);
151138
150610
  }
@@ -151751,10 +151223,10 @@ function assertTikTokWriteOk(raw, label2) {
151751
151223
  const message = raw.message ?? "\u672A\u77E5\u9519\u8BEF";
151752
151224
  throw new Error(`${label2} \u4E1A\u52A1\u5931\u8D25 code=${String(code)}\uFF1A${message}`);
151753
151225
  }
151754
- async function putTikTok(path62, body, opts, section, commandLabel) {
151226
+ async function putTikTok(path61, body, opts, section, commandLabel) {
151755
151227
  const advertiserId = assertTikTokAccountId(opts.account);
151756
151228
  const config = loadConfig(opts.token);
151757
- const url = `${requireTikTokApiUrl(config)}/${path62}`;
151229
+ const url = `${requireTikTokApiUrl(config)}/${path61}`;
151758
151230
  const payload = await apiFetch2(
151759
151231
  url,
151760
151232
  config,
@@ -152079,7 +151551,7 @@ var YANDEX_SECTION_ALIASES = {
152079
151551
 
152080
151552
  // src/commands/yandex-analysis/run-batch.ts
152081
151553
  init_auth();
152082
- import * as path59 from "path";
151554
+ import * as path58 from "path";
152083
151555
  import { performance as performance8 } from "perf_hooks";
152084
151556
  init_version();
152085
151557
 
@@ -152091,8 +151563,8 @@ var YANDEX_SEARCH_TERMS_MAX_DAYS = 180;
152091
151563
  function stripLocalDate2(d) {
152092
151564
  return new Date(d.getFullYear(), d.getMonth(), d.getDate());
152093
151565
  }
152094
- function parseLocalYmd3(ymd2) {
152095
- const parts = ymd2.trim().split("-").map((x) => parseInt(x, 10));
151566
+ function parseLocalYmd3(ymd) {
151567
+ const parts = ymd.trim().split("-").map((x) => parseInt(x, 10));
152096
151568
  if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n))) {
152097
151569
  return /* @__PURE__ */ new Date(NaN);
152098
151570
  }
@@ -152219,25 +151691,25 @@ function endpointHintForYandexSection(def) {
152219
151691
  }
152220
151692
 
152221
151693
  // src/commands/yandex-analysis/merge-snapshot.ts
152222
- import * as fs48 from "fs/promises";
152223
- import * as path58 from "path";
151694
+ import * as fs47 from "fs/promises";
151695
+ import * as path57 from "path";
152224
151696
  function asRecord40(value) {
152225
151697
  if (value && typeof value === "object" && !Array.isArray(value)) {
152226
151698
  return value;
152227
151699
  }
152228
151700
  return null;
152229
151701
  }
152230
- function num14(value) {
151702
+ function num13(value) {
152231
151703
  if (value === null || value === void 0 || value === "") return void 0;
152232
151704
  const n = Number(value);
152233
151705
  return Number.isFinite(n) ? n : void 0;
152234
151706
  }
152235
- function round211(value) {
151707
+ function round210(value) {
152236
151708
  return value == null ? void 0 : Math.round(value * 100) / 100;
152237
151709
  }
152238
151710
  function normalizeYandexRoi(value) {
152239
151711
  if (typeof value !== "number" && typeof value !== "string") return void 0;
152240
- const r = num14(value);
151712
+ const r = num13(value);
152241
151713
  return r === -1 ? void 0 : r;
152242
151714
  }
152243
151715
  function asItems(payload) {
@@ -152248,19 +151720,19 @@ function asItems(payload) {
152248
151720
  return items3.filter((r) => asRecord40(r) !== null);
152249
151721
  }
152250
151722
  function pickMetrics2(row, extras = []) {
152251
- const spend = num14(row.spend) ?? 0;
152252
- const impressions = num14(row.impressions) ?? 0;
152253
- const clicks = num14(row.clicks) ?? 0;
152254
- const conversions = num14(row.conversions) ?? 0;
151723
+ const spend = num13(row.spend) ?? 0;
151724
+ const impressions = num13(row.impressions) ?? 0;
151725
+ const clicks = num13(row.clicks) ?? 0;
151726
+ const conversions = num13(row.conversions) ?? 0;
152255
151727
  const out = {
152256
151728
  spend,
152257
151729
  impressions,
152258
151730
  clicks,
152259
151731
  conversions,
152260
- ctr: num14(row.ctr) ?? (impressions > 0 ? clicks / impressions : void 0),
152261
- averageCpc: num14(row.averageCpc) ?? (clicks > 0 ? round211(spend / clicks) : void 0),
152262
- conversionRate: num14(row.conversionRate) ?? (clicks > 0 ? conversions / clicks : void 0),
152263
- costPerConversion: num14(row.costPerConversion) ?? (conversions > 0 ? round211(spend / conversions) : void 0),
151732
+ ctr: num13(row.ctr) ?? (impressions > 0 ? clicks / impressions : void 0),
151733
+ averageCpc: num13(row.averageCpc) ?? (clicks > 0 ? round210(spend / clicks) : void 0),
151734
+ conversionRate: num13(row.conversionRate) ?? (clicks > 0 ? conversions / clicks : void 0),
151735
+ costPerConversion: num13(row.costPerConversion) ?? (conversions > 0 ? round210(spend / conversions) : void 0),
152264
151736
  roi: normalizeYandexRoi(row.roi)
152265
151737
  };
152266
151738
  for (const f of extras) {
@@ -152270,7 +151742,7 @@ function pickMetrics2(row, extras = []) {
152270
151742
  }
152271
151743
  async function loadSectionPayload3(snapshotDir, file) {
152272
151744
  try {
152273
- const raw = await fs48.readFile(path58.join(snapshotDir, file), "utf8");
151745
+ const raw = await fs47.readFile(path57.join(snapshotDir, file), "utf8");
152274
151746
  return JSON.parse(raw);
152275
151747
  } catch {
152276
151748
  return null;
@@ -152280,7 +151752,7 @@ async function readManifest8(snapshotDir, accountId) {
152280
151752
  const candidates = [];
152281
151753
  if (accountId) candidates.push(reportManifestFile(accountId));
152282
151754
  try {
152283
- const entries = await fs48.readdir(snapshotDir);
151755
+ const entries = await fs47.readdir(snapshotDir);
152284
151756
  for (const name2 of entries.filter(
152285
151757
  (n) => n.startsWith("report-manifest") && n.endsWith(".json")
152286
151758
  )) {
@@ -152290,7 +151762,7 @@ async function readManifest8(snapshotDir, accountId) {
152290
151762
  }
152291
151763
  for (const name2 of candidates) {
152292
151764
  try {
152293
- const raw = await fs48.readFile(path58.join(snapshotDir, name2), "utf8");
151765
+ const raw = await fs47.readFile(path57.join(snapshotDir, name2), "utf8");
152294
151766
  const parsed = JSON.parse(raw);
152295
151767
  if (Array.isArray(parsed.artifacts) && parsed.artifacts.length > 0) return parsed;
152296
151768
  } catch {
@@ -152356,10 +151828,10 @@ function aggregateDailyToWeekly(dailyRows) {
152356
151828
  map.set(key, acc);
152357
151829
  }
152358
151830
  acc.days += 1;
152359
- acc.spend += num14(row.spend) ?? 0;
152360
- acc.impressions += num14(row.impressions) ?? 0;
152361
- acc.clicks += num14(row.clicks) ?? 0;
152362
- acc.conversions += num14(row.conversions) ?? 0;
151831
+ acc.spend += num13(row.spend) ?? 0;
151832
+ acc.impressions += num13(row.impressions) ?? 0;
151833
+ acc.clicks += num13(row.clicks) ?? 0;
151834
+ acc.conversions += num13(row.conversions) ?? 0;
152363
151835
  }
152364
151836
  return [...map.values()].sort((a, b) => a.weekStart.getTime() - b.weekStart.getTime()).map((acc) => {
152365
151837
  const startDate = formatYmd2(acc.weekStart);
@@ -152370,13 +151842,13 @@ function aggregateDailyToWeekly(dailyRows) {
152370
151842
  startDate,
152371
151843
  endDate,
152372
151844
  days: acc.days,
152373
- spend: round211(acc.spend),
151845
+ spend: round210(acc.spend),
152374
151846
  impressions: Math.round(acc.impressions),
152375
151847
  clicks: Math.round(acc.clicks),
152376
- conversions: round211(acc.conversions),
151848
+ conversions: round210(acc.conversions),
152377
151849
  ctr: acc.impressions > 0 ? acc.clicks / acc.impressions : void 0,
152378
- averageCpc: acc.clicks > 0 ? round211(acc.spend / acc.clicks) : void 0,
152379
- costPerConversion: acc.conversions > 0 ? round211(acc.spend / acc.conversions) : void 0
151850
+ averageCpc: acc.clicks > 0 ? round210(acc.spend / acc.clicks) : void 0,
151851
+ costPerConversion: acc.conversions > 0 ? round210(acc.spend / acc.conversions) : void 0
152380
151852
  };
152381
151853
  });
152382
151854
  }
@@ -152449,7 +151921,7 @@ function mapDeviceRows2(payload) {
152449
151921
  return asItems(payload).map((r) => pickMetrics2(r, ["device", "network"]));
152450
151922
  }
152451
151923
  async function mergeYandexAnalysisSnapshotIntoReport(payload, snapshotDir) {
152452
- const absDir = path58.resolve(snapshotDir);
151924
+ const absDir = path57.resolve(snapshotDir);
152453
151925
  const metaAccountId = typeof asRecord40(payload.meta)?.accountId === "string" ? asRecord40(payload.meta)?.accountId : void 0;
152454
151926
  const manifest = await readManifest8(snapshotDir, metaAccountId);
152455
151927
  if (!manifest) {
@@ -152474,24 +151946,24 @@ async function mergeYandexAnalysisSnapshotIntoReport(payload, snapshotDir) {
152474
151946
  if (!meta.platform) meta.platform = "Yandex Direct";
152475
151947
  const kpis = { ...payload.kpis ?? {} };
152476
151948
  if (totals) {
152477
- if (num14(totals.spend) != null) kpis.spend = round211(num14(totals.spend));
152478
- if (num14(totals.impressions) != null) kpis.impressions = Math.round(num14(totals.impressions));
152479
- if (num14(totals.clicks) != null) kpis.clicks = Math.round(num14(totals.clicks));
152480
- if (num14(totals.conversions) != null) kpis.conversions = round211(num14(totals.conversions));
152481
- if (num14(totals.ctr) != null) kpis.ctr = num14(totals.ctr);
152482
- if (num14(totals.averageCpc) != null) kpis.averageCpc = round211(num14(totals.averageCpc));
152483
- if (num14(totals.costPerConversion) != null) {
152484
- kpis.costPerConversion = round211(num14(totals.costPerConversion));
152485
- }
152486
- if (num14(totals.conversionRate) != null) kpis.conversionRate = num14(totals.conversionRate);
151949
+ if (num13(totals.spend) != null) kpis.spend = round210(num13(totals.spend));
151950
+ if (num13(totals.impressions) != null) kpis.impressions = Math.round(num13(totals.impressions));
151951
+ if (num13(totals.clicks) != null) kpis.clicks = Math.round(num13(totals.clicks));
151952
+ if (num13(totals.conversions) != null) kpis.conversions = round210(num13(totals.conversions));
151953
+ if (num13(totals.ctr) != null) kpis.ctr = num13(totals.ctr);
151954
+ if (num13(totals.averageCpc) != null) kpis.averageCpc = round210(num13(totals.averageCpc));
151955
+ if (num13(totals.costPerConversion) != null) {
151956
+ kpis.costPerConversion = round210(num13(totals.costPerConversion));
151957
+ }
151958
+ if (num13(totals.conversionRate) != null) kpis.conversionRate = num13(totals.conversionRate);
152487
151959
  const overviewRoi = normalizeYandexRoi(totals.roi);
152488
151960
  if (overviewRoi != null) kpis.roi = overviewRoi;
152489
151961
  }
152490
151962
  if (overview) {
152491
- if (num14(overview.balance) != null) kpis.balance = round211(num14(overview.balance));
152492
- if (num14(overview.avgDailySpend) != null)
152493
- kpis.avgDailySpend = round211(num14(overview.avgDailySpend));
152494
- if (num14(overview.activeDays) != null) kpis.activeDays = num14(overview.activeDays);
151963
+ if (num13(overview.balance) != null) kpis.balance = round210(num13(overview.balance));
151964
+ if (num13(overview.avgDailySpend) != null)
151965
+ kpis.avgDailySpend = round210(num13(overview.avgDailySpend));
151966
+ if (num13(overview.activeDays) != null) kpis.activeDays = num13(overview.activeDays);
152495
151967
  if (overview.balanceAsOf != null) kpis.balanceAsOf = overview.balanceAsOf;
152496
151968
  }
152497
151969
  if (kpis.balance != null && kpis.avgDailySpend != null && Number(kpis.avgDailySpend) > 0) {
@@ -152635,7 +152107,7 @@ async function runAllYandexSections(opts) {
152635
152107
  const results = await runWithConcurrency6(tasks, concurrency);
152636
152108
  const succeeded = results.filter((r) => r.ok).length;
152637
152109
  const failed = results.length - succeeded;
152638
- const absoluteSnapshotDir = path59.resolve(opts.jsonOut);
152110
+ const absoluteSnapshotDir = path58.resolve(opts.jsonOut);
152639
152111
  const summary = {
152640
152112
  kind: "siluzan-tso-yandex-analysis-snapshot-batch",
152641
152113
  absoluteSnapshotDir,
@@ -152653,9 +152125,9 @@ async function runAllYandexSections(opts) {
152653
152125
  }
152654
152126
 
152655
152127
  // src/commands/yandex-analysis/render-report.ts
152656
- import fs49 from "fs";
152128
+ import fs48 from "fs";
152657
152129
  import fsPromises8 from "fs/promises";
152658
- import path60 from "path";
152130
+ import path59 from "path";
152659
152131
  import { fileURLToPath as fileURLToPath15 } from "url";
152660
152132
 
152661
152133
  // src/commands/yandex-analysis/report-content.ts
@@ -152862,14 +152334,14 @@ init_html();
152862
152334
  var TEMPLATE_BASENAME6 = "yandex-period-report.html";
152863
152335
  var INJECT_MARKER6 = "window.__YANDEX_PERIOD_REPORT__ = window.__YANDEX_PERIOD_REPORT__ || null;";
152864
152336
  function resolveSkillTemplatePath9(basename14) {
152865
- const dir = path60.dirname(fileURLToPath15(import.meta.url));
152337
+ const dir = path59.dirname(fileURLToPath15(import.meta.url));
152866
152338
  const candidates = [
152867
- path60.join(dir, "skill", "report-templates", basename14),
152868
- path60.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
152869
- path60.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
152339
+ path59.join(dir, "skill", "report-templates", basename14),
152340
+ path59.join(dir, "skill", "siluzan-ads", "report-templates", basename14),
152341
+ path59.join(dir, "..", "..", "assets", "siluzan-ads", "report-templates", basename14)
152870
152342
  ];
152871
152343
  for (const p of candidates) {
152872
- if (fs49.existsSync(p)) return p;
152344
+ if (fs48.existsSync(p)) return p;
152873
152345
  }
152874
152346
  return candidates[0];
152875
152347
  }
@@ -152912,10 +152384,10 @@ function injectReportData7(html, payload, lang) {
152912
152384
  return localized.replace(INJECT_MARKER6, `window.__YANDEX_PERIOD_REPORT__ = ${json};`);
152913
152385
  }
152914
152386
  async function runYandexAnalysisRender(opts) {
152915
- const dataPath = path60.resolve(opts.dataFile);
152387
+ const dataPath = path59.resolve(opts.dataFile);
152916
152388
  let data = asRecord42(await readJsonFile9(dataPath));
152917
152389
  if (opts.snapshotDir?.trim()) {
152918
- data = await mergeYandexAnalysisSnapshotIntoReport(data, path60.resolve(opts.snapshotDir));
152390
+ data = await mergeYandexAnalysisSnapshotIntoReport(data, path59.resolve(opts.snapshotDir));
152919
152391
  }
152920
152392
  data = refreshWeeklyFromDaily(data);
152921
152393
  const lang = readReportLangOrExit({ flag: opts.lang, meta: data.meta });
@@ -152941,10 +152413,10 @@ async function runYandexAnalysisRender(opts) {
152941
152413
  `);
152942
152414
  process.exit(1);
152943
152415
  }
152944
- const outPath = path60.resolve(
152945
- opts.out ?? path60.join(path60.dirname(dataPath), "yandex-period-report.html")
152416
+ const outPath = path59.resolve(
152417
+ opts.out ?? path59.join(path59.dirname(dataPath), "yandex-period-report.html")
152946
152418
  );
152947
- const outDir = path60.dirname(outPath);
152419
+ const outDir = path59.dirname(outPath);
152948
152420
  await fsPromises8.mkdir(outDir, { recursive: true });
152949
152421
  await fsPromises8.writeFile(outPath, injectReportData7(html, data, lang), "utf8");
152950
152422
  const { stats } = contentCheck;
@@ -153045,13 +152517,13 @@ function optionalId(raw) {
153045
152517
  function insightsLevelToPath(level) {
153046
152518
  return level;
153047
152519
  }
153048
- function assertYandexAnalysisQuery(path62, query) {
153049
- const caps = YANDEX_PATH_CAPS[path62];
152520
+ function assertYandexAnalysisQuery(path61, query) {
152521
+ const caps = YANDEX_PATH_CAPS[path61];
153050
152522
  if (query.timeIncrement != null && !caps.timeIncrement) {
153051
- throw new Error(`--time-increment \u4E0D\u80FD\u7528\u4E8E /${path62}\uFF08\u4EC5 campaigns / adgroups / ads\uFF09\u3002`);
152523
+ throw new Error(`--time-increment \u4E0D\u80FD\u7528\u4E8E /${path61}\uFF08\u4EC5 campaigns / adgroups / ads\uFF09\u3002`);
153052
152524
  }
153053
152525
  if (query.network != null && !caps.network) {
153054
- throw new Error(`--network \u4E0D\u80FD\u7528\u4E8E /${path62}\uFF08\u4EC5 campaigns / geo / devices\uFF09\u3002`);
152526
+ throw new Error(`--network \u4E0D\u80FD\u7528\u4E8E /${path61}\uFF08\u4EC5 campaigns / geo / devices\uFF09\u3002`);
153055
152527
  }
153056
152528
  if (query.status != null && !caps.status) {
153057
152529
  throw new Error(`--status \u4EC5\u7528\u4E8E /ads\uFF08\u62D2\u5BA1/\u5BA1\u6838\u6001\u8D70\u7ED3\u6784\u67E5\u8BE2\uFF0C\u884C\u5185 spend \u4E3A 0\uFF09\u3002`);
@@ -153068,12 +152540,12 @@ function assertYandexAnalysisQuery(path62, query) {
153068
152540
  );
153069
152541
  }
153070
152542
  if (query.limit != null && !caps.limit) {
153071
- throw new Error(`--limit \u4E0D\u80FD\u7528\u4E8E /${path62}\uFF08overview / daily / devices \u65E0\u6B64\u53C2\u6570\uFF09\u3002`);
152543
+ throw new Error(`--limit \u4E0D\u80FD\u7528\u4E8E /${path61}\uFF08overview / daily / devices \u65E0\u6B64\u53C2\u6570\uFF09\u3002`);
153072
152544
  }
153073
152545
  }
153074
- function buildYandexAnalysisSearchParams(path62, query) {
153075
- assertYandexAnalysisQuery(path62, query);
153076
- const caps = YANDEX_PATH_CAPS[path62];
152546
+ function buildYandexAnalysisSearchParams(path61, query) {
152547
+ assertYandexAnalysisQuery(path61, query);
152548
+ const caps = YANDEX_PATH_CAPS[path61];
153077
152549
  const params = new URLSearchParams({
153078
152550
  account: query.account,
153079
152551
  start: query.start,
@@ -153099,10 +152571,10 @@ function buildYandexAnalysisSearchParams(path62, query) {
153099
152571
  }
153100
152572
  return params;
153101
152573
  }
153102
- async function fetchYandexAnalysisPath(config, path62, query, verbose) {
152574
+ async function fetchYandexAnalysisPath(config, path61, query, verbose) {
153103
152575
  const yandexApiUrl = requireYandexApi(config);
153104
- const params = buildYandexAnalysisSearchParams(path62, query);
153105
- const url = analysisUrl(yandexApiUrl, path62, params.toString());
152576
+ const params = buildYandexAnalysisSearchParams(path61, query);
152577
+ const url = analysisUrl(yandexApiUrl, path61, params.toString());
153106
152578
  return apiFetch2(url, config, {}, verbose);
153107
152579
  }
153108
152580
  function unwrapYandexItems(raw) {
@@ -153166,13 +152638,13 @@ ${args.title}
153166
152638
  console.log(` ${args.footnote}
153167
152639
  `);
153168
152640
  }
153169
- async function fetchPath(opts, path62, extra) {
152641
+ async function fetchPath(opts, path61, extra) {
153170
152642
  const accountId = assertYandexAccountId(opts.account);
153171
152643
  const { startDate, endDate } = resolveRange(opts.start, opts.end);
153172
152644
  const config = loadConfig(opts.token);
153173
152645
  const raw = await fetchYandexAnalysisPath(
153174
152646
  config,
153175
- path62,
152647
+ path61,
153176
152648
  {
153177
152649
  account: accountId,
153178
152650
  start: startDate,
@@ -153442,14 +152914,14 @@ function requireYandexEntityId(raw, label2) {
153442
152914
  }
153443
152915
  return id;
153444
152916
  }
153445
- function yandexAdsUrl(base2, path62, account) {
152917
+ function yandexAdsUrl(base2, path61, account) {
153446
152918
  const q = new URLSearchParams({ account });
153447
- return `${base2.replace(/\/$/, "")}/yandex-ads/${path62}?${q}`;
152919
+ return `${base2.replace(/\/$/, "")}/yandex-ads/${path61}?${q}`;
153448
152920
  }
153449
- async function postYandex(path62, body, opts, section, commandLabel) {
152921
+ async function postYandex(path61, body, opts, section, commandLabel) {
153450
152922
  const account = assertYandexAccountId(opts.account);
153451
152923
  const config = loadConfig(opts.token);
153452
- const url = yandexAdsUrl(requireYandexApi(config), path62, account);
152924
+ const url = yandexAdsUrl(requireYandexApi(config), path61, account);
153453
152925
  const payload = await apiFetch2(
153454
152926
  url,
153455
152927
  config,
@@ -153622,10 +153094,10 @@ function registerYandexAnalysisCommands(program2) {
153622
153094
  }
153623
153095
 
153624
153096
  // src/commands/ad-gap/catalog.ts
153625
- var bing = (path62, needsBody = true) => ({
153097
+ var bing = (path61, needsBody = true) => ({
153626
153098
  service: "tso",
153627
153099
  method: "POST",
153628
- path: `/reporting/media-account/BingV2/{account}/library/${path62}`,
153100
+ path: `/reporting/media-account/BingV2/{account}/library/${path61}`,
153629
153101
  needsBody
153630
153102
  });
153631
153103
  var BING_COVERAGE_WRITES = [
@@ -153812,10 +153284,10 @@ var BING_COVERAGE_READS = [
153812
153284
  "audience-group-assets",
153813
153285
  "audience-group-assets-by-audience"
153814
153286
  ];
153815
- var insight = (path62, method = "POST", needsBody = true) => ({
153287
+ var insight = (path61, method = "POST", needsBody = true) => ({
153816
153288
  service: "tso",
153817
153289
  method,
153818
- path: `/reporting/media-account/BingV2/{account}/insights/${path62}`,
153290
+ path: `/reporting/media-account/BingV2/{account}/insights/${path61}`,
153819
153291
  needsBody
153820
153292
  });
153821
153293
  function bingCoverage() {
@@ -153824,10 +153296,10 @@ function bingCoverage() {
153824
153296
  for (const name2 of BING_COVERAGE_READS) actions[`bing.read-${name2}`] = bing(`coverage-read/${name2}`);
153825
153297
  return actions;
153826
153298
  }
153827
- var yandex = (path62, extra) => ({
153299
+ var yandex = (path61, extra) => ({
153828
153300
  service: "yandex",
153829
153301
  method: "POST",
153830
- path: `/yandex-ads/library/${path62}`,
153302
+ path: `/yandex-ads/library/${path61}`,
153831
153303
  needsBody: true,
153832
153304
  ...extra
153833
153305
  });
@@ -153911,10 +153383,10 @@ function yandexCoverage() {
153911
153383
  for (const name2 of YANDEX_COVERAGE_READS) actions[`yandex.read-${name2}`] = yandex(`coverage-read/${name2}`);
153912
153384
  return actions;
153913
153385
  }
153914
- var facebook = (path62, extra) => ({
153386
+ var facebook = (path61, extra) => ({
153915
153387
  service: "facebook",
153916
153388
  method: "POST",
153917
- path: `/api/fb/ads/{account}/${path62}`,
153389
+ path: `/api/fb/ads/{account}/${path61}`,
153918
153390
  needsBody: true,
153919
153391
  ...extra
153920
153392
  });
@@ -154076,16 +153548,16 @@ function metaCoverage() {
154076
153548
  }
154077
153549
  return actions;
154078
153550
  }
154079
- var tiktok = (path62) => ({
153551
+ var tiktok = (path61) => ({
154080
153552
  service: "tiktok",
154081
153553
  method: "POST",
154082
- path: `/tiktokgap/${path62}`,
153554
+ path: `/tiktokgap/${path61}`,
154083
153555
  needsBody: true
154084
153556
  });
154085
- var google = (method, path62, extra) => ({
153557
+ var google = (method, path61, extra) => ({
154086
153558
  service: "google",
154087
153559
  method,
154088
- path: path62,
153560
+ path: path61,
154089
153561
  needsBody: method !== "GET" && method !== "DELETE",
154090
153562
  ...extra
154091
153563
  });
@@ -154385,20 +153857,20 @@ function resolveGapPath(actionName, target) {
154385
153857
  const parent = action.needsParent ? requireToken(target.parent, "parent") : target.parent?.trim() ?? "";
154386
153858
  const id = action.needsId ? requireToken(target.id, "id") : target.id?.trim() ?? "";
154387
153859
  const label2 = action.needsLabel ? requireToken(target.label, "label") : target.label?.trim() ?? "";
154388
- let path62 = action.path.replaceAll("{account}", encodeURIComponent(account)).replaceAll("{parent}", encodeURIComponent(parent)).replaceAll("{id}", encodeURIComponent(id)).replaceAll("{label}", encodeURIComponent(label2));
154389
- if (path62.includes("{")) {
153860
+ let path61 = action.path.replaceAll("{account}", encodeURIComponent(account)).replaceAll("{parent}", encodeURIComponent(parent)).replaceAll("{id}", encodeURIComponent(id)).replaceAll("{label}", encodeURIComponent(label2));
153861
+ if (path61.includes("{")) {
154390
153862
  throw new Error(`action ${actionName} \u8FD8\u7F3A\u8DEF\u5F84\u53C2\u6570`);
154391
153863
  }
154392
153864
  if (action.service === "yandex") {
154393
- path62 += `${path62.includes("?") ? "&" : "?"}account=${encodeURIComponent(account)}`;
153865
+ path61 += `${path61.includes("?") ? "&" : "?"}account=${encodeURIComponent(account)}`;
154394
153866
  }
154395
153867
  if (action.service === "facebook" && action.path.includes("/coverage")) {
154396
153868
  const extra = [];
154397
153869
  if (action.needsId) extra.push(`id=${encodeURIComponent(id)}`);
154398
153870
  if (action.needsParent) extra.push(`parent=${encodeURIComponent(parent)}`);
154399
- if (extra.length > 0) path62 += `${path62.includes("?") ? "&" : "?"}${extra.join("&")}`;
153871
+ if (extra.length > 0) path61 += `${path61.includes("?") ? "&" : "?"}${extra.join("&")}`;
154400
153872
  }
154401
- return { action, path: path62 };
153873
+ return { action, path: path61 };
154402
153874
  }
154403
153875
  function requireToken(value, label2) {
154404
153876
  const text5 = (value ?? "").trim();
@@ -154796,9 +154268,9 @@ function interceptAgentCompatArgv(argv) {
154796
154268
  installProcessHandlers();
154797
154269
  function getVersion() {
154798
154270
  try {
154799
- const __dirname3 = path61.dirname(fileURLToPath16(import.meta.url));
154800
- const pkgPath = path61.join(__dirname3, "..", "package.json");
154801
- const pkg = JSON.parse(fs50.readFileSync(pkgPath, "utf8"));
154271
+ const __dirname3 = path60.dirname(fileURLToPath16(import.meta.url));
154272
+ const pkgPath = path60.join(__dirname3, "..", "package.json");
154273
+ const pkg = JSON.parse(fs49.readFileSync(pkgPath, "utf8"));
154802
154274
  return pkg.version ?? "0.0.0";
154803
154275
  } catch {
154804
154276
  return "0.0.0";