@adport/mcp 0.13.0 → 0.13.2

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.
@@ -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.2",
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: {
@@ -989,10 +989,11 @@ var CREATIVE_UI_SCRIPT = String.raw`
989
989
  };
990
990
  const unique=values=>[...new Set(arr(values).filter(value=>typeof value==='string'&&value.trim()))];
991
991
  return creatives.map(creative=>{
992
- const name=creative.name || 'Untitled creative',status=statusOf(creative.status);
992
+ const name=creative.name || 'Untitled creative',delivery=creative.deliveryStatus || creative.status;
993
+ const status=statusOf(delivery==='ADSET_PAUSED'?'Ad set paused':delivery==='CAMPAIGN_PAUSED'?'Campaign paused':delivery);
993
994
  const destination=arr(creative.landing_urls).map(value=>safeUrl(value)).find(Boolean);
994
995
  const headline=unique(creative.headlines).filter(text=>text!==name).join(' · '),copy=unique(creative.descriptions).filter(text=>text!==name&&text!==headline).join('\n');
995
- const active=/^(active|enabled|ready|approved)$/i.test(creative.status || '');
996
+ const active=/^(active|enabled|ready|approved)$/i.test(delivery || '');
996
997
  return '<article class="creative-card" data-media-id="'+esc(creative.id)+'"><div class="creative-heading">'+(providerSvg[creative.provider]?logo(creative.provider):'')+'<span class="creative-name" title="'+esc(name)+'">'+esc(name)+'</span>'+(menuFor?menuFor(creative):'')+'</div>'+mediaView(creative)+'<div class="creative-copy">'+(headline?'<strong title="'+esc(headline)+'">'+esc(headline)+'</strong>':'')+(copy?'<p title="'+esc(copy)+'">'+esc(copy)+'</p>':'')+'</div><div class="creative-footer"><span class="creative-status'+(active?' creative-status-active':'')+'">'+esc(status.label)+'</span>'+(destination?'<a class="creative-destination" href="'+esc(destination.href)+'" target="_blank" rel="noopener noreferrer">'+esc(destination.hostname.replace(/^www\./,''))+'</a>':'')+'</div></article>';
997
998
  }).join('');
998
999
  }
@@ -1042,6 +1043,19 @@ var PROVIDER_GALLERY_UI = String.raw`
1042
1043
  let providerGallery=null;
1043
1044
  const galleryStable=value=>JSON.stringify((function sort(v){return Array.isArray(v)?v.map(sort):object(v)?Object.fromEntries(Object.entries(v).sort(([a],[b])=>a.localeCompare(b)).map(([k,item])=>[k,sort(item)])):v;})(value));
1044
1045
  const galleryItemKey=item=>[item.provider,item.account_id,item.id].join(':');
1046
+ function galleryItems(data,meta) {
1047
+ const creatives=arr(data.creatives);
1048
+ if(meta.tool!=='meta_list_ads' || !Array.isArray(data.ads)) return creatives;
1049
+ const delivery=new Map();
1050
+ for(const ad of data.ads) {
1051
+ if(typeof ad?.effective_status==='string' && ad.effective_status && typeof ad.account_id==='string' && typeof ad.id==='string')
1052
+ delivery.set(galleryItemKey({provider:'meta',account_id:ad.account_id,id:ad.id}),ad.effective_status);
1053
+ }
1054
+ return creatives.map(item=>{
1055
+ const status=delivery.get(galleryItemKey(item));
1056
+ return status?{...item,deliveryStatus:status}:item;
1057
+ });
1058
+ }
1045
1059
  function galleryScope(meta) {
1046
1060
  const args={...meta.refresh?.arguments};delete args[meta.pagination?.cursorInput];
1047
1061
  return galleryStable({tool:meta.tool,provider:meta.provider,account:meta.accountId,project:meta.context?.project_id,filters:args});
@@ -1080,12 +1094,12 @@ var PROVIDER_GALLERY_UI = String.raw`
1080
1094
  bindGalleryCard(card,gallery);
1081
1095
  }
1082
1096
  function renderProviderGallery(data,meta) {
1083
- const previous=providerGallery,previousWrite=previous?.meta.capabilities?.can_write,retain=previous && previous.scope===galleryScope(meta) && app.querySelector('[data-provider-gallery]');
1097
+ const previous=providerGallery,previousWrite=previous?.meta.capabilities?.can_write,retain=meta.accountId && previous && previous.scope===galleryScope(meta) && app.querySelector('[data-provider-gallery]');
1084
1098
  if(!retain) providerGallery={scope:galleryScope(meta),data,meta,items:new Map(),sources:new Map(),seen:new Set(),busy:null,review:null};
1085
1099
  const gallery=providerGallery;gallery.data=data;gallery.meta=meta;
1086
1100
  if(!retain) app.innerHTML=chrome('<div data-provider-notes></div><div class="creative-grid" data-provider-gallery role="region" aria-label="Creative previews" tabindex="0"></div><div data-provider-pages></div>','');
1087
1101
  const root=app.querySelector('[data-provider-gallery]');
1088
- for(const item of arr(data.creatives)) {
1102
+ for(const item of galleryItems(data,meta)) {
1089
1103
  const key=galleryItemKey(item);gallery.sources.set(key,meta.refresh?.arguments);if(gallery.items.has(key)) {const old=gallery.items.get(key);if(galleryStable(old)!==galleryStable(item) || previousWrite!==meta.capabilities?.can_write) {const card=[...root.querySelectorAll('[data-creative-key]')].find(node=>node.dataset.creativeKey===key);gallery.items.set(key,item);if(card) {if(meta.capabilities?.can_write!==true) card.querySelector('[data-creative-editor]')?.remove();updateGalleryCard(card,old,item,gallery);}}continue;}
1090
1104
  gallery.items.set(key,item);
1091
1105
  const template=document.createElement('template');template.innerHTML=creativeCards([item],galleryMenu);const card=template.content.firstElementChild;card.dataset.creativeKey=key;root.append(card);bindGalleryCard(card,gallery);bindCreativeErrors(card);
@@ -1093,7 +1107,8 @@ var PROVIDER_GALLERY_UI = String.raw`
1093
1107
  root.querySelector('.empty')?.remove();if(!gallery.items.size) root.innerHTML='<div class="empty">No creatives to preview.</div>';
1094
1108
  root.classList.toggle('creative-grid-single',gallery.items.size===1);
1095
1109
  app.querySelector('[data-provider-notes]').innerHTML=notices({...data,truncated:false});
1096
- state.result={structuredContent:{...data,creatives:[...gallery.items.values()],_adport:meta}};renderProviderPages();
1110
+ if(meta.accountId) state.result={structuredContent:{...data,creatives:[...gallery.items.values()],_adport:meta}};
1111
+ renderProviderPages();
1097
1112
  }
1098
1113
  function renderProviderPages(message='') {
1099
1114
  const gallery=providerGallery,area=app.querySelector('[data-provider-pages]');if(!gallery || !area) return;
@@ -1167,7 +1182,7 @@ var PROVIDER_GALLERY_UI = String.raw`
1167
1182
  gallery.busy={kind:'refresh',tool:gallery.meta.tool,args};renderProviderPages();
1168
1183
  try {
1169
1184
  const response=await callTool(gallery.meta.tool,args,60000),value=galleryPageValue(response,gallery,args);if(providerGallery!==gallery) return;
1170
- const updated=value.creatives.find(item=>galleryItemKey(item)===review.key);
1185
+ const updated=galleryItems(value,value._adport).find(item=>galleryItemKey(item)===review.key);
1171
1186
  if(!updated && !(phase==='applied' && review.kind==='remove')) throw new Error('The edited creative is outside this page. Ask your assistant for a fresh view.');
1172
1187
  if(!updated) {
1173
1188
  gallery.items.delete(review.key);gallery.sources.delete(review.key);card?.remove();gallery.seen.clear();
@@ -1244,13 +1259,6 @@ var OPERATION_UI_SCRIPT = String.raw`
1244
1259
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
1245
1260
  ${OPERATION_RECONCILIATION_UI}
1246
1261
  const human = value => String(value).replace(/([a-z])([A-Z])/g,'$1 $2').replace(/[_.]/g,' ').replace(/^./,c=>c.toUpperCase());
1247
- function resultData(result) {
1248
- if (result?.structuredContent && typeof result.structuredContent === 'object') return result.structuredContent;
1249
- for (const item of arr(result?.content)) {
1250
- if (item.type === 'text') { try { const value=JSON.parse(item.text),data=object(value)?value:{value};return result._meta?.adport?{...data,_adport:result._meta.adport}:data; } catch {} }
1251
- }
1252
- return Array.isArray(result)?{value:result}:result || {};
1253
- }
1254
1262
  function dataFields(value, prefix='', depth=0) {
1255
1263
  if (!object(value) || depth>8) return [];
1256
1264
  return Object.entries(value).filter(([key])=>!['_adport','data_source','pending_operation_id'].includes(key)).flatMap(([key,item])=>{
@@ -1431,7 +1439,7 @@ var OPERATION_UI_SCRIPT = String.raw`
1431
1439
  else send({jsonrpc:'2.0',id:id++,method:'ui/update-model-context',params:{structuredContent:{adport_operation:facts}}});
1432
1440
  }
1433
1441
  function renderFailure(data,meta,isWrite) {
1434
- const phase=errorPhase(data),title=phase==='expired'?'Preview expired':phase==='blocked'?'Action blocked':isWrite?'Outcome unconfirmed':'Request failed';
1442
+ const phase=errorPhase(data),title=phase==='expired'?'Preview expired':phase==='blocked'?'Action blocked':isWrite?'Outcome unconfirmed':data.error==='UNREADABLE_TOOL_RESULT'?'Result unreadable':'Request failed';
1435
1443
  app.innerHTML=chrome(operationHeader(title,meta.accountId,meta.provider)+'<p class="operation-note" role="alert">'+esc(data.message || (isWrite?'Check the result before retrying.':'See the tool response for details.'))+'</p>'+(!['expired','blocked'].includes(phase) && isWrite?'<p class="operation-note">Check the current state before retrying.</p>':'')+'<details><summary>Details</summary><pre>'+esc(JSON.stringify(data,null,2))+'</pre></details>','');
1436
1444
  }
1437
1445
  `;
@@ -1467,9 +1475,12 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
1467
1475
  const fields=[['Spend',appleReportMoney(metrics.localSpend)],['Taps',taps===null?'—':taps.toLocaleString(state.host.locale||'en')],['Installs',installs===null?'—':installs.toLocaleString(state.host.locale||'en')],['CPI',installs===0?'—':appleReportMoney(metrics.totalAvgCPI)]];
1468
1476
  return '<dl class="record-fields apple-report-metrics">'+fields.map(([label,value])=>'<div><dt>'+esc(label)+'</dt><dd>'+esc(value)+'</dd></div>').join('')+'</dl>';
1469
1477
  }
1478
+ function appleEntityName(metadata) {
1479
+ return [metadata?.searchTermText,metadata?.text,metadata?.name,metadata?.keyword?.text].find(value=>typeof value==='string' && value.trim()) ?? String(metadata?.id ?? '');
1480
+ }
1470
1481
  function appleReportRow(row,index) {
1471
1482
  const metadata=object(row?.metadata)?row.metadata:{},keyword=object(metadata.keyword)?metadata.keyword:{};
1472
- const name=[metadata.searchTermText,metadata.text,metadata.name,keyword.text].find(value=>typeof value==='string'&&value.trim()) ?? (metadata.id!==undefined?String(metadata.id):'Unnamed result '+(index+1));
1483
+ const name=appleEntityName(metadata) || 'Unnamed result '+(index+1);
1473
1484
  const status=[metadata.displayStatus,metadata.systemStatus,metadata.status].find(value=>typeof value==='string'&&value);
1474
1485
  const dimensions=['countryOrRegion','countryCode','adminArea','locality','deviceClass','ageRange','gender'].flatMap(key=>typeof metadata[key]==='string'&&metadata[key]?[metadata[key]]:[]);
1475
1486
  const matchType=metadata.matchType||keyword.matchType;
@@ -1479,8 +1490,8 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
1479
1490
  return '<article class="record-row"><div class="record-heading"><strong>'+esc(name)+'</strong>'+(status?'<span>'+esc(human(status.toLowerCase()))+'</span>':'')+'</div>'+(dimensions.length?'<p class="apple-report-dimensions">'+dimensions.map(esc).join(' · ')+'</p>':'')+(hasTotals||!periods.length?appleReportMetrics(row?.totalMetrics):'')+breakdown+'</article>';
1480
1491
  }
1481
1492
  function appleChartRecord(row,index,metrics=row?.totalMetrics) {
1482
- const metadata=object(row?.metadata)?row.metadata:{},keyword=object(metadata.keyword)?metadata.keyword:{};
1483
- const name=[metadata.searchTermText,metadata.text,metadata.name,keyword.text].find(value=>typeof value==='string'&&value.trim())??String(metadata.id??'Unnamed result '+(index+1));
1493
+ const metadata=object(row?.metadata)?row.metadata:{};
1494
+ const name=appleEntityName(metadata) || 'Unnamed result '+(index+1);
1484
1495
  const context=['countryOrRegion','countryCode','deviceClass','ageRange','gender'].flatMap(key=>typeof metadata[key]==='string'?[metadata[key]]:[]);
1485
1496
  const fields=[['spend','Spend',metrics?.localSpend?.amount,appleReportMoney(metrics?.localSpend),currencyOf(metrics?.localSpend||{})||'Account units'],['taps','Taps',metrics?.taps,appleReportNumber(metrics?.taps)===null?'—':String(metrics.taps),''],['installs','Installs',metrics?.totalInstalls,appleReportNumber(metrics?.totalInstalls)===null?'—':String(metrics.totalInstalls),'']].map(([key,label,raw,display,unit])=>({key,label,value:appleReportNumber(raw),display,unit}));
1486
1497
  for(const [key,raw] of Object.entries(metrics||{}))if(!['localSpend','taps','totalInstalls','date'].includes(key)) {
@@ -1489,10 +1500,13 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
1489
1500
  }
1490
1501
  return {name,context:typeof metrics?.date==='string'&&!reportDate(metrics.date)?[...context,metrics.date]:context,series:[name,...context].join(' · '),date:reportDate(metrics?.date),fields};
1491
1502
  }
1492
- function appleReportOverview(metrics) {
1503
+ function appleReportOverview(metrics,entityName) {
1493
1504
  if(!object(metrics))return '';
1494
1505
  const taps=appleReportNumber(metrics.taps),installs=appleReportNumber(metrics.totalInstalls);
1495
- return '<div class="report-overview apple-report-total" aria-label="Report total"><div><small>Total spend</small><strong>'+esc(appleReportMoney(metrics.localSpend))+'</strong></div><dl><div><dt>Taps</dt><dd>'+esc(taps??'—')+'</dd></div><div><dt>Installs</dt><dd>'+esc(installs??'—')+'</dd></div>'+(installs>0&&object(metrics.totalAvgCPI)?'<div><dt>CPI</dt><dd>'+esc(appleReportMoney(metrics.totalAvgCPI))+'</dd></div>':'')+'</dl></div>';
1506
+ if(taps===null && installs===null && appleReportNumber(metrics.localSpend?.amount)===null)return '';
1507
+ const grandTotal=entityName===undefined,label=grandTotal?'Report total':'Returned row metrics';
1508
+ const spend=grandTotal?'Total spend':entityName?'Spend · '+entityName:'Spend for this row';
1509
+ return '<div class="report-overview'+(grandTotal?' apple-report-total':'')+'" aria-label="'+label+'"><div><small>'+esc(spend)+'</small><strong>'+esc(appleReportMoney(metrics.localSpend))+'</strong></div><dl><div><dt>Taps</dt><dd>'+esc(taps??'—')+'</dd></div><div><dt>Installs</dt><dd>'+esc(installs??'—')+'</dd></div>'+(installs>0&&object(metrics.totalAvgCPI)?'<div><dt>CPI</dt><dd>'+esc(appleReportMoney(metrics.totalAvgCPI))+'</dd></div>':'')+'</dl></div>';
1496
1510
  }
1497
1511
  function renderAppleReport(data,meta) {
1498
1512
  const payload=recordPayload(data),hasRows=object(payload)&&Array.isArray(payload.rows),rows=hasRows?payload.rows:[];
@@ -1500,7 +1514,8 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
1500
1514
  const grandTotal=payload?.summary?.grandTotal;
1501
1515
  // Use Apple's explicit total, which can cover more rows than this page.
1502
1516
  // Never sum breakdowns, average CPIs, or mix currencies in the widget.
1503
- const summary=rows.length?appleReportOverview(grandTotal):'';
1517
+ const single=rows.length===1?rows[0]:null;
1518
+ const summary=rows.length?appleReportOverview(grandTotal) || (single?appleReportOverview(single.totalMetrics,appleEntityName(single.metadata)):''):'';
1504
1519
  const pagination=data.pagination,offset=pagination?.offset,count=pagination?.totalCount;
1505
1520
  const page=rows.length&&Number.isSafeInteger(offset)&&offset>=0&&Number.isSafeInteger(count)&&count>=offset+rows.length&&(offset>0||count>rows.length)?'<p class="apple-report-page">Showing '+(offset+1)+'–'+(offset+Math.min(rows.length,1000))+' of '+count+' results</p>':'';
1506
1521
  const clean={...data};delete clean._adport;
@@ -1537,23 +1552,6 @@ var GAQL_REPORT_UI = String.raw`
1537
1552
  return human(human(path.replace(/^segments\./, '')).toLowerCase()).replace(/\bid\b/i, 'ID');
1538
1553
  }
1539
1554
 
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
1555
  function gaqlHasTrend(points, dimensions, paths) {
1558
1556
  // A dated series must refer to the same returned entity and breakdown on every date.
1559
1557
  if (points.length > 366 || new Set(points.map(point => point.date)).size < 2) return false;
@@ -1624,6 +1622,134 @@ var GAQL_REPORT_UI = String.raw`
1624
1622
  }
1625
1623
  `;
1626
1624
 
1625
+ // src/meta-insights-ui.ts
1626
+ var META_INSIGHTS_UI = String.raw`
1627
+ const metaBreakdownLabels = {
1628
+ publisher_platform:'Platform', platform_position:'Placement', impression_device:'Impression device', device_platform:'Device platform',
1629
+ age:'Age', gender:'Gender', country:'Country', region:'Region', dma:'DMA', zip:'ZIP', product_id:'Product ID',
1630
+ hourly_stats_aggregated_by_advertiser_time_zone:'Hour (ad account)', hourly_stats_aggregated_by_audience_time_zone:'Hour (audience)',
1631
+ image_asset:'Image', video_asset:'Video', title_asset:'Headline', body_asset:'Ad text', ad_format_asset:'Ad format',
1632
+ objective:'Objective', buying_type:'Buying type', attribution_setting:'Attribution setting'
1633
+ };
1634
+ function metaBreakdownKeys(payload) {
1635
+ return [...new Set([...arr(payload?.breakdowns).filter(key => typeof key === 'string'), ...Object.keys(metaBreakdownLabels)])];
1636
+ }
1637
+ function metaBreakdownValue(key, value) {
1638
+ if (object(value)) return workflowText(value.name || value.text || value.title || value.id || value.hash);
1639
+ if (typeof value === 'boolean') return value ? 'Yes' : 'No';
1640
+ const text = workflowText(value);
1641
+ return ['publisher_platform','platform_position','impression_device','device_platform','gender'].includes(key) ? human(text) : text;
1642
+ }
1643
+ function metaEntityValues(rows, level) {
1644
+ const names = rows.map(row => workflowText(row[level + '_name'])), ids = rows.map(row => workflowText(row[level + '_id']));
1645
+ const byName = new Map();
1646
+ names.forEach((name, i) => {
1647
+ if (!byName.has(name)) byName.set(name, new Set());
1648
+ byName.get(name).add(ids[i]);
1649
+ });
1650
+ return names.map((name, i) => name && ids[i] && byName.get(name).size > 1 ? name + ' (' + ids[i] + ')' : name || ids[i]);
1651
+ }
1652
+ function metaMetricLabel(key) {
1653
+ const [kind, action] = key.split(' · ');
1654
+ if (!action) return nativeReportLabel(key);
1655
+ const event = action.replaceAll('_', ' ');
1656
+ if (kind === 'actions' && /(?:^|_)(?:purchase|lead|install|click|registration)$/.test(action)) return human(event) + 's';
1657
+ if (kind === 'action_values') return human(event) + ' value';
1658
+ if (kind === 'cost_per_action_type') return 'Cost per ' + event;
1659
+ if (kind === 'purchase_roas') return human(event) + ' ROAS';
1660
+ return nativeReportLabel(key);
1661
+ }
1662
+
1663
+ function metaInsightsReport(records, points, payload) {
1664
+ const rows = records.map(record => record?.native || {}), dimensions = [];
1665
+ const add = (label, values) => {
1666
+ if (values.some(Boolean)) dimensions.push({label, values, shared:values.every(value => value === values[0])});
1667
+ };
1668
+ for (const [level, label] of [['account','Account'],['campaign','Campaign'],['adset','Ad set'],['ad','Ad']]) {
1669
+ add(label, metaEntityValues(rows, level));
1670
+ }
1671
+ for (const key of metaBreakdownKeys(payload)) {
1672
+ if (rows.some(row => Object.hasOwn(row, key))) add(Object.hasOwn(metaBreakdownLabels,key) ? metaBreakdownLabels[key] : recordLabel(key), rows.map(row => metaBreakdownValue(key, row[key])));
1673
+ }
1674
+ const seriesDimensions = dimensions.filter(dimension => !dimension.shared);
1675
+ const locale = state.host.locale || 'en';
1676
+ const dates = new Intl.DateTimeFormat(locale, {month:'short', day:'numeric', year:'numeric', timeZone:'UTC'});
1677
+ const periodLabels = new Map();
1678
+ const periods = rows.map(row => {
1679
+ const start = reportDate(row.date_start), end = reportDate(row.date_stop), key = [start,end].join('/');
1680
+ if (!periodLabels.has(key)) {
1681
+ const from = start && new Date(start), to = end && new Date(end);
1682
+ const period = from && to && from <= to ? dates.formatRange(from, to) :
1683
+ from && !to ? 'From ' + dates.format(from) : to && !from ? 'Through ' + dates.format(to) : '';
1684
+ periodLabels.set(key, period);
1685
+ }
1686
+ return periodLabels.get(key);
1687
+ });
1688
+ add('Period', periods);
1689
+
1690
+ const varying = dimensions.filter(dimension => !dimension.shared), scope = dimensions.filter(dimension => dimension.shared).map(dimension => dimension.values[0]);
1691
+ const joined = (columns, i) => columns.map(column => column.values[i] || '—').join(' · ');
1692
+ const label = varying.map(dimension => dimension.label).join(' / ');
1693
+ const title = varying.length ? 'Performance by ' + varying.map(dimension => dimension.label.toLowerCase()).join(' and ') : 'Meta ad performance';
1694
+ const currencies = new Set(records.map(record => record?.currency || ''));
1695
+ const numeric = new Intl.NumberFormat(locale, {maximumFractionDigits:2});
1696
+ const fieldsByRow = points.map(point => {
1697
+ const fields = new Map();
1698
+ for (const field of point.fields) {
1699
+ const display = field.shortDisplay ?? (field.value === null ? field.display : numeric.format(field.display));
1700
+ const suffix = /(?:^|_)ctr$/.test(field.key) ? '%' : field.key.startsWith('purchase_roas · ') ? '×' : '';
1701
+ const shortDisplay = display + (field.value !== null ? suffix : '');
1702
+ fields.set(field.key, fields.has(field.key) ? {...field, value:null, shortDisplay:'See Details'} :
1703
+ {...field, label:metaMetricLabel(field.key), shortDisplay, display:shortDisplay + (field.unit ? ' ' + field.unit : '')});
1704
+ }
1705
+ return fields;
1706
+ });
1707
+ const keys = [...new Set(fieldsByRow.flatMap(fields => [...fields.keys()]))];
1708
+ const priority = key => /^(?:actions|purchase_roas|cost_per_action_type) · (?:.*[_.])?(?:purchase|lead|install|registration)$/.test(key) ? 5 : reportMetricPriority(key);
1709
+ keys.sort((a,b) => priority(a) - priority(b));
1710
+ const isMoney = key => nativeReportMoneyField(key, 'meta');
1711
+ if (keys.some(isMoney) && currencies.has('')) scope.push('Currency unavailable');
1712
+ const subject = scope.join(' · ');
1713
+ const view = html => ({title, subject, html});
1714
+ if (!keys.length) return view(workflowNote('No metrics were returned for this selection.'));
1715
+ 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.'));
1716
+
1717
+ const shown = keys.slice(0,5), currency = currencies.size === 1 && records[0]?.currency;
1718
+ const metricHeader = key => metaMetricLabel(key) + (currency && isMoney(key) ? ' · ' + currency : '');
1719
+ const cell = (i, key) => {
1720
+ const field = fieldsByRow[i].get(key);
1721
+ if (!field) return '—';
1722
+ return field.shortDisplay + (field.value !== null && isMoney(key) && currencies.size > 1 ? ' ' + (records[i]?.currency || '(unknown currency)') : '');
1723
+ };
1724
+ const extra = keys.length > shown.length ? workflowNote((keys.length - shown.length) + ' more metrics in Details.') : '';
1725
+ if (rows.length === 1) return view('<div class="meta-insight-kpis">' + workflowFields(shown.map(key => [metricHeader(key),cell(0,key)])) + '</div>' + extra);
1726
+
1727
+ const names = rows.map((_,i) => joined(varying,i));
1728
+ const distinct = new Set(names).size === rows.length && rows.every((_,i) => varying.some(column => column.values[i]));
1729
+ 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)));
1730
+ const ranked = comparable && (keys[0] === 'spend' || keys.length === 1) && fieldsByRow.some(fields => available(fields.get(keys[0])?.value));
1731
+ const order = rows.map((_,i) => i);
1732
+ if (ranked) order.sort((a,b) => (fieldsByRow[b].get(keys[0])?.value ?? -Infinity) - (fieldsByRow[a].get(keys[0])?.value ?? -Infinity));
1733
+
1734
+ // Only join daily observations of an identified entity or breakdown.
1735
+ const series = rows.map((_,i) => joined(seriesDimensions,i) || joined(dimensions.filter(column => column.label !== 'Period'),i));
1736
+ const seriesCount = new Set(series).size;
1737
+ const trend = keys.length === 1 && distinct && rows.length <= 366 && dimensions.some(column => column.label !== 'Period') &&
1738
+ points.every(point => point.date) && new Set(points.map(point => point.date)).size > 1 && seriesCount <= 3 &&
1739
+ seriesCount < rows.length && (!isMoney(keys[0]) || currencies.size === 1);
1740
+ if (trend || (keys.length === 1 && ranked && distinct && rows.length <= 8)) {
1741
+ const pointsForChart = order.map(i => ({name:names[i], series:series[i], date:points[i].date, fields:[fieldsByRow[i].get(keys[0])].filter(Boolean)}));
1742
+ const chart = reportCharts(pointsForChart, {metric:keys[0], mode:trend ? undefined : 'bars', label:metaMetricLabel(keys[0]) + (trend ? ' over time' : '')});
1743
+ return {...view(chart.html), mount:chart.mount};
1744
+ }
1745
+ const note = distinct ? '' : workflowNote('Some rows share a label or are missing one. A more specific name, ID, or breakdown can distinguish them.');
1746
+ const values = order.slice(0,1000).map(i => [names[i], ...shown.map(key => cell(i,key))]);
1747
+ const table = workflowTable([label, ...shown.map(metricHeader)], values, title, {compact:true, sorted:ranked ? 1 : -1});
1748
+ const limit = values.length < rows.length ? workflowNote('Showing 1,000 of ' + rows.length.toLocaleString(locale) + ' returned rows. All rows are in Details.') : '';
1749
+ return view(note + '<div class="meta-insights-table">' + table + '</div>' + extra + limit);
1750
+ }
1751
+ `;
1752
+
1627
1753
  // src/native-report-ui.ts
1628
1754
  var NATIVE_REPORT_TOOLS = [
1629
1755
  "ga4_report",
@@ -1644,10 +1770,17 @@ var NATIVE_REPORT_TOOLS = [
1644
1770
  ];
1645
1771
  var NATIVE_REPORT_UI_STYLES = String.raw`
1646
1772
  .native-report-metrics { grid-template-columns:repeat(auto-fit,minmax(min(110px,100%),1fr)) }
1773
+ .meta-insights-table .workflow-table :is(th,td):not(:first-child) { text-align:right; white-space:nowrap }
1774
+ .meta-insights-table .workflow-table :is(th,td):first-child { min-width:8rem }
1775
+ .meta-insights-table [aria-sort="descending"]::after { content:' ↓'; color:var(--ink) }
1776
+ .meta-insight-kpis .record-fields { display:flex; flex-wrap:wrap; gap:14px 28px }
1777
+ .meta-insight-kpis .record-fields dt { color:var(--muted); font-size:11px }
1778
+ .meta-insight-kpis .record-fields dd { margin:4px 0 0; font-size:20px; font-weight:600; font-variant-numeric:tabular-nums }
1647
1779
  `;
1648
1780
  var NATIVE_REPORT_UI_SCRIPT = String.raw`
1649
1781
  const nativeReportTools=new Set(${JSON.stringify(NATIVE_REPORT_TOOLS)});
1650
1782
  ${GAQL_REPORT_UI}
1783
+ ${META_INSIGHTS_UI}
1651
1784
  function nativeReportDecimal(value,scale=0) {
1652
1785
  const text=typeof value==='number'&&Number.isFinite(value)?String(value):typeof value==='string'?value:'';
1653
1786
  if(!/^-?\d+(?:\.\d+)?$/.test(text))return null;
@@ -1678,7 +1811,7 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1678
1811
  return typeof value==='string'||typeof value==='number'||typeof value==='boolean'?String(value):'—';
1679
1812
  }
1680
1813
  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));
