@adport/mcp 0.13.0 → 0.13.1

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/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  assembleRuntime,
4
4
  runStdioServer
5
- } from "./chunk-TNQOM6VM.js";
5
+ } from "./chunk-TEP7TOPQ.js";
6
6
 
7
7
  // src/bin.ts
8
8
  var includeRawTools = process.argv.includes("--raw-api-tools");
@@ -22,7 +22,7 @@ import { createOpenAIModule } from "@adport/provider-openai";
22
22
  // package.json
23
23
  var package_default = {
24
24
  name: "@adport/mcp",
25
- version: "0.13.0",
25
+ version: "0.13.1",
26
26
  description: "adport MCP server \u2014 the open control plane for paid media",
27
27
  license: "Apache-2.0",
28
28
  type: "module",
@@ -73,7 +73,7 @@ var package_default = {
73
73
  jsdom: "26.1.0",
74
74
  tsup: "^8.3.0",
75
75
  typescript: "^5.8.0",
76
- vitest: "^4.1.10",
76
+ vitest: "^5.1.1",
77
77
  "@modelcontextprotocol/client": "^2.4.0"
78
78
  },
79
79
  repository: {
@@ -1537,23 +1537,6 @@ var GAQL_REPORT_UI = String.raw`
1537
1537
  return human(human(path.replace(/^segments\./, '')).toLowerCase()).replace(/\bid\b/i, 'ID');
1538
1538
  }
1539
1539
 
1540
- const gaqlMoneyFormats = new Map();
1541
- function gaqlAmount(amount, currency) {
1542
- const locale = state.host.locale || 'en', key = locale + '/' + (currency || '');
1543
- if (!gaqlMoneyFormats.has(key)) {
1544
- const digits = currency ? new Intl.NumberFormat(locale, {style:'currency', currency}).resolvedOptions().maximumFractionDigits : 2;
1545
- gaqlMoneyFormats.set(key, {
1546
- format: new Intl.NumberFormat(locale, {minimumFractionDigits:digits, maximumFractionDigits:digits}),
1547
- unit: 10 ** -digits
1548
- });
1549
- }
1550
- const {format, unit} = gaqlMoneyFormats.get(key);
1551
- if (Number(amount) !== 0 && Math.abs(Number(amount)) < unit) {
1552
- return Number(amount) < 0 ? '>' + format.format(-unit) : '<' + format.format(unit);
1553
- }
1554
- return format.format(amount);
1555
- }
1556
-
1557
1540
  function gaqlHasTrend(points, dimensions, paths) {
1558
1541
  // A dated series must refer to the same returned entity and breakdown on every date.
1559
1542
  if (points.length > 366 || new Set(points.map(point => point.date)).size < 2) return false;
@@ -1624,6 +1607,134 @@ var GAQL_REPORT_UI = String.raw`
1624
1607
  }
1625
1608
  `;
1626
1609
 
1610
+ // src/meta-insights-ui.ts
1611
+ var META_INSIGHTS_UI = String.raw`
1612
+ const metaBreakdownLabels = {
1613
+ publisher_platform:'Platform', platform_position:'Placement', impression_device:'Impression device', device_platform:'Device platform',
1614
+ age:'Age', gender:'Gender', country:'Country', region:'Region', dma:'DMA', zip:'ZIP', product_id:'Product ID',
1615
+ hourly_stats_aggregated_by_advertiser_time_zone:'Hour (ad account)', hourly_stats_aggregated_by_audience_time_zone:'Hour (audience)',
1616
+ image_asset:'Image', video_asset:'Video', title_asset:'Headline', body_asset:'Ad text', ad_format_asset:'Ad format',
1617
+ objective:'Objective', buying_type:'Buying type', attribution_setting:'Attribution setting'
1618
+ };
1619
+ function metaBreakdownKeys(payload) {
1620
+ return [...new Set([...arr(payload?.breakdowns).filter(key => typeof key === 'string'), ...Object.keys(metaBreakdownLabels)])];
1621
+ }
1622
+ function metaBreakdownValue(key, value) {
1623
+ if (object(value)) return workflowText(value.name || value.text || value.title || value.id || value.hash);
1624
+ if (typeof value === 'boolean') return value ? 'Yes' : 'No';
1625
+ const text = workflowText(value);
1626
+ return ['publisher_platform','platform_position','impression_device','device_platform','gender'].includes(key) ? human(text) : text;
1627
+ }
1628
+ function metaEntityValues(rows, level) {
1629
+ const names = rows.map(row => workflowText(row[level + '_name'])), ids = rows.map(row => workflowText(row[level + '_id']));
1630
+ const byName = new Map();
1631
+ names.forEach((name, i) => {
1632
+ if (!byName.has(name)) byName.set(name, new Set());
1633
+ byName.get(name).add(ids[i]);
1634
+ });
1635
+ return names.map((name, i) => name && ids[i] && byName.get(name).size > 1 ? name + ' (' + ids[i] + ')' : name || ids[i]);
1636
+ }
1637
+ function metaMetricLabel(key) {
1638
+ const [kind, action] = key.split(' · ');
1639
+ if (!action) return nativeReportLabel(key);
1640
+ const event = action.replaceAll('_', ' ');
1641
+ if (kind === 'actions' && /(?:^|_)(?:purchase|lead|install|click|registration)$/.test(action)) return human(event) + 's';
1642
+ if (kind === 'action_values') return human(event) + ' value';
1643
+ if (kind === 'cost_per_action_type') return 'Cost per ' + event;
1644
+ if (kind === 'purchase_roas') return human(event) + ' ROAS';
1645
+ return nativeReportLabel(key);
1646
+ }
1647
+
1648
+ function metaInsightsReport(records, points, payload) {
1649
+ const rows = records.map(record => record?.native || {}), dimensions = [];
1650
+ const add = (label, values) => {
1651
+ if (values.some(Boolean)) dimensions.push({label, values, shared:values.every(value => value === values[0])});
1652
+ };
1653
+ for (const [level, label] of [['account','Account'],['campaign','Campaign'],['adset','Ad set'],['ad','Ad']]) {
1654
+ add(label, metaEntityValues(rows, level));
1655
+ }
1656
+ for (const key of metaBreakdownKeys(payload)) {
1657
+ if (rows.some(row => Object.hasOwn(row, key))) add(Object.hasOwn(metaBreakdownLabels,key) ? metaBreakdownLabels[key] : recordLabel(key), rows.map(row => metaBreakdownValue(key, row[key])));
1658
+ }
1659
+ const seriesDimensions = dimensions.filter(dimension => !dimension.shared);
1660
+ const locale = state.host.locale || 'en';
1661
+ const dates = new Intl.DateTimeFormat(locale, {month:'short', day:'numeric', year:'numeric', timeZone:'UTC'});
1662
+ const periodLabels = new Map();
1663
+ const periods = rows.map(row => {
1664
+ const start = reportDate(row.date_start), end = reportDate(row.date_stop), key = [start,end].join('/');
1665
+ if (!periodLabels.has(key)) {
1666
+ const from = start && new Date(start), to = end && new Date(end);
1667
+ const period = from && to && from <= to ? dates.formatRange(from, to) :
1668
+ from && !to ? 'From ' + dates.format(from) : to && !from ? 'Through ' + dates.format(to) : '';
1669
+ periodLabels.set(key, period);
1670
+ }
1671
+ return periodLabels.get(key);
1672
+ });
1673
+ add('Period', periods);
1674
+
1675
+ const varying = dimensions.filter(dimension => !dimension.shared), scope = dimensions.filter(dimension => dimension.shared).map(dimension => dimension.values[0]);
1676
+ const joined = (columns, i) => columns.map(column => column.values[i] || '—').join(' · ');
1677
+ const label = varying.map(dimension => dimension.label).join(' / ');
1678
+ const title = varying.length ? 'Performance by ' + varying.map(dimension => dimension.label.toLowerCase()).join(' and ') : 'Meta ad performance';
1679
+ const currencies = new Set(records.map(record => record?.currency || ''));
1680
+ const numeric = new Intl.NumberFormat(locale, {maximumFractionDigits:2});
1681
+ const fieldsByRow = points.map(point => {
1682
+ const fields = new Map();
1683
+ for (const field of point.fields) {
1684
+ const display = field.shortDisplay ?? (field.value === null ? field.display : numeric.format(field.display));
1685
+ const suffix = /(?:^|_)ctr$/.test(field.key) ? '%' : field.key.startsWith('purchase_roas · ') ? '×' : '';
1686
+ const shortDisplay = display + (field.value !== null ? suffix : '');
1687
+ fields.set(field.key, fields.has(field.key) ? {...field, value:null, shortDisplay:'See Details'} :
1688
+ {...field, label:metaMetricLabel(field.key), shortDisplay, display:shortDisplay + (field.unit ? ' ' + field.unit : '')});
1689
+ }
1690
+ return fields;
1691
+ });
1692
+ const keys = [...new Set(fieldsByRow.flatMap(fields => [...fields.keys()]))];
1693
+ const priority = key => /^(?:actions|purchase_roas|cost_per_action_type) · (?:.*[_.])?(?:purchase|lead|install|registration)$/.test(key) ? 5 : reportMetricPriority(key);
1694
+ keys.sort((a,b) => priority(a) - priority(b));
1695
+ const isMoney = key => nativeReportMoneyField(key, 'meta');
1696
+ if (keys.some(isMoney) && currencies.has('')) scope.push('Currency unavailable');
1697
+ const subject = scope.join(' · ');
1698
+ const view = html => ({title, subject, html});
1699
+ if (!keys.length) return view(workflowNote('No metrics were returned for this selection.'));
1700
+ if (rows.length > 1 && !varying.length) return view(workflowNote('These rows have no distinguishing labels. Include a campaign, ad set, ad name, or a breakdown such as placement to compare them.'));
1701
+
1702
+ const shown = keys.slice(0,5), currency = currencies.size === 1 && records[0]?.currency;
1703
+ const metricHeader = key => metaMetricLabel(key) + (currency && isMoney(key) ? ' · ' + currency : '');
1704
+ const cell = (i, key) => {
1705
+ const field = fieldsByRow[i].get(key);
1706
+ if (!field) return '—';
1707
+ return field.shortDisplay + (field.value !== null && isMoney(key) && currencies.size > 1 ? ' ' + (records[i]?.currency || '(unknown currency)') : '');
1708
+ };
1709
+ const extra = keys.length > shown.length ? workflowNote((keys.length - shown.length) + ' more metrics in Details.') : '';
1710
+ if (rows.length === 1) return view('<div class="meta-insight-kpis">' + workflowFields(shown.map(key => [metricHeader(key),cell(0,key)])) + '</div>' + extra);
1711
+
1712
+ const names = rows.map((_,i) => joined(varying,i));
1713
+ const distinct = new Set(names).size === rows.length && rows.every((_,i) => varying.some(column => column.values[i]));
1714
+ const comparable = periods.every(period => period === periods[0]) && (!isMoney(keys[0]) || (currencies.size === 1 && (currency || new Set(rows.map(row => row.account_id)).size === 1)));
1715
+ const ranked = comparable && (keys[0] === 'spend' || keys.length === 1) && fieldsByRow.some(fields => available(fields.get(keys[0])?.value));
1716
+ const order = rows.map((_,i) => i);
1717
+ if (ranked) order.sort((a,b) => (fieldsByRow[b].get(keys[0])?.value ?? -Infinity) - (fieldsByRow[a].get(keys[0])?.value ?? -Infinity));
1718
+
1719
+ // Only join daily observations of an identified entity or breakdown.
1720
+ const series = rows.map((_,i) => joined(seriesDimensions,i) || joined(dimensions.filter(column => column.label !== 'Period'),i));
1721
+ const seriesCount = new Set(series).size;
1722
+ const trend = keys.length === 1 && distinct && rows.length <= 366 && dimensions.some(column => column.label !== 'Period') &&
1723
+ points.every(point => point.date) && new Set(points.map(point => point.date)).size > 1 && seriesCount <= 3 &&
1724
+ seriesCount < rows.length && (!isMoney(keys[0]) || currencies.size === 1);
1725
+ if (trend || (keys.length === 1 && ranked && distinct && rows.length <= 8)) {
1726
+ const pointsForChart = order.map(i => ({name:names[i], series:series[i], date:points[i].date, fields:[fieldsByRow[i].get(keys[0])].filter(Boolean)}));
1727
+ const chart = reportCharts(pointsForChart, {metric:keys[0], mode:trend ? undefined : 'bars', label:metaMetricLabel(keys[0]) + (trend ? ' over time' : '')});
1728
+ return {...view(chart.html), mount:chart.mount};
1729
+ }
1730
+ const note = distinct ? '' : workflowNote('Some rows share a label or are missing one. A more specific name, ID, or breakdown can distinguish them.');
1731
+ const values = order.slice(0,1000).map(i => [names[i], ...shown.map(key => cell(i,key))]);
1732
+ const table = workflowTable([label, ...shown.map(metricHeader)], values, title, {compact:true, sorted:ranked ? 1 : -1});
1733
+ const limit = values.length < rows.length ? workflowNote('Showing 1,000 of ' + rows.length.toLocaleString(locale) + ' returned rows. All rows are in Details.') : '';
1734
+ return view(note + '<div class="meta-insights-table">' + table + '</div>' + extra + limit);
1735
+ }
1736
+ `;
1737
+
1627
1738
  // src/native-report-ui.ts
1628
1739
  var NATIVE_REPORT_TOOLS = [
1629
1740
  "ga4_report",
@@ -1644,10 +1755,17 @@ var NATIVE_REPORT_TOOLS = [
1644
1755
  ];
1645
1756
  var NATIVE_REPORT_UI_STYLES = String.raw`
1646
1757
  .native-report-metrics { grid-template-columns:repeat(auto-fit,minmax(min(110px,100%),1fr)) }
1758
+ .meta-insights-table .workflow-table :is(th,td):not(:first-child) { text-align:right; white-space:nowrap }
1759
+ .meta-insights-table .workflow-table :is(th,td):first-child { min-width:8rem }
1760
+ .meta-insights-table [aria-sort="descending"]::after { content:' ↓'; color:var(--ink) }
1761
+ .meta-insight-kpis .record-fields { display:flex; flex-wrap:wrap; gap:14px 28px }
1762
+ .meta-insight-kpis .record-fields dt { color:var(--muted); font-size:11px }
1763
+ .meta-insight-kpis .record-fields dd { margin:4px 0 0; font-size:20px; font-weight:600; font-variant-numeric:tabular-nums }
1647
1764
  `;
1648
1765
  var NATIVE_REPORT_UI_SCRIPT = String.raw`
1649
1766
  const nativeReportTools=new Set(${JSON.stringify(NATIVE_REPORT_TOOLS)});
1650
1767
  ${GAQL_REPORT_UI}
1768
+ ${META_INSIGHTS_UI}
1651
1769
  function nativeReportDecimal(value,scale=0) {
1652
1770
  const text=typeof value==='number'&&Number.isFinite(value)?String(value):typeof value==='string'?value:'';
1653
1771
  if(!/^-?\d+(?:\.\d+)?$/.test(text))return null;
@@ -1678,7 +1796,7 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1678
1796
  return typeof value==='string'||typeof value==='number'||typeof value==='boolean'?String(value):'—';
1679
1797
  }
1680
1798
  function nativeReportMoneyField(key,provider,moneyFields=[]) {
1681
- return moneyFields.includes(key)||/^(spend|revenue|cpc|cpm|cost_per_conversion|costInLocalCurrency|costInUsd|total_complete_payment_rate|conversion_.*_total_value)$|^(?:action_values|cost_per_action_type) · /i.test(key)||provider==='google'&&(/Micros$/.test(key)||/conversionsValue$/i.test(key));
1799
+ return moneyFields.includes(key)||/^(spend|revenue|cpc|cpm|cost_per_conversion|costInLocalCurrency|costInUsd|total_complete_payment_rate|conversion_.*_total_value)$|^(?:action_values|cost_per_action_type) · /i.test(key)||provider==='meta'&&/^(?:cpp$|cost_per_)/.test(key)||provider==='google'&&(/Micros$/.test(key)||/conversionsValue$/i.test(key));
1682
1800
  }
1683
1801
  function nativeReportScale(key,provider) { return provider==='reddit'?/total_value$/i.test(key)?2:6:provider==='google'&&/Micros$/.test(key)?6:0; }
1684
1802
  function reportBucket(value) {
@@ -1698,9 +1816,11 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1698
1816
  const googleName=googleDimensions?.get(googleEntity);
1699
1817
  const bucket=dimensions.conversionLagBucket??dimensions.conversionOrAdjustmentLagBucket;
1700
1818
  const analyticsName=['ga4','gsc'].includes(provider)?Object.values(dimensions).filter(value=>typeof value==='string'&&value).join(' · '):null;
1701
- const name=bucket?reportBucket(bucket):googleName??analyticsName??first(names,[row,metrics,dimensions]) ?? first(ids,[row,dimensions]) ?? (provider==='google'?'Report':'Result '+(index+1));
1819
+ const identity=bucket?reportBucket(bucket):googleName??analyticsName??first(names,[row,metrics,dimensions])??first(ids,[row,dimensions]);
1820
+ const name=identity??(provider==='google'?'Report':provider==='meta'?'Reported metrics':'Result '+(index+1));
1702
1821
  const status=first(['entity_status','status'],[row]);
1703
1822
  const dimensionKeys=['date','day','week','month','stat_time_day','stat_time_hour','country','countryOrRegion','countryCode','country_code','country_id','deviceClass','device_platform','age','gender','platform','placement','insight_value','genre','BidMatchType','match_type','date_start','date_stop','start_time','end_time'];
1823
+ if(provider==='meta')dimensionKeys.push(...metaBreakdownKeys(payload));
1704
1824
  const context=[...new Set([...dimensionKeys.flatMap(key=>[row[key],dimensions[key]]),...(provider==='google'?Object.entries(dimensions).filter(([key,value])=>!['conversionLagBucket','conversionOrAdjustmentLagBucket','date'].includes(key)&&typeof value==='string').map(([,value])=>human(value.toLowerCase())):[]),...(bucket&&googleName?[googleName]:[])].filter(value=>typeof value==='string'&&value))];
1705
1825
  const currency=[row.currency,row.account_currency,row.currency_code,row.customer?.currencyCode,metrics.currency,payload.currency,payload.metadata?.currencyCode,meta.currency].find(value=>typeof value==='string'&&/^[A-Z]{3}$/.test(value));
1706
1826
  const ignored=new Set([...names,...ids,...dimensionKeys,'currency','account_currency','currency_code','entity_type','status','entity_status','report_type','FileUrlExpiryTimeUtc','file_available','timezone']);
@@ -1716,7 +1836,7 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1716
1836
  const priority=key=>/^(spend|impressions|clicks)$/i.test(key)?['spend','impressions','clicks'].indexOf(key.toLowerCase()):/^(conversion|conversions|purchases)$|^actions · purchase$/i.test(key)?3:4;
1717
1837
  fields.sort((a,b)=>priority(a[0])-priority(b[0]));
1718
1838
  const moneyFields=provider==='ga4'?arr(payload.metric_headers).filter(header=>header.type==='TYPE_CURRENCY').map(header=>header.name):[];
1719
- return {name,status,context,currency,moneyFields,provider,fields,gaqlDimensions:googleDimensions,gaqlEntity:googleEntity,native:row,date:reportDate(dimensions.stat_time_day??(provider==='ga4'&&/^\d{8}$/.test(dimensions.date||'')?dimensions.date.replace(/^(\d{4})(\d{2})(\d{2})$/,'$1-$2-$3'):dimensions.date)??(row.date_start===row.date_stop?row.date_start:null)??(row.date_range?.start===row.date_range?.end?row.date_range?.start:null)),series:googleName||(['ga4','gsc'].includes(provider)?Object.entries(dimensions).filter(([key])=>key!=='date').map(([,value])=>value).join(' · ')||'Website':name)};
1839
+ return {name,identity,status,context,currency,moneyFields,provider,fields,gaqlDimensions:googleDimensions,gaqlEntity:googleEntity,native:row,date:reportDate(dimensions.stat_time_day??(provider==='ga4'&&/^\d{8}$/.test(dimensions.date||'')?dimensions.date.replace(/^(\d{4})(\d{2})(\d{2})$/,'$1-$2-$3'):dimensions.date)??(row.date_start===row.date_stop?row.date_start:null)??(row.date_range?.start===row.date_range?.end?row.date_range?.start:null)),series:googleName||(['ga4','gsc'].includes(provider)?Object.entries(dimensions).filter(([key])=>key!=='date').map(([,value])=>value).join(' · ')||'Website':name)};
1720
1840
  }
1721
1841
  function nativeChartRecord(record) {
1722
1842
  if(!record)return {name:'Unavailable row',context:[],fields:[]};
@@ -1725,9 +1845,9 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1725
1845
  const ratio=nativeReportRatio(key,record.provider);
1726
1846
  const value=record.provider==='spotify'&&String(raw)==='-5'?null:reportNumber(monetary?scaled:raw);
1727
1847
  const display=nativeReportMetric(key,raw,record.provider,record.currency,record.moneyFields);
1728
- const googleMoney=record.provider==='google'&&monetary;
1729
- const shortDisplay=googleMoney&&scaled!==null?gaqlAmount(scaled,record.currency):undefined;
1730
- return {key,label:key==='costInLocalCurrency'?'Spend':key==='costInUsd'?'Spend · USD':nativeReportLabel(key),value:ratio&&value!==null?value*100:value,display,shortDisplay,unit:ratio?'%':monetary?key==='costInUsd'?'USD':record.currency||(googleMoney?'Currency unavailable':'Account units'):''};
1848
+ const shortMoney=monetary&&['google','meta'].includes(record.provider);
1849
+ const shortDisplay=shortMoney&&scaled!==null?reportAmount(scaled,record.currency):undefined;
1850
+ return {key,label:key==='costInLocalCurrency'?'Spend':key==='costInUsd'?'Spend · USD':nativeReportLabel(key),value:ratio&&value!==null?value*100:value,display,shortDisplay,unit:ratio?'%':monetary?key==='costInUsd'?'USD':record.currency||(record.provider==='meta'?'':shortMoney?'Currency unavailable':'Account units'):''};
1731
1851
  });