1814
+ 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
1815
  }
1683
1816
  function nativeReportScale(key,provider) { return provider==='reddit'?/total_value$/i.test(key)?2:6:provider==='google'&&/Micros$/.test(key)?6:0; }
1684
1817
  function reportBucket(value) {
@@ -1698,9 +1831,11 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1698
1831
  const googleName=googleDimensions?.get(googleEntity);
1699
1832
  const bucket=dimensions.conversionLagBucket??dimensions.conversionOrAdjustmentLagBucket;
1700
1833
  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));
1834
+ const identity=bucket?reportBucket(bucket):googleName??analyticsName??first(names,[row,metrics,dimensions])??first(ids,[row,dimensions]);
1835
+ const name=identity??(provider==='google'?'Report':provider==='meta'?'Reported metrics':'Result '+(index+1));
1702
1836
  const status=first(['entity_status','status'],[row]);
1703
1837
  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'];
1838
+ if(provider==='meta')dimensionKeys.push(...metaBreakdownKeys(payload));
1704
1839
  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
1840
  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
1841
  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 +1851,7 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1716
1851
  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
1852
  fields.sort((a,b)=>priority(a[0])-priority(b[0]));
1718
1853
  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)};
1854
+ 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
1855
  }
1721
1856
  function nativeChartRecord(record) {
1722
1857
  if(!record)return {name:'Unavailable row',context:[],fields:[]};
@@ -1725,9 +1860,9 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1725
1860
  const ratio=nativeReportRatio(key,record.provider);
1726
1861
  const value=record.provider==='spotify'&&String(raw)==='-5'?null:reportNumber(monetary?scaled:raw);
1727
1862
  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'):''};
1863
+ const shortMoney=monetary&&['google','meta'].includes(record.provider);
1864
+ const shortDisplay=shortMoney&&scaled!==null?reportAmount(scaled,record.currency):undefined;
1865
+ 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
1866
  });
1732
1867
  const low=record.native.lowImpressionShare,high=record.native.highImpressionShare;
1733
1868
  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 +1885,27 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1750
1885
  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
1886
  const missingGoals=arr(data.not_returned_goal_ids).filter(id=>!arr(data.errors).some(error=>error?.goal_id===id&&error?.error_code));
1752
1887
  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);
1888
+ 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
1889
  const pageArgs=['ga4_report','gsc_search_analytics'].includes(meta.tool)?readPageArgs(meta,'data-report-next'):null;
1755
1890
  const points=records.map(nativeChartRecord);
1756
- const table=provider==='google'&&!delay&&entries.length?gaqlReportTable(records,points):null;
1891
+ let presentation;
1892
+ if(entries.length && provider==='meta') presentation=metaInsightsReport(records,points,payload);
1893
+ if(entries.length && provider==='google' && !delay) presentation=gaqlReportTable(records,points);
1894
+ if(!presentation && records.length>1 && records.every(row=>row&&!workflowText(row.identity)) &&
1895
+ new Set(records.map(row=>JSON.stringify([row.context,row.date,row.currency]))).size===1) {
1896
+ presentation={html:workflowNote('These rows have no distinguishing labels. Include an entity name or a breakdown to compare them.'), detailRows:true};
1897
+ }
1757
1898
  const entity=records[0]?.gaqlEntity;