1732
1852
  const low=record.native.lowImpressionShare,high=record.native.highImpressionShare;
1733
1853
  const range=record.provider==='apple'&&[low,high].every(value=>typeof value==='number'&&Number.isFinite(value)&&value>=0&&value<=1)&&low<=high?[low,high]:undefined;
@@ -1750,19 +1870,27 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1750
1870
  const errors=arr(data.errors).filter(error=>error?.error_code).map(error=>'<p class="notice">Goal '+esc(error.goal_id||'unavailable')+': '+esc(error.error_code)+'</p>').join('');
1751
1871
  const missingGoals=arr(data.not_returned_goal_ids).filter(id=>!arr(data.errors).some(error=>error?.goal_id===id&&error?.error_code));
1752
1872
  const absent=missingGoals.length?'<p class="notice">No summary returned for goal'+(missingGoals.length===1?'':'s')+' '+missingGoals.map(esc).join(', ')+'.</p>':'';
1753
- const records=entries.slice(0,1000).map((row,index)=>nativeReportRecord(row,index,meta,payload)),delay=provider==='google'&&entries.some(row=>row?.segments?.conversionLagBucket||row?.segments?.conversionOrAdjustmentLagBucket);
1873
+ const records=(provider==='meta'?entries:entries.slice(0,1000)).map((row,index)=>nativeReportRecord(row,index,meta,payload)),delay=provider==='google'&&entries.some(row=>row?.segments?.conversionLagBucket||row?.segments?.conversionOrAdjustmentLagBucket);
1754
1874
  const pageArgs=['ga4_report','gsc_search_analytics'].includes(meta.tool)?readPageArgs(meta,'data-report-next'):null;