1758
1899
  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});
1900
+ 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
1901
  const analytics=['ga4','gsc'].includes(provider),range=payload?.date_range;
1761
1902
  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();
1903
+ const subject=presentation?.subject||(analytics?[meta.accountId,period].filter(Boolean).join(' · '):'');
1904
+ const view=presentation||chart;
1905
+ const body=view?.html||'<p class="operation-note">'+missing+'</p>';
1906
+ const showDetailRows=!presentation||presentation.detailRows||provider==='meta'&&entries.length===1;
1907
+ 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'):'');
1908
+ view?.mount?.();
1766
1909
  bindReadPage(meta,pageArgs,'data-report-next','data-report-page-status',value=>Array.isArray(recordPayload(value)?.rows));
1767
1910
  }
1768
1911
  `;
@@ -1817,9 +1960,9 @@ var WORKFLOW_UI = String.raw`
1817
1960
  (status?'<span class="pill '+tone+'">'+esc(status)+'</span>':'')+'</div>'+body+'</'+tag+'>';
1818
1961
  }
1819
1962
 
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>';
1963
+ function workflowHeader(labels,sorted=-1) {
1964
+ return '<thead role="rowgroup"><tr role="row">'+labels.map((label,i)=>
1965
+ '<th role="columnheader" scope="col"'+(i===sorted?' aria-sort="descending"':'')+'>'+esc(label)+'</th>').join('')+'</tr></thead>';
1823
1966
  }
1824
1967
 
1825
1968
  function workflowCell(label,html,heading=false) {
@@ -1828,10 +1971,10 @@ var WORKFLOW_UI = String.raw`
1828
1971
  '<span class="workflow-cell-label" aria-hidden="true" data-label="'+esc(label)+'"></span><span>'+html+'</span></'+tag+'>';
1829
1972
  }
1830
1973
 
1831
- function workflowTable(labels,rows,description) {
1974
+ function workflowTable(labels,rows,description,{compact=false,sorted=-1}={}) {
1832
1975
  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">'+
1976
+ return '<div class="'+(compact?'collection-scroll':'workflow-scroll')+'" role="region" aria-label="'+esc(description)+'" tabindex="0">'+
1977
+ '<table class="workflow-table'+(compact?'':' workflow-stack')+'" role="table">'+workflowHeader(labels,sorted)+'<tbody role="rowgroup">'+
1835
1978
  rows.map(row=>'<tr role="row">'+row.map((value,i)=>workflowCell(labels[i],esc(workflowText(value)||'—'),i===0)).join('')+'</tr>').join('')+
1836
1979
  '</tbody></table></div>';
1837
1980
  }
@@ -2316,6 +2459,23 @@ var REPORT_CHART_SCRIPT = String.raw`
2316
2459
  function reportNumber(value) {
2317
2460
  const decimal=nativeReportDecimal(value);return decimal!==null&&Number.isFinite(Number(decimal))?Number(decimal):null;
2318
2461
  }
2462
+ const reportMoneyFormats = new Map();
2463
+ function reportAmount(amount, currency) {
2464
+ const locale = state.host.locale || 'en', key = locale + '/' + (currency || '');
2465
+ if (!reportMoneyFormats.has(key)) {
2466
+ const digits = currency ? new Intl.NumberFormat(locale, {style:'currency', currency}).resolvedOptions().maximumFractionDigits : 2;
2467
+ reportMoneyFormats.set(key, {
2468
+ format: new Intl.NumberFormat(locale, {minimumFractionDigits:digits, maximumFractionDigits:digits}),
2469
+ unit: 10 ** -digits
2470
+ });
2471
+ }
2472
+ const {format, unit} = reportMoneyFormats.get(key);
2473
+ if (Number(amount) !== 0 && Math.abs(Number(amount)) < unit) {
2474
+ return Number(amount) < 0 ? '>' + format.format(-unit) : '<' + format.format(unit);
2475
+ }
2476
+ return format.format(amount);
2477
+ }
2478
+
2319
2479
  function reportMetricPriority(key) {
2320
2480
  const value=key.replaceAll('_','').toLowerCase();
2321
2481
  const order=['spend','costmicros','costinlocalcurrency','costinusd','conversions','conversion','totalinstalls','installs','purchases','clicks','taps','impressions','searchpopularity1to100','searchpopularityingenre','searchpopularity1to5','overallsuccesscount','successcount'];
@@ -2350,14 +2510,17 @@ var REPORT_CHART_SCRIPT = String.raw`
2350
2510
  return '<section class="report-chart" data-report-chart><div class="report-chart-head"><b>'+esc(title)+'</b>'+(unit?'<span>'+esc(unit)+'</span>':'')+'</div>'+body+(!trend&&model.returned>shown.length?'<p class="report-chart-foot">'+shown.length+' of '+model.returned+' returned rows · all rows in Details</p>':trend&&model.returned>points.length?'<p class="report-chart-foot">'+points.length+' of '+model.returned+' dated observations · all data in Details</p>':'')+'</section>';
2351
2511
  }).join('')+(groups.size>4?'<p class="report-chart-foot">Showing four units. All returned values are in Details.</p>':'');
2352
2512
  return {html,mount:()=>{
2353
- const elements=[...app.querySelectorAll('[data-native-line]')];
2513
+ const elements=[...app.querySelectorAll('[data-native-line]')],widths=new Map();
2354
2514
  const draw=()=>elements.forEach(element=>{
2355
2515
  if(element.isConnected===false)return;
2356
2516
  const model=models[Number(element.dataset.nativeLine)];if(!model)return;
2517
+ const width=Math.max(240,Math.floor(element.getBoundingClientRect?.().width||480));
2518
+ if(widths.get(element)===width)return;
2519
+ widths.set(element,width);
2357
2520
  const series=new Map();for(const point of model.points){const name=point.series||point.name;if(!series.has(name))series.set(name,[]);series.get(name).push(point);}
2358
2521
  const chosen=[...series.entries()].slice(0,3),valid=chosen.flatMap(([,points])=>points).filter(point=>available(point.value));
2359
2522
  if(!valid.length){element.innerHTML='<p class="operation-note">No complete dated values were returned.</p>';return;}
2360
- const width=Math.max(240,Math.floor(element.getBoundingClientRect?.().width||480)),height=178,left=46,right=12,top=12,bottom=30;
2523
+ const height=178,left=46,right=12,top=12,bottom=30;
2361
2524
  const dates=[...new Set(model.points.map(point=>point.date))].sort(),start=Date.parse(dates[0]),end=Date.parse(dates.at(-1)),span=Math.max(86400000,end-start);
2362
2525
  const max=Math.max(1e-100,...valid.map(point=>point.value)),min=Math.min(0,...valid.map(point=>point.value)),range=max-min||1;
2363
2526
  const x=date=>left+(Date.parse(date)-start)/span*(width-left-right),y=value=>top+(max-value)/range*(height-top-bottom);
@@ -2370,7 +2533,7 @@ var REPORT_CHART_SCRIPT = String.raw`
2370
2533
  return '<path d="'+line+'" fill="none" stroke="'+colors[index]+'" stroke-width="2" stroke-dasharray="'+dashes[index]+'"/>'+sorted.filter(point=>available(point.value)).map(point=>'<circle cx="'+x(point.date)+'" cy="'+y(point.value)+'" r="3" fill="'+colors[index]+'" tabindex="0"><title>'+esc(pretty(name)+' · '+point.date+' · '+point.display)+'</title></circle>').join('');
2371
2534
  }).join('');