1755
1875
  const points=records.map(nativeChartRecord);
1756
- const table=provider==='google'&&!delay&&entries.length?gaqlReportTable(records,points):null;
1876
+ let presentation;
1877
+ if(entries.length && provider==='meta') presentation=metaInsightsReport(records,points,payload);
1878
+ if(entries.length && provider==='google' && !delay) presentation=gaqlReportTable(records,points);
1879
+ if(!presentation && records.length>1 && records.every(row=>row&&!workflowText(row.identity)) &&
1880
+ new Set(records.map(row=>JSON.stringify([row.context,row.date,row.currency]))).size===1) {
1881
+ presentation={html:workflowNote('These rows have no distinguishing labels. Include an entity name or a breakdown to compare them.'), detailRows:true};
1882
+ }
1757
1883
  const entity=records[0]?.gaqlEntity;
1758
1884
  const dimension=entity&&records.every(row=>row?.gaqlEntity===entity)?gaqlEntities.get(entity).toLowerCase():undefined;
1759
- const chart=table?null:reportCharts(points,delay?{dimension:'delay',mode:'bars',metric:records.some(record=>record?.fields.some(([key])=>key==='conversions'))?'conversions':undefined}:meta.tool==='apple_impression_share'?{metric:'Impression share',dimension:'search term'}:{dimension});
1885
+ const chart=entries.length&&!presentation?reportCharts(points,delay?{dimension:'delay',mode:'bars',metric:records.some(record=>record?.fields.some(([key])=>key==='conversions'))?'conversions':undefined}:meta.tool==='apple_impression_share'?{metric:'Impression share',dimension:'search term'}:{dimension}):null;
1760
1886
  const analytics=['ga4','gsc'].includes(provider),range=payload?.date_range;
1761
1887
  const period=analytics&&object(range)?[range.start_date??range.start,range.end_date??range.end].filter(workflowText).join(' – '):'';
1762
- const subject=table?.subject||(analytics?[meta.accountId,period].filter(Boolean).join(' · '):'');
1763
- const body=table?.html||(entries.length?chart.html:'<p class="operation-note">'+missing+'</p>');
1764
- app.innerHTML=chrome(operationHeader(table?.title||(delay?'Conversion delay':title),subject,provider)+notices({...data,...(meta.tool==='linkedin_demographic_report'?{notes:[]}:{}),errors:arr(data.errors).filter(error=>!error?.error_code)})+errors+absent+'<section data-native-report data-read-page-focus tabindex="-1">'+body+(meta.tool==='linkedin_demographic_report'?'<p class="report-chart-foot">Approximate demographics · privacy thresholds apply</p>':'')+(entries.length>1000?'<p class="operation-note">Showing 1,000 returned rows. The full response is in Details.</p>':'')+readPageMarkup(pageArgs,'data-report-next','data-report-page-status')+'<details class="report-data"><summary>Details · '+entries.length+' results</summary>'+(!table&&entries.length?'<div class="record-list" role="region" aria-label="Native report data" tabindex="0">'+entries.slice(0,1000).map((row,index)=>nativeReportRow(row,index,meta,payload)).join('')+'</div>':'')+'<pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details></section>',table?entries.length+(entries.length===1?' row':' rows'):'');
1765
- chart?.mount();
1888
+ const subject=presentation?.subject||(analytics?[meta.accountId,period].filter(Boolean).join(' · '):'');
1889
+ const view=presentation||chart;
1890
+ const body=view?.html||'<p class="operation-note">'+missing+'</p>';
1891
+ const showDetailRows=!presentation||presentation.detailRows||provider==='meta'&&entries.length===1;
1892
+ app.innerHTML=chrome(operationHeader(presentation?.title||(delay?'Conversion delay':title),subject,provider)+notices({...data,...(meta.tool==='linkedin_demographic_report'?{notes:[]}:{}),errors:arr(data.errors).filter(error=>!error?.error_code)})+errors+absent+'<section data-native-report data-read-page-focus tabindex="-1">'+body+(meta.tool==='linkedin_demographic_report'?'<p class="report-chart-foot">Approximate demographics · privacy thresholds apply</p>':'')+(provider!=='meta'&&entries.length>1000?'<p class="operation-note">Showing 1,000 returned rows. The full response is in Details.</p>':'')+readPageMarkup(pageArgs,'data-report-next','data-report-page-status')+'<details class="report-data"><summary>Details · '+entries.length+' result'+(entries.length===1?'':'s')+'</summary>'+(showDetailRows&&entries.length?'<div class="record-list" role="region" aria-label="Native report data" tabindex="0">'+entries.slice(0,1000).map((row,index)=>nativeReportRow(row,index,meta,payload)).join('')+'</div>':'')+'<pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details></section>',presentation?entries.length+(entries.length===1?' row':' rows'):'');
1893
+ view?.mount?.();
1766
1894
  bindReadPage(meta,pageArgs,'data-report-next','data-report-page-status',value=>Array.isArray(recordPayload(value)?.rows));