2372
2535
  const axis=value=>new Intl.NumberFormat(state.host.locale||'en',{notation:Math.abs(value)>=1000?'compact':'standard',maximumFractionDigits:3}).format(value);
2373
- element.innerHTML='<svg viewBox="0 0 '+width+' '+height+'" role="img" aria-label="'+esc(model.label+' over reported dates')+'"><line class="chart-grid" x1="'+left+'" x2="'+(width-right)+'" y1="'+(height-bottom)+'" y2="'+(height-bottom)+'"/><text x="'+(left-8)+'" y="'+(top+4)+'" text-anchor="end">'+esc(axis(max))+'</text><text x="'+(left-8)+'" y="'+(height-bottom)+'" text-anchor="end">'+esc(axis(min))+'</text>'+paths+labels+'</svg>'+(chosen.length>1?'<div class="report-legend">'+chosen.map(([name],index)=>'<span><i style="border-color:'+colors[index]+';border-top-style:'+(index?'dashed':'solid')+'"></i>'+esc(pretty(name))+'</span>').join('')+'</div>':'')+(series.size>3?'<p class="report-chart-foot">3 of '+series.size+' series · all series in Details</p>':'');
2536
+ element.innerHTML='<svg height="'+height+'" viewBox="0 0 '+width+' '+height+'" role="img" aria-label="'+esc(model.label+' over reported dates')+'"><line class="chart-grid" x1="'+left+'" x2="'+(width-right)+'" y1="'+(height-bottom)+'" y2="'+(height-bottom)+'"/><text x="'+(left-8)+'" y="'+(top+4)+'" text-anchor="end">'+esc(axis(max))+'</text><text x="'+(left-8)+'" y="'+(height-bottom)+'" text-anchor="end">'+esc(axis(min))+'</text>'+paths+labels+'</svg>'+(chosen.length>1?'<div class="report-legend">'+chosen.map(([name],index)=>'<span><i style="border-color:'+colors[index]+';border-top-style:'+(index?'dashed':'solid')+'"></i>'+esc(pretty(name))+'</span>').join('')+'</div>':'')+(series.size>3?'<p class="report-chart-foot">3 of '+series.size+' series · all series in Details</p>':'');
2374
2537
  });
2375
2538
  draw();if(typeof ResizeObserver!=='undefined'&&models.some(model=>model.trend)){trendResize=new ResizeObserver(draw);elements.forEach(element=>trendResize.observe(element));}
2376
2539
  }};
@@ -2378,8 +2541,8 @@ var REPORT_CHART_SCRIPT = String.raw`
2378
2541
  `;
2379
2542
 
2380
2543
  // 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";
2544
+ var ADPORT_UI_URI = "ui://adport/insight-card-v41.html";
2545
+ var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-v41.html";
2383
2546
  var ADPORT_UI_DOMAIN = "https://app.adport.dev";
2384
2547
  var ADPORT_UI_RESOURCE_DOMAINS = [
2385
2548
  ADPORT_UI_DOMAIN,
@@ -2715,6 +2878,44 @@ ${NATIVE_REPORT_UI_SCRIPT}
2715
2878
  ${REPORT_CHART_SCRIPT}
2716
2879
  ${INSIGHT_UI_SCRIPT}
2717
2880
  ${TREND_UI_SCRIPT}
2881
+ function isToolResult(value) {
2882
+ return object(value) && (Object.hasOwn(value,'structuredContent') || Array.isArray(value.content) && value.content.every(block=>typeof block?.type==='string'))
2883
+ && Object.keys(value).every(key=>['content','structuredContent','_meta','isError'].includes(key));
2884
+ }
2885
+ function textPayload(content) {
2886
+ const blocks=arr(content).filter(block=>block?.type==='text' && typeof block.text==='string');
2887
+ for (const block of blocks) {
2888
+ try { return JSON.parse(block.text); } catch {}
2889
+ }
2890
+ if (blocks.length===1 && content.length===1) {
2891
+ const text=blocks[0].text, first=text.trimStart()[0];
2892
+ if (first==='{' || first==='[') return {error:'UNREADABLE_TOOL_RESULT',message:'The widget could not read the complete tool response. Check the result in the conversation.'};
2893
+ return {message:text};
2894
+ }
2895
+ }
2896
+ function normalizeToolResult(input,hostMeta) {
2897
+ let value=input, envelopeMeta, isError=false, fromText=false;
2898
+ // A host can forward a complete CallToolResult inside another text block.
2899
+ // Stop at the provider payload, including its own result, content or copy.
2900
+ for (let depth=0;depth<8 && isToolResult(value);depth++) {
2901
+ isError ||= value.isError===true;
2902
+ envelopeMeta ??= value._meta?.adport;
2903
+ fromText=value.structuredContent==null;
2904
+ const next=fromText?textPayload(value.content):value.structuredContent;
2905
+ if (next===undefined) break;
2906
+ value=next;
2907
+ }
2908
+ const data=object(value)?value:{value};
2909
+ const meta=hostMeta ?? (fromText?undefined:data._adport) ?? envelopeMeta;
2910
+ let structuredContent=data;
2911
+ if (meta!==data._adport) {
2912
+ structuredContent={...data};
2913
+ if (meta) structuredContent._adport=meta;
2914
+ else delete structuredContent._adport;
2915
+ }
2916
+ return {structuredContent,...(isError?{isError:true}:{})};
2917
+ }
2918
+ function resultData(result) { return result?.structuredContent ?? {}; }
2718
2919
  async function callTool(tool,parameters,timeoutMs=30000) {
2719
2920
  const requestId=id++;
2720
2921
  return new Promise((resolve,reject)=>{
@@ -2725,7 +2926,7 @@ ${TREND_UI_SCRIPT}
2725
2926
  const request=pendingRequests.get(requestId);if (request) {clearTimeout(request.timer);pendingRequests.delete(requestId);request.resolve(result);}
2726
2927
  },error=>{const request=pendingRequests.get(requestId);if (request) {clearTimeout(request.timer);pendingRequests.delete(requestId);request.reject(error);}});
2727
2928
  } else send({jsonrpc:'2.0',id:requestId,method:'tools/call',params:{name:tool,arguments:parameters}});
2728
- });
2929
+ }).then(result=>result==null?result:normalizeToolResult(result));
2729
2930
  }
2730
2931
  ${MEDIA_UPLOAD_UI}
2731
2932
  ${MEDIA_LIBRARY_UI}
@@ -2733,11 +2934,27 @@ ${CREATIVE_UI_SCRIPT}
2733
2934
  ${PROVIDER_GALLERY_UI}
2734
2935
  ${WORKFLOW_UI}
2735
2936
  ${PLANNING_UI}