1767
1895
  }
1768
1896
  `;
@@ -1817,9 +1945,9 @@ var WORKFLOW_UI = String.raw`
1817
1945
  (status?'<span class="pill '+tone+'">'+esc(status)+'</span>':'')+'</div>'+body+'</'+tag+'>';
1818
1946
  }
1819
1947
 
1820
- function workflowHeader(labels) {
1821
- return '<thead role="rowgroup"><tr role="row">'+labels.map(label=>
1822
- '<th role="columnheader" scope="col">'+esc(label)+'</th>').join('')+'</tr></thead>';
1948
+ function workflowHeader(labels,sorted=-1) {
1949
+ return '<thead role="rowgroup"><tr role="row">'+labels.map((label,i)=>
1950
+ '<th role="columnheader" scope="col"'+(i===sorted?' aria-sort="descending"':'')+'>'+esc(label)+'</th>').join('')+'</tr></thead>';
1823
1951
  }
1824
1952
 
1825
1953
  function workflowCell(label,html,heading=false) {
@@ -1828,10 +1956,10 @@ var WORKFLOW_UI = String.raw`
1828
1956
  '<span class="workflow-cell-label" aria-hidden="true" data-label="'+esc(label)+'"></span><span>'+html+'</span></'+tag+'>';
1829
1957
  }
1830
1958
 
1831
- function workflowTable(labels,rows,description) {
1959
+ function workflowTable(labels,rows,description,{compact=false,sorted=-1}={}) {
1832
1960
  if(!rows.length)return '';
1833
- return '<div class="workflow-scroll" role="region" aria-label="'+esc(description)+'" tabindex="0">'+
1834
- '<table class="workflow-table workflow-stack" role="table">'+workflowHeader(labels)+'<tbody role="rowgroup">'+
1961
+ return '<div class="'+(compact?'collection-scroll':'workflow-scroll')+'" role="region" aria-label="'+esc(description)+'" tabindex="0">'+
1962
+ '<table class="workflow-table'+(compact?'':' workflow-stack')+'" role="table">'+workflowHeader(labels,sorted)+'<tbody role="rowgroup">'+
1835
1963
  rows.map(row=>'<tr role="row">'+row.map((value,i)=>workflowCell(labels[i],esc(workflowText(value)||'—'),i===0)).join('')+'</tr>').join('')+
1836
1964
  '</tbody></table></div>';
1837
1965
  }
@@ -2316,6 +2444,23 @@ var REPORT_CHART_SCRIPT = String.raw`
2316
2444
  function reportNumber(value) {
2317
2445
  const decimal=nativeReportDecimal(value);return decimal!==null&&Number.isFinite(Number(decimal))?Number(decimal):null;
2318
2446
  }
2447
+ const reportMoneyFormats = new Map();
2448
+ function reportAmount(amount, currency) {
2449
+ const locale = state.host.locale || 'en', key = locale + '/' + (currency || '');
2450
+ if (!reportMoneyFormats.has(key)) {
2451
+ const digits = currency ? new Intl.NumberFormat(locale, {style:'currency', currency}).resolvedOptions().maximumFractionDigits : 2;
2452
+ reportMoneyFormats.set(key, {
2453
+ format: new Intl.NumberFormat(locale, {minimumFractionDigits:digits, maximumFractionDigits:digits}),
2454
+ unit: 10 ** -digits
2455
+ });
2456
+ }
2457
+ const {format, unit} = reportMoneyFormats.get(key);
2458
+ if (Number(amount) !== 0 && Math.abs(Number(amount)) < unit) {
2459
+ return Number(amount) < 0 ? '>' + format.format(-unit) : '<' + format.format(unit);
2460
+ }
2461
+ return format.format(amount);
2462
+ }
2463
+
2319
2464
  function reportMetricPriority(key) {
2320
2465
  const value=key.replaceAll('_','').toLowerCase();
2321
2466
  const order=['spend','costmicros','costinlocalcurrency','costinusd','conversions','conversion','totalinstalls','installs','purchases','clicks','taps','impressions','searchpopularity1to100','searchpopularityingenre','searchpopularity1to5','overallsuccesscount','successcount'];
@@ -2378,8 +2523,8 @@ var REPORT_CHART_SCRIPT = String.raw`
2378
2523
  `;
2379
2524
 
2380
2525
  // src/ui.ts
2381
- var ADPORT_UI_URI = "ui://adport/insight-card-v36.html";
2382
- var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-v36.html";
2526
+ var ADPORT_UI_URI = "ui://adport/insight-card-v40.html";
2527
+ var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-v40.html";
2383
2528
  var ADPORT_UI_DOMAIN = "https://app.adport.dev";
2384
2529
  var ADPORT_UI_RESOURCE_DOMAINS = [
2385
2530
  ADPORT_UI_DOMAIN,
@@ -2858,7 +3003,7 @@ ${PLANNING_UI}
2858
3003
 
2859
3004
  // src/index.ts
2860
3005
  var PROVIDER_IDS = ["ga4", "gsc", "gtm", "google", "meta", "tiktok", "apple", "microsoft", "reddit", "snapchat", "spotify", "pinterest", "linkedin", "x", "openai"];
2861
- var ADPORT_UI_RESOURCE_URIS = [ADPORT_UI_URI, "ui://adport/insight-card-v35.html", "ui://adport/insight-card-v34.html", "ui://adport/insight-card-v33.html", "ui://adport/insight-card-v32.html", "ui://adport/insight-card-v31.html", "ui://adport/insight-card-v30.html", "ui://adport/insight-card-v29.html", "ui://adport/insight-card-v28.html", "ui://adport/insight-card-v27.html", "ui://adport/insight-card-v26.html", "ui://adport/insight-card-v25.html", "ui://adport/insight-card-v24.html", "ui://adport/insight-card-v23.html", "ui://adport/insight-card-v22.html", "ui://adport/insight-card-v21.html", "ui://adport/insight-card-v20.html", "ui://adport/insight-card-v19.html", "ui://adport/insight-card-v18.html", "ui://adport/insight-card-v17.html", "ui://adport/insight-card-v16.html", "ui://adport/insight-card-v15.html", "ui://adport/insight-card-v14.html", "ui://adport/insight-card-v13.html", "ui://adport/insight-card-v12.html", "ui://adport/insight-card-v11.html", "ui://adport/insight-card-v10.html", "ui://adport/insight-card-v9.html", "ui://adport/insight-card-v8.html", "ui://adport/insight-card-v7.html", "ui://adport/insight-card-v6.html", "ui://adport/insight-card-v5.html", "ui://adport/insight-card-v4.html", "ui://adport/insight-card-v3.html", "ui://adport/insight-card-v2.html", ADPORT_SUMMARY_UI_URI, "ui://adport/summary-card-v35.html", "ui://adport/summary-card-v34.html", "ui://adport/summary-card-v33.html", "ui://adport/summary-card-v32.html", "ui://adport/summary-card-v30.html"];
3006
+ var ADPORT_UI_RESOURCE_URIS = [ADPORT_UI_URI, "ui://adport/insight-card-v36.html", "ui://adport/insight-card-v35.html", "ui://adport/insight-card-v34.html", "ui://adport/insight-card-v33.html", "ui://adport/insight-card-v32.html", "ui://adport/insight-card-v31.html", "ui://adport/insight-card-v30.html", "ui://adport/insight-card-v29.html", "ui://adport/insight-card-v28.html", "ui://adport/insight-card-v27.html", "ui://adport/insight-card-v26.html", "ui://adport/insight-card-v25.html", "ui://adport/insight-card-v24.html", "ui://adport/insight-card-v23.html", "ui://adport/insight-card-v22.html", "ui://adport/insight-card-v21.html", "ui://adport/insight-card-v20.html", "ui://adport/insight-card-v19.html", "ui://adport/insight-card-v18.html", "ui://adport/insight-card-v17.html", "ui://adport/insight-card-v16.html", "ui://adport/insight-card-v15.html", "ui://adport/insight-card-v14.html", "ui://adport/insight-card-v13.html", "ui://adport/insight-card-v12.html", "ui://adport/insight-card-v11.html", "ui://adport/insight-card-v10.html", "ui://adport/insight-card-v9.html", "ui://adport/insight-card-v8.html", "ui://adport/insight-card-v7.html", "ui://adport/insight-card-v6.html", "ui://adport/insight-card-v5.html", "ui://adport/insight-card-v4.html", "ui://adport/insight-card-v3.html", "ui://adport/insight-card-v2.html", ADPORT_SUMMARY_UI_URI, "ui://adport/summary-card-v36.html", "ui://adport/summary-card-v35.html", "ui://adport/summary-card-v34.html", "ui://adport/summary-card-v33.html", "ui://adport/summary-card-v32.html", "ui://adport/summary-card-v30.html"];
2862
3007
  var DEFAULT_MCP_ICONS = [{
2863
3008
  src: "https://app.adport.dev/icon.svg?brand=orange-dot-v2",
2864
3009
  mimeType: "image/svg+xml",
@@ -3077,4 +3222,4 @@ export {
3077
3222
  createMcpServer,
3078
3223
  runStdioServer
3079
3224
  };
3080
- //# sourceMappingURL=chunk-TNQOM6VM.js.map
3225
+ //# sourceMappingURL=chunk-TEP7TOPQ.js.map