2937
+ function readPresentation(data) {
2938
+ // Some hosts forward only the public text result. These views need no
2939
+ // account scope, pagination arguments or write capability to display it.
2940
+ const name=state.host.toolInfo?.tool?.name, tool=typeof name==='string'?name.split('__').pop():undefined;
2941
+ if ((!tool || tool==='meta_list_ads') && Array.isArray(data.ads) && Array.isArray(data.creatives) &&
2942
+ data.creatives.every(item=>item?.provider==='meta' && typeof item.id==='string' && typeof item.account_id==='string')) {
2943
+ return {tool:'meta_list_ads',view:'creatives',provider:'meta'};
2944
+ }
2945
+ const rows=data.result?.rows;
2946
+ const appleMetrics=metrics=>object(metrics?.localSpend) && (Object.hasOwn(metrics,'taps') || Object.hasOwn(metrics,'totalInstalls'));
2947
+ if (Array.isArray(rows) && (tool==='apple_report' || !tool && (appleMetrics(data.result.summary?.grandTotal) ||
2948
+ rows.some(row=>appleMetrics(row?.totalMetrics) || arr(row?.granularMetrics).some(appleMetrics))))) {
2949
+ return {tool:'apple_report',view:'records',provider:'apple'};
2950
+ }
2951
+ return {};
2952
+ }
2736
2953
  function render(result) {
2737
2954
  cancelHold();clearTimeout(expiryTimer);trendResize?.disconnect();
2738
2955
  let data=resultData(result);
2739
2956
  if (!object(data)) data={value:data};
2740
- const meta = data._adport || {};
2957
+ const meta = data._adport || readPresentation(data);
2741
2958
  recordPages=null;
2742
2959
  if(providerGallery && meta.view!=='creatives' && (!providerGallery.review || meta.view!=='operation' || meta.tool!==providerGallery.review.tool || meta.accountId!==providerGallery.meta.accountId || meta.context?.project_id!==providerGallery.meta.context?.project_id)) providerGallery=null;
2743
2960
  syntheticResult = data.data_source === 'synthetic';
@@ -2776,12 +2993,13 @@ ${PLANNING_UI}
2776
2993
  hostResults.add(fingerprint);
2777
2994
  if (hostResults.size>16) hostResults.delete(hostResults.values().next().value);
2778
2995
  }
2779
- function acceptResult(result,local=false) {
2780
- if (!result || typeof result !== 'object') return;
2996
+ function acceptResult(input,local=false,hostMeta) {
2997
+ if (input==null) return;
2998
+ const result=normalizeToolResult(input,hostMeta);
2781
2999
  const incoming=resultData(result);
2782
3000
  if(!local && (providerGalleryIgnoreEcho(incoming) || mediaLibraryIgnoreEcho(incoming) || recordPagesIgnoreEcho(incoming) || readPageIgnoreEcho(incoming) || distributionIgnoreEcho(incoming))) return;
2783
- if(!local && (app.querySelector('[data-media-gallery]') && uploads.items.length>0 && ['media_prepare_upload','media_finalize_upload','media_get'].includes(incoming?._adport?.tool || result._meta?.adport?.tool) || mediaLibrary?.loading && incoming?._adport?.tool==='media_list' && mediaLibraryProject(incoming,incoming._adport)===mediaLibrary.project)) return;
2784
- const fingerprint=JSON.stringify(incoming);
3001
+ if(!local && (app.querySelector('[data-media-gallery]') && uploads.items.length>0 && ['media_prepare_upload','media_finalize_upload','media_get'].includes(incoming?._adport?.tool) || mediaLibrary?.loading && incoming?._adport?.tool==='media_list' && mediaLibraryProject(incoming,incoming._adport)===mediaLibrary.project)) return;
3002
+ const fingerprint=(result.isError?'error:':'')+JSON.stringify(incoming);
2785
3003
  // Host state updates can echo an old tool result after a local edit/apply.
2786
3004
  if (!local && state.hasLocalResult && hostResults.has(fingerprint)) return;
2787
3005
  if (local) state.hasLocalResult=true;
@@ -2798,8 +3016,7 @@ ${PLANNING_UI}
2798
3016
  if (!globals) return;
2799
3017
  const metadata = globals.toolResponseMetadata;
2800
3018
  const envelope = metadata?.mcp_tool_result || metadata?.call_tool_result;
2801
- if (envelope && typeof envelope === 'object') return acceptResult(envelope);
2802
- if (globals.toolOutput && typeof globals.toolOutput === 'object') acceptResult({structuredContent:{...globals.toolOutput,...(metadata?.adport?{_adport:metadata.adport}:{})}});
3019
+ acceptResult(object(envelope)?envelope:globals.toolOutput,false,metadata?.adport);
2803
3020
  }
2804
3021
  // Some hosts mount an error result's resource but never relay its payload.
2805
3022
  // This is a delivery fallback, not a claim about tool execution or success.
@@ -2833,12 +3050,12 @@ ${PLANNING_UI}
2833
3050
  if (message.method === 'ui/notifications/tool-result') acceptResult(message.params);
2834
3051
  if (message.method === 'ui/notifications/tool-cancelled') acceptResult({structuredContent:{cancelled:true,message:message.params?.reason}});
2835
3052
  if (message.method === 'ui/notifications/host-context-changed') {
2836
- const previousLocale = state.host.locale;
3053
+ const previousHost = state.host;
2837
3054
  state.host = {...state.host,...message.params};
2838
3055
  document.documentElement.dataset.theme = state.host.theme || '';
2839
3056
  // Size/theme updates must not rebuild the DOM: opening Details changes
2840
3057
  // the iframe height, which some hosts echo back as a context update.
2841
- if (state.result && previousLocale !== state.host.locale) {
3058
+ if (state.result && (previousHost.locale!==state.host.locale || !resultData(state.result)._adport && previousHost.toolInfo?.tool?.name!==state.host.toolInfo?.tool?.name)) {
2842
3059
  const expanded = app.querySelector('details')?.open || false;
2843
3060
  render(state.result);
2844
3061
  const details = app.querySelector('details');
@@ -2858,7 +3075,7 @@ ${PLANNING_UI}
2858
3075
 
2859
3076
  // src/index.ts
2860
3077
  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"];
3078
+ var ADPORT_UI_RESOURCE_URIS = [ADPORT_UI_URI, "ui://adport/insight-card-v40.html", "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-v40.html", "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
3079
  var DEFAULT_MCP_ICONS = [{
2863
3080
  src: "https://app.adport.dev/icon.svg?brand=orange-dot-v2",
2864
3081
  mimeType: "image/svg+xml",
@@ -3077,4 +3294,4 @@ export {
3077
3294
  createMcpServer,
3078
3295
  runStdioServer
3079
3296
  };
3080
- //# sourceMappingURL=chunk-TNQOM6VM.js.map
3297
+ //# sourceMappingURL=chunk-NWNTOUFX.js.map