@haoxdong/marquee-cli 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire}from'node:module';const require=createRequire(import.meta.url);
3
+ var jm=Object.create;var Li=Object.defineProperty;var Vm=Object.getOwnPropertyDescriptor;var Gm=Object.getOwnPropertyNames;var Bm=Object.getPrototypeOf,Hm=Object.prototype.hasOwnProperty;var he=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var re=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Y=(e,t)=>{for(var n in t)Li(e,n,{get:t[n],enumerable:!0})},zm=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Gm(t))!Hm.call(e,i)&&i!==n&&Li(e,i,{get:()=>t[i],enumerable:!(r=Vm(t,i))||r.enumerable});return e};var Ba=(e,t,n)=>(n=e!=null?jm(Bm(e)):{},zm(t||!e||!e.__esModule?Li(n,"default",{value:e,enumerable:!0}):n,e));var T,ge=v(()=>{"use strict";T=class extends Error{constructor(n,r,i){super(r);this.code=n;this.details=i}name="MarqueeError";toJSON(){return{code:this.code,message:this.message,details:this.details}}}});function qi(e){return"steps"in e}var Fi=v(()=>{"use strict"});function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Q=v(()=>{"use strict"});function kt(e,t){if(!e)throw new Error(`Unsupported asset search response shape: ${t}; record a Scenario before accepting this fallback.`)}function He(e,t){if(e!=null)return kt(typeof e=="string"&&e.length>0,`${t} is not a non-empty string`),e}function Ja(e,t,n){let r=e.identifiers;if(!Array.isArray(r))return;let i=r.some(o=>(kt(m(o),"identifier is not an object"),Ni(o.type,"identifier type").trim().toUpperCase()===n));kt(!i,`${t} identifiers fallback`)}function Ui(e){let t=He(m(e.xref)?e.xref.ticker:void 0,"xref.ticker")??He(e.ticker,"ticker");return t!==void 0?t:(Ja(e,"ticker","TKR"),"")}function ji(e){let t=He(m(e.xref)?e.xref.bbid:void 0,"xref.bbid")??He(e.bbid,"bbid");return t!==void 0?t:(Ja(e,"bbid","BID"),"")}function Ya(e){return kt(m(e),"missing response object"),kt(Array.isArray(e.results),"missing results array"),e.results}function Ni(e,t){return kt(typeof e=="string"&&e.length>0,`missing ${t}`),e}function Ka(e){return{type:"asset",id:Ni(e.id,"id"),title:Ni(e.name,"name"),assetClass:He(e.assetClass,"assetClass"),assetType:He(e.type,"type"),ticker:He(Ui(e)||void 0,"ticker"),bbid:He(ji(e)||void 0,"bbid")}}var Vi=v(()=>{"use strict";Q()});var Qa={};Y(Qa,{default:()=>oh});function th(e){return e.trim().replace(Xm," ").replace(/\s+/g," ").replace(eh,(r,i,o,s="")=>`${i.toUpperCase()}/${o.toUpperCase()}${s}`).toUpperCase()}function nh(e){let t=e;return Array.isArray(t.assets)?t.assets:[]}function rh(e){let t=e.split(/\s+/),n=t.length>=2?t[t.length-1].toUpperCase():"";return Zm[n]}var Zm,Xm,eh,ih,oh,Za=v(()=>{"use strict";Vi();Zm={UW:"NASD",UQ:"NASD",UR:"NASD",UN:"NYSE",US:"NYSE",UF:"ARCA",UP:"ARCA",LN:"LSE",LI:"LSE",FP:"EPA",GR:"XETR",GY:"XETR",HK:"HKEX",JP:"TSE",JT:"TSE",AU:"ASX",CN:"TSX",SS:"SSE",SZ:"SZSE",SW:"SWX",IM:"BIT",SM:"BME",NA:"ENXT"},Xm=/[&?]/g,eh=/^([A-Za-z]{1,8})\.([A-Za-z])(\s+.*)?$/;ih={name:"asset.resolve",columns:["id","name"],request:({query:e})=>({method:"GET",path:"/v1/plots/entities",query:{ids:th(e),type:"Asset"},hedgeDelaysMs:[500,1250]}),transform:({raw:e})=>{let t=nh(e);if(t.length===0)throw new Error("No asset found");let n=t[0];if(!n||n.id==null)throw new Error("missing asset id in asset resolve response");let r=Ui(n),i=ji(n),o=typeof n.exchange=="string"?n.exchange:rh(i);return{id:String(n.id),name:String(n.name||n.short_name||n.id||""),...typeof n.assetClass=="string"?{assetClass:n.assetClass}:{},...typeof n.type=="string"?{type:n.type}:{},...r?{ticker:r}:{},...i?{bbid:i}:{},...o?{exchange:o}:{},...typeof n.currency=="string"?{currency:n.currency}:{}}}},oh=ih});var Xa={};Y(Xa,{default:()=>ah});var sh,ah,eu=v(()=>{"use strict";Vi();sh={name:"asset.search",request:({query:e,limit:t})=>({method:"GET",path:"/v1/search/assets",query:{qs:e,limit:t??10}}),transform:({raw:e})=>Ya(e).map(Ka).filter(t=>t.id.length>0)},ah=sh});var uu={};Y(uu,{default:()=>qh});function ce(e,t){if(!e)throw new T("adapter",`Unsupported content feed response shape: ${t}; record a Scenario before accepting this fallback.`)}function ph(e){let t=e.id;return ce(typeof t=="string"&&t.trim().length>0,"id is required"),t}function gh(e){let t=e.metadata?.title;return ce(typeof t=="string"&&t.trim().length>0,"metadata.title is required"),t}function mh(e){let t=e.metadata?.publishedTime;if(typeof t=="string"&&t.trim().length>0)return t;let n=e.metadata?.publicationDate;return ce(typeof n=="string"&&n.trim().length>0,"metadata.publishedTime or metadata.publicationDate is required"),n}function hh(e){let t=e.metadata?.pagePath;return ce(typeof t=="string"&&t.startsWith("/"),"metadata.pagePath must be a root-relative path"),`https://marquee.gs.com${t}`}function yh(e){let t=e.metadata?.summary;return ce(typeof t=="string"&&t.trim().length>0,"metadata.summary is required"),t}function er(e){if(e)return/^https?:\/\//i.test(e)?e:`https://marquee.gs.com${e.startsWith("/")?"":"/"}${e}`}function tu(e){return e.documentSource==="RELAY_DOCUMENT_LEGACY"}function Gi(e){return e.documentSource===void 0||e.documentSource==="sec_div"}function wh(e){return e.replace(/\s*&\s*/g," and ").replace(/\s+/g," ").trim()}function bh(e){let t=e.authors;ce(t!=null,"authors must be a non-empty array"),ce(Array.isArray(t),"authors is not an array"),ce(t.length>0,"authors must be a non-empty array");let n=[],r;for(let i of t)ce(i&&typeof i=="object"&&typeof i.displayName=="string"&&i.displayName.trim().length>0,"authors[].displayName is required"),n.push(i.displayName),!r&&typeof i.division=="string"&&i.division.trim().length>0&&(r=wh(i.division));return ce(r,"authors[].division is required"),{authors:n,source:r}}function Rh(e){let t=e.components;return ce(t!=null,"components must be a non-empty array"),ce(Array.isArray(t),"components is not an array"),ce(t.length>0,"components must be a non-empty array"),t}function Hi(e,t=[]){if(Array.isArray(e)){for(let r of e)Hi(r,t);return t}if(!m(e))return t;let n=e.properties;m(n)&&typeof n.content=="string"&&n.content.length>0&&t.push(n.content);for(let r of Object.values(e))Hi(r,t);return t}function kh(e){let t=e.replace(/\s+/g,"");ce(t.length>0&&t.length%4===0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t),"components[].properties.content must be base64 encoded");let n=Buffer.from(t,"base64").toString("utf8");return ce(Buffer.from(n,"utf8").toString("base64")===t,"components[].properties.content must be base64 encoded"),n}function iu(e){return e.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;|&apos;/g,"'").replace(/&#x([0-9a-f]+);/gi,(t,n)=>String.fromCodePoint(Number.parseInt(n,16))).replace(/&#(\d+);/g,(t,n)=>String.fromCodePoint(Number.parseInt(n,10)))}function ou(e){return iu(e.replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\b[^>]*>/gi,`
4
+ `).replace(/<\s*li\b[^>]*>/gi,`
5
+ - `).replace(/<[^>]+>/g," ").replace(/\r/g,"")).split(`
6
+ `).map(t=>t.replace(/\s+/g," ").trim()).filter(Boolean).join(`
7
+ `)}function _e(e,t){if(!e)throw new T("adapter",`Unsupported GIR HTML response shape: ${t}; record a Scenario before accepting this fallback.`)}function su(e,t){try{return JSON.parse(`"${e}"`)}catch{_e(!1,t)}}function Ah(e,t){for(let n=t;n<e.length;n+=1){if(e[n]!=='"')continue;let r=0;for(let i=n-1;i>=t&&e[i]==="\\";i-=1)r+=1;if(r%2===0)return n}return-1}function Sh(e){let t='self.__next_f.push([1,"',n=[],r=0;for(;r<e.length;){let i=e.indexOf(t,r);if(i<0)break;let o=i+t.length,s=Ah(e,o);_e(s>=0,"Next.js metadata stream is truncated");let a=su(e.slice(o,s),"Next.js metadata payload is invalid");_e(a,"Next.js metadata payload is invalid"),n.push(a),r=s+1}return n}function Ch(e){let t=e?.replace(/\s+/g," ").trim();if(!(!t||t==="$undefined"))return t}function zi(e,t){return Ch(iu(su(e,t)))}function Eh(e,t){let r=new RegExp(`"${t}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`).exec(e);if(r)return zi(r[1],`${t} is not valid JSON text`)}function vh(e,t,n,r,i,o){let s=fh[t.toLowerCase()];if(!s)return;let a=Number.parseInt(e,10),u=Number.parseInt(r,10);return o.toUpperCase()==="AM"?u===12&&(u=0):u!==12&&(u+=12),`${n}-${s}-${String(a).padStart(2,"0")} ${String(u).padStart(2,"0")}:${i}`}function xh(e){let t=/\b(\d{1,2}) ([A-Z][a-z]+) (\d{4}) \| (\d{1,2}):(\d{2})(AM|PM) [A-Z]{2,5} \| ([^"\n<]+)/.exec(e);_e(t,"publication byline is required");let n=vh(t[1],t[2],t[3],t[4],t[5],t[6]);_e(n,"publication byline date is invalid");let r=zi(t[7],"publication byline source is not valid JSON text");return _e(r,"publication byline source is required"),{publicationDate:n,source:r}}function au(e){return!!e&&/^\+\d[\d().\s-]+$/.test(e)}function Ih(e){return!!e&&e.length<=100&&/[A-Za-z]/.test(e)&&!/[.@]/.test(e)&&!au(e)}function Dh(e){let t=Array.from(e.matchAll(/"children"\s*:\s*"((?:\\.|[^"\\])*)"/g)).map(r=>zi(r[1],"author metadata is not valid JSON text")).filter(r=>!!r),n=[];for(let r=0;r<t.length;r+=1){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t[r]))continue;let i=t[r-1],o=t[r-2];!au(i)||!Ih(o)||n.push(o)}return _e(n.length>0,"author metadata is required"),n}function Th(e){let t=Sh(e);_e(t.length>0,"Next.js metadata stream is required");let n=t.join(`
8
+ `),r=Eh(n,"distributionHeadline");_e(r,"distributionHeadline is required");let i=xh(n),o=Dh(n);return{title:r,...i,authors:o}}function Ph(e){let t=Hi(Rh(e)).map(n=>ou(kh(n))).filter(n=>n.length>0).join(`
9
+ `);return ce(t.length>0,"components must expose article body content"),t}function _h(e){try{let t=new URL(e);if(t.origin==="https://marquee.gs.com")return`${t.pathname}${t.search}`}catch{}return e}function Bi(e){if(!e)return;let t=_h(e.trim());if(!t)return;let r=/[?#]/.exec(t)?.index??t.length,i=t.slice(0,r),o=t.slice(r);if(/\.html$/i.test(i))return t;if(/\.pdf$/i.test(i))return`${i.replace(/\.pdf$/i,".html")}${o}`}function nu(e){return Bi(e.path)??Bi(e.url)??Bi(e.downloadPath)}function ru(e){return/\/\s*>$/.test(e)||/^<\s*(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)\b/i.test(e)}function $h(e){return/\sdata-testid\s*=\s*(?:"Chapter"|'Chapter'|Chapter)(?:\s|>|\/)/i.test(e)}function Oh(e){let t=[],n=/<\/?([a-zA-Z][\w:-]*)\b[^>]*>/g,r;for(;(r=n.exec(e))!==null;){let i=r[0];if(i.startsWith("</")||!$h(i)||ru(i))continue;let o=r[1].toLowerCase(),s=1,a=-1,u=n.lastIndex;for(;(r=n.exec(e))!==null;){let l=r[0];if(r[1].toLowerCase()===o)if(l.startsWith("</")){if(s-=1,s===0){a=r.index;break}}else ru(l)||(s+=1)}a>=u&&t.push(e.slice(u,a))}return t}function Mh(e){let t=e.split(`
10
+ `).map(o=>o.trim()).filter(Boolean),n=t.findIndex(o=>/^Resource Corner$/i.test(o)),i=(n>=0?t.slice(0,n):t).join(`
11
+ `).trim();return i.length>0?i:void 0}function Wh(e,t){if(_e(typeof e=="string"&&e.trim().length>0,"GIR HTML response must be non-empty text"),/<title>\s*GoldmanSachs\s*-\s*Login\s*<\/title>/i.test(e))throw new T("adapter",dh,{path:t});let n=Th(e),r=Oh(e).map(o=>ou(o.replace(/<button[\s\S]*?<\/button>/gi," "))).filter(o=>o.length>0),i=Mh(r.join(`
12
+ `));if(!i)throw new T("adapter",ch,{path:t});return{...n,body:i}}var uh,dh,ch,lh,fh,Lh,qh,du=v(()=>{"use strict";ge();Q();uh="No GIR HTML article path is available. Open the source in a browser for the full document.",dh="GIR HTML returned a login page. Run: marquee auth login.",ch="GIR HTML did not expose Chapter body containers. Open the source in a browser for the full document.",lh="No body endpoint is available for this content source. Open the source in a browser for the full document.",fh={january:"01",february:"02",march:"03",april:"04",may:"05",june:"06",july:"07",august:"08",september:"09",october:"10",november:"11",december:"12"};Lh={name:"content.get",columns:["type","id","title","publicationDate","authors","source"],steps:[{name:"body",request:e=>{if(tu(e)){let t=nu(e);return t?{method:"GET",path:t,headers:{Accept:"text/html"},responseType:"text",acceptHtml:!0}:null}return Gi(e)?{method:"GET",path:`/v1/content/feed/article/${encodeURIComponent(e.id)}`}:null}}],formatError:(e,t,n)=>Gi(e)&&t===400?"This may be a GIR research document. Use `content research <uuid> --date YYYY-MM-DD` instead.":n,transform:async({steps:e,args:t})=>{if(tu(t)){let f=nu(t);if(f){let g=Wh(e.body,f);return{id:t.id,type:"article",title:g.title,publicationDate:g.publicationDate,authors:g.authors,source:g.source,...t.quote?{quote:t.quote}:{},...t.synopsis?{synopsis:t.synopsis}:{},body:g.body,url:er(f)}}let p=er(t.path??t.url);return{id:t.id,type:"article",title:t.title??"",...t.publicationDate?{publicationDate:t.publicationDate}:{},...t.authors&&t.authors.length>0?{authors:t.authors}:{},...t.source?{source:t.source}:{},...t.quote?{quote:t.quote}:{},...t.synopsis?{synopsis:t.synopsis}:{},bodyUnavailableReason:uh,...p?{url:p}:{}}}if(!Gi(t))return{id:t.id,type:"article",title:t.title??"",...t.publicationDate?{publicationDate:t.publicationDate}:{},...t.authors&&t.authors.length>0?{authors:t.authors}:{},...t.source?{source:t.source}:{},...t.quote?{quote:t.quote}:{},...t.synopsis?{synopsis:t.synopsis}:{},bodyUnavailableReason:lh,...er(t.url??t.path)?{url:er(t.url??t.path)}:{}};let n=e.body,r=ph(n),i=gh(n),o=mh(n),s=hh(n),{authors:a,source:u}=bh(n),l=yh(n),c=Ph(n);return{id:r,type:"article",title:i,publicationDate:o,authors:a,source:u,...t.quote?{quote:t.quote}:{},synopsis:l,body:c,url:s}}},qh=Lh});var bu={};Y(bu,{default:()=>yy});import Fh from"node:assert/strict";function ae(e,t){Fh(e,`Unsupported content search response shape: ${t}; record a Scenario before accepting this fallback.`)}function be(e,t){return ae(typeof e=="string",`${t} is required`),ae(e.trim().length>0,`${t} is required`),e}function Gh(e,t){if(e!=null)return be(e,t)}function nr(e,t){return ae(typeof e=="number",`${t} is not a number`),ae(Number.isFinite(e),`${t} is not a number`),e}function mu(e,t){return ae(typeof e=="boolean",`${t} is not a boolean`),e}function Bh(e){return ae(Array.isArray(e.documents),"documents is not an array"),e.documents}function Hh(e){return ae(Array.isArray(e.facetList),"facetList is not an array"),e.facetList}function zh(e){return`all EQ \${(${e})}$`}function Ki(e){return e==="relevance"?"relevance":"time"}function Yi(e){let t=e?.trim();if(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))throw new Error(`invalid date "${t}"; expected YYYY-MM-DD`);return t}}function Jh(e){let t=new Intl.DateTimeFormat("en-US",{timeZone:Ji,timeZoneName:"shortOffset"}).formatToParts(e).find(s=>s.type==="timeZoneName")?.value,n=/^GMT(?:(?<sign>[+-])(?<hours>\d{1,2})(?::(?<minutes>\d{2}))?)?$/.exec(t??"");if(!n?.groups)throw new Error(`could not determine ${Ji} offset`);let r=Number(n.groups.hours??"0"),i=Number(n.groups.minutes??"0"),o=r*60+i;return n.groups.sign==="-"?-o:o}function tr(e,t=0){let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)throw new Error(`invalid date "${e}"; expected YYYY-MM-DD`);let r=Number(n[1]),i=Number(n[2])-1,o=Number(n[3]),s=new Date(Date.UTC(r,i,o));if(s.getUTCFullYear()!==r||s.getUTCMonth()!==i||s.getUTCDate()!==o)throw new Error(`invalid date "${e}"; expected YYYY-MM-DD`);let a=new Date(Date.UTC(r,i,o+t)),u=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate());for(let l=0;l<3;l+=1){let c=Jh(new Date(u)),d=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate())-c*6e4;if(d===u)break;u=d}return new Date(u).toISOString().slice(0,19)}function hu(e){return e.trim().toLowerCase()}function Qi(e){return Array.isArray(e)?e.flatMap(t=>{let n=hu(t.field),r=t.value.trim();if(!n||!r)return[];if(!dn[n])throw new Error(`unknown content search filter field "${t.field}"`);return[{field:n,value:r}]}):[]}function Zi(e){return Array.isArray(e)?e.flatMap(t=>{let n=hu(t.field),r=t.guid.trim(),i=t.name.trim();if(!n||!r||!i)return[];if(!dn[n])throw new Error(`unknown content search facet field "${t.field}"`);return[{field:n,guid:r,name:i}]}):[]}function Yh(e,t){return`${dn[e]} EQ \${(${t})}$`}function Kh(e){let t=[zh(e.query)];for(let i of Qi(e.select))t.push(Yh(i.field,i.value));let n=Yi(e.from),r=Yi(e.to);return n&&r?t.push(`publicationDateTime IN [${tr(n)},${tr(r,1)}]`):n?t.push(`publicationDateTime GEQ ${tr(n)}`):r&&t.push(`publicationDateTime LEQ ${tr(r,1)}`),t.join(" AND ")}function yu(e){return`(${Kh(e)})`}function Qh(e){return{filter:yu(e),facets:wu(e),sort:Ki(e.sort),page:typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?e.page:jh,size:pu,language:gu,limitTo:'[""]',applyHighlighting:!0}}function cu(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function wu(e){let t=Zi(e.appliedFacets);if(t.length===0)return"()";let n=new Map;for(let i of t)n.set(i.field,[...n.get(i.field)??[],i.guid]);return`(${[...n.entries()].map(([i,o])=>o.length===1?`${dn[i]} CTS_ALL [${cu(o[0])}]`:`(${o.map(s=>`${dn[i]} CTS_ALL [${cu(s)}]`).join(" OR ")})`).join(" AND ")})`}function Zh(e){let t=yu(e),n=wu(e),r=Ki(e.sort);return["https://marquee.gs.com/content/research/site/search.html",`?filter=${encodeURIComponent(t)}`,...n!=="()"?[`&facets=${encodeURIComponent(n)}`]:[],`&sort=${r}`,`&language=${encodeURIComponent(gu)}`].join("")}function Xh(e,t){let n=new Map;for(let r of[...Qi(e).map(i=>({field:i.field,value:i.value})),...Zi(t).map(i=>({field:i.field,value:i.name}))]){let i=n.get(r.field)??new Set;i.add(r.value.trim().toLowerCase()),n.set(r.field,i)}return n}function ey(e,t,n){return e.get(t)?.has(n.trim().toLowerCase())===!0}function lu(e){return Yi(e)}function ty(e){return Qi(e.select)}function ny(e){ae(Array.isArray(e),"documents[].authors is not an array");let t=e.map(n=>be(n,"documents[].authors[]"));return ae(t.length>0,"documents[].authors is empty"),t}function ry(e){let t=new Intl.DateTimeFormat("en-US",{timeZone:Ji,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e),n=r=>t.find(i=>i.type===r)?.value??"";return`${n("year")}-${n("month")}-${n("day")} ${n("hour")}:${n("minute")}`}function iy(e){let t=new Date(e);return ae(!Number.isNaN(t.getTime()),"documents[].publicationDateTime is invalid"),ry(t)}function oy(e){return e.replace(/<\/?b>/gi,"").replace(/<[^>]+>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/\s+/g," ").trim()}function fu(e,t){if(e==null)return;ae(typeof e=="string",`${t} is not a string`);let n=oy(e);return n.length>0?n:void 0}function sy(e){return e.startsWith("http://")||e.startsWith("https://")?e:`https://marquee.gs.com${e.startsWith("/")?"":"/"}${e}`}function ay(e){let t=nr(e,"totalRecords");return ae(t>=0,"totalRecords is not a non-negative number"),t}function uy(e){let t=nr(e,"page");return ae(t>0,"page is not a positive number"),t}function dy(e){return pu}function cy(e){let t=be(e.id,"documents[].id"),n=be(e.distributionHeadline,"documents[].distributionHeadline"),r=iy(nr(e.publicationDateTime,"documents[].publicationDateTime")),i=ny(e.authors),o=be(e.sourceDisplayName,"documents[].sourceDisplayName"),s=be(e.source,"documents[].source"),a=fu(e.synopsis,"documents[].synopsis"),u=fu(e.highlight,"documents[].highlight"),l=be(e.path,"documents[].path"),c=Gh(e.downloadPath,"documents[].downloadPath");return{id:t,type:"article",title:n,publicationDate:r,authors:i,source:o,documentSource:s,...a?{synopsis:a}:{},...u?{snippet:u}:{},path:l,...c?{downloadPath:c}:{},url:sy(l)}}function ly(e){let t=[];for(let n of Bh(e))t.push(cy(n));return t}function fy(e){let t=be(e,"facetList[].label").trim().toLowerCase(),n=Vh[t];return ae(n,`unknown facet label "${e}"`),n}function py(e,t,n){return ae(Array.isArray(e),"facetList[].values is not an array"),e.map(r=>{let i=be(r.id,"facetList[].values[].id"),o=be(r.guid,"facetList[].values[].guid"),s=be(r.name,"facetList[].values[].name"),a=nr(r.count,"facetList[].values[].count");ae(a>=0,"facetList[].values[].count is negative");let u=mu(r.selected,"facetList[].values[].selected")||ey(t,n,s);return{id:i,guid:o,name:s,count:a,selected:u}})}function gy(e,t,n){let r=Xh(t,n),i=[];for(let o of Hh(e)){let s=fy(o.label),a=py(o.values,r,s);ae(a.length>0,"facetList[].values is empty"),i.push({field:s,label:be(o.label,"facetList[].label"),selected:mu(o.selected,"facetList[].selected")||a.some(u=>u.selected),values:a})}return i}function my(e=process.env){return!!(e.MARQUEE_BROKER_URL?.trim()&&e.MARQUEEBOT_ACCOUNT_ID?.trim()&&e.MARQUEE_OWNER_SESSION_ID?.trim()&&e.MARQUEE_BROKER_INVOCATION_TOKEN?.trim())}var Nh,Uh,jh,pu,gu,Ji,dn,Vh,hy,yy,Ru=v(()=>{"use strict";Nh="/research/search/reports/advanced-search",Uh="application/prs.gir-search-service.v2+json;charset=UTF-8",jh=1,pu=10,gu='["en"]',Ji="America/New_York",dn={author:"authors",source:"sources",type:"report_types",region:"regions_and_countries",subject:"subjects_and_notability",company:"companies",industry:"industries",publication:"publications",subsource:"disciplines_and_assets",action:"actions",focus:"focus"},Vh={sources:"source","sub-sources/assets":"subsource","report types":"type",publications:"publication",authors:"author","regions/countries":"region",subjects:"subject",companies:"company",industries:"industry",actions:"action",focus:"focus"};hy={name:"content.search",columns:["title","publicationDate","source","authors"],steps:[{name:"search",request:e=>({method:"POST",path:Nh,headers:{Accept:Uh,"Content-Type":"application/json;charset=UTF-8"},body:Qh(e)})}],transform:({steps:e,args:t})=>{let n=e.search,r=dy(t.limit),i=lu(t.from),o=lu(t.to);return{type:"content-search",query:t.query,link:Zh(t),totalRecords:ay(n.totalRecords),limit:r,page:uy(n.page),sort:Ki(t.sort),...i?{from:i}:{},...o?{to:o}:{},appliedFilters:ty(t),appliedFacets:Zi(t.appliedFacets),results:ly(n).slice(0,r),facets:gy(n,t.select,t.appliedFacets)}},formatError:(e,t,n)=>{if(!my()&&(t===401||/session/i.test(n)||/not authenticated/i.test(n)))return"Research session expired or missing. Run: marquee auth login"}},yy=hy});var ku={};Y(ku,{default:()=>Ry});var wy,by,Ry,Au=v(()=>{"use strict";wy={UW:"NASD",UQ:"NASD",UR:"NASD",UN:"NYSE",US:"NYSE",UF:"ARCA",UP:"ARCA",LN:"LSE",LI:"LSE",FP:"EPA",GR:"XETR",GY:"XETR",HK:"HKEX",JP:"TSE",JT:"TSE",AU:"ASX",CN:"TSX",SS:"SSE",SZ:"SZSE",SW:"SWX",IM:"BIT",SM:"BME",NA:"ENXT"},by={name:"marketview.asset-identity",columns:["assetClass","type","exchange","currency"],request:({id:e,type:t="Asset"})=>({method:"GET",path:"/v1/plots/entities",query:{ids:e,type:t}}),transform:({raw:e})=>{let t=(e.countries??[])[0]??{};if(Object.keys(t).length>0)return{name:t.name??t.title??null,region:t.region??null,subRegion:t.subRegion??null};let n=(e.portfolios??[])[0]??{};if(Object.keys(n).length>0)return{name:n.name??n.title??null,currency:n.currency??null};let r=(e.assets??[])[0]??{},i=typeof r.bbid=="string"?r.bbid:"",o=i.split(/\s+/),s=o.length>=2?o[o.length-1].toUpperCase():"",a=wy[s]||null;return{assetClass:r.assetClass??null,type:r.type??null,currency:r.currency??null,bbid:i||null,ticker:r.ticker??null,name:r.name??null,exchange:a}}},Ry=by});function Su(e,t){let n=t[e];return typeof n=="string"&&n.length>0&&n!==e}function rr(e,t){return typeof e!="string"?!1:(e.startsWith("MA")||ky.test(e))&&!Su(e,t)}var ky,Xi=v(()=>{"use strict";ky=/^[A-Z0-9]{15,}$/});function ie(e,t){if(Array.isArray(e))return e.map(n=>ie(n,t));if(typeof e=="string")return t[e]||e;if(!m(e))return e;if(m(e.rdate))return e.rdate.rule;for(let n of Ay){if(!(n in e))continue;let r=ie(e[n],t);if(r!=null)return r}return e}function Cu(e,t){return(e==null||e==="")&&t.length===1?t[0]:e}var ir,Ay,At=v(()=>{"use strict";Q();ir=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i,Ay=["label","display","displayName","name","title","value"]});function rt(e){return typeof e=="string"?e.trim():""}function or(e){let t=rt(e);return t.length>0&&Sy.test(t)}function St(e){let t=rt(e);return or(t)||Cy.test(t)&&!Ey.test(t)}function cn(e){let t=rt(e.name),n=rt(e.short_name)||rt(e.bbid)||rt(e.xref?.bbid);return t&&(!n||St(n))?t:n||t||rt(e.id)}var Sy,Cy,Ey,Eu=v(()=>{"use strict";Sy=/^[A-Z0-9_*./-]{1,16} [A-Z*]{2,4}$/,Cy=/^[A-Z][A-Z0-9_.-]{1,14}$/,Ey=/^(?:CH|DV|MD|MW|WC)[A-Z0-9_.-]*\d[A-Z0-9_.-]*$/});function vu(e){let t=e&&typeof e=="object"?e.results:void 0;if(!Array.isArray(t))throw new T("http","Malformed constituents response: expected results array",{path:"/v1/marketview/constituents"});return t}function vy(e,t){if(!t?.id)return;let n=cn(t)||t.id;e[t.id]=n;for(let r of[t.bbid,t.xref?.bbid,t.short_name,t.ticker])St(r)&&(e[String(r).trim()]=n)}function xy(e,t){if(!(!t||typeof t!="object")){for(let n of Object.values(t))if(Array.isArray(n))for(let r of n)vy(e,r)}}function Iy(e,t,n,r){let i=new Set(n);for(let o of n)e[o]=[];for(let o of r.results||[]){let s=o.constituentId||o.assetId;if(s){for(let a of o.controlGroups||[])i.has(a)&&e[a].push(s);t[s]||(t[s]=cn({...o,id:s})||s)}}}function xu(e,t){return e.flatMap(n=>typeof n=="string"&&n.startsWith("CG")&&t[n]?t[n]:[n])}function Dy(e,t){return!rr(e,t)}function ln(e,t){let n=ie(e,t);return n==null?"":typeof n=="object"?JSON.stringify(n):String(n)}function to(e,t){let n=new Set,r=[];for(let i of e){let o=ln(i,t);n.has(o)||(n.add(o),r.push(i))}return r}function Iu(e,t,n){let r=[],i=new Set;for(let o of e){if(!Dy(o,t))continue;let s=ln(o,t);if(!i.has(s)&&(i.add(s),r.push(o),n!==void 0&&r.length>=n))break}return r}async function Du(e,t,n={},r={}){let i={...n.entityMap??{}},o={...n.cgMembers??{}},s=E=>Object.prototype.hasOwnProperty.call(i,E),a=E=>Object.prototype.hasOwnProperty.call(o,E),u=r.countryIds??new Set,l=[...t].filter(E=>E.startsWith("MA")&&!s(E)),c=[...t].filter(E=>E.startsWith("MP")&&!s(E)),d=[...t].filter(E=>!E.startsWith("MA")&&!E.startsWith("MP")&&!E.startsWith("CG")&&!u.has(E)&&!s(E)&&St(E)),f=[...u].filter(E=>!s(E)),p=[...t].filter(E=>E.startsWith("CG")&&!a(E));if(l.length===0&&c.length===0&&d.length===0&&f.length===0&&p.length===0)return{entityMap:i,cgMembers:o};let g=[];for(let E=0;E<l.length;E+=ze)g.push(l.slice(E,E+ze));let h=[];for(let E=0;E<c.length;E+=ze)h.push(c.slice(E,E+ze));let y=[];for(let E=0;E<d.length;E+=ze)y.push(d.slice(E,E+ze));let w=[];for(let E=0;E<f.length;E+=ze)w.push(f.slice(E,E+ze));let b=[...g.map(E=>()=>e("/v1/plots/entities",{method:"GET",query:{ids:E}})),...h.map(E=>()=>e("/v1/plots/entities",{method:"GET",query:{ids:E,type:"Portfolio"}})),...y.map(E=>()=>e("/v1/plots/entities",{method:"GET",query:{ids:E,type:"Asset"}})),...w.map(E=>()=>e("/v1/plots/entities",{method:"GET",query:{ids:E,type:"Country"}}))],R=b.length>0?Promise.all(b.map(E=>E())):Promise.resolve([]),S=p.length>0?e("/v1/marketview/constituents",{method:"GET",query:{groupIds:p,limit:eo}}).then(async E=>{let j=vu(E);return p.length===1||j.length<eo?[{requestedCgIds:p,response:{results:j}}]:(await Promise.all(p.map(A=>e("/v1/marketview/constituents",{method:"GET",query:{groupIds:[A],limit:eo}})))).map((A,I)=>({requestedCgIds:[p[I]],response:{results:vu(A)}}))}):Promise.resolve([]),[C,x]=await Promise.all([R,S]);for(let E of C)xy(i,E);for(let E of x)Iy(o,i,E.requestedCgIds,E.response);return{entityMap:i,cgMembers:o}}var ze,eo,sr=v(()=>{"use strict";ge();Xi();At();Eu();ze=50,eo=100});var _u={};Y(_u,{default:()=>My});function Tu(e){return(Array.isArray(e)?e:e.split(",")).map(t=>t.trim()).filter(Boolean)}function Py(e){if(!e||typeof e!="object")return[];let t=e.assets;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function _y(e){return cn(e)}function $y(e){return[e.bbid,e.ticker,e.id].map(t=>String(t??"").trim()).find(t=>t.length>0)??""}function Pu(e){let t=new Map;for(let n of e)t.set(n.display,(t.get(n.display)??0)+1);return e.map(n=>{let i=(t.get(n.display)??0)>1&&n.qualifier&&n.qualifier!==n.display?`${n.display} (${n.qualifier})`:n.display;return{id:n.id,display:i}})}function Oy(e,t){return[t,e.name,e.short_name,e.bbid,e.ticker,e.id].map(n=>String(n??"").toLowerCase()).join(" ")}var no,Ty,My,$u=v(()=>{"use strict";sr();no=50,Ty={name:"marketview.asset-options",columns:["matches"],steps:[{name:"first",request:({ids:e})=>{let t=Tu(e).slice(0,no);return t.length===0?null:{method:"GET",path:"/v1/plots/entities",query:{ids:t,type:"Asset"}}}}],transform:async({steps:e,args:t,request:n})=>{let r=Tu(t.ids),i=[];for(let c=0;c<r.length;c+=no)i.push(r.slice(c,c+no));let o=i.slice(1),s=[e.first,...await Promise.all(o.map(c=>n("/v1/plots/entities",{method:"GET",query:{ids:c,type:"Asset"}})))],a=(t.query??"").toLowerCase(),u=t.limit??30,l=[];for(let c of s)for(let d of Py(c)){let f=typeof d.id=="string"?d.id:"",p=_y(d),g=$y(d),h=Oy(d,p);if(!(!f||!p)&&(!a||h.includes(a))&&(l.push({id:f,display:p,qualifier:g}),l.length>=u))return{matches:Pu(l)}}return{matches:Pu(l)}}};My=Ty});function Ct(e){return m(e)&&m(e.rdate)&&typeof e.rdate.rule=="string"}function ar(e){if(!(!Ct(e)||!m(e.rdate)))return String(e.rdate.rule)}function fn(e){return Ct(e)?e.value:void 0}var ro=v(()=>{"use strict";Q()});function Ee(e){if(!m(e)||!("marks"in e)||!("step"in e))return e;let t=e.value??e.defaultValue;return m(t)&&"value"in t?t.value:e}var pn=v(()=>{"use strict";Q()});function We(e,t){if(!e)throw new Error(`Unsupported Widget Payload shape: ${t}; record a Scenario before accepting this fallback.`)}function ve(e){return e?.id||e?.field||e?.name}function gn(e,t){We(m(e),"render control is not a record");let n=Object.prototype.hasOwnProperty.call(e,"value");We(n||!Object.prototype.hasOwnProperty.call(e,"defaultValue"),"render control uses defaultValue fallback");let r=n?Ee(e.value):Ee(t);We(r!==void 0,"render control has no selected component value");let i=ar(t);if(i===void 0)return r;let o=fn(t);return String(r)===i||o!=null&&String(r)===String(o)?t:r}function Wy(e,t){let n=e.renderParams?.component||{},r=(e.renderParams?.controls||[]).find(o=>ve(o)===t);if(!r)return;let i=n[t];return gn(r,i)}function mn(e,t,n=[]){let i=(e.renderParams?.component||{})[t]??Wy(e,t)??e.contextParameter?.value??e.contextParameter?.values?.default??void 0;return Cu(i,n)}function io(e){if(!m(e))return!1;let t=e.values,n=Object.prototype.hasOwnProperty.call(e,"values")&&(!m(t)||Object.keys(t).some(r=>r!=="default"));return Object.prototype.hasOwnProperty.call(e,"type")||Object.prototype.hasOwnProperty.call(e,"options")||Object.prototype.hasOwnProperty.call(e,"enums")||Object.prototype.hasOwnProperty.call(e,"allowedValues")||Object.prototype.hasOwnProperty.call(e,"defaultValue")||Object.prototype.hasOwnProperty.call(e,"offset")||n}function Ly(e){let t=e.field??e.id;return We(t!==void 0||!Object.prototype.hasOwnProperty.call(e,"name"),"param field uses name fallback"),typeof t=="string"&&t.trim().length>0?t:void 0}function oo(e){if("value"in e)return e.value;if("default"in e)return e.default;if(m(e.values)&&"default"in e.values)return e.values.default;We(!("rawValue"in e),"param value uses rawValue fallback"),We(!("defaultValue"in e),"param value uses defaultValue fallback")}function ur(e,t,n){!t||n===void 0||n===null||n===""||e.some(r=>r.field===t)||e.push({field:t,value:n})}function hn(e,t){if(Array.isArray(t))for(let n of t)We(m(n),"param entry is not a record"),ur(e,Ly(n),oo(n))}function Ou(e,t){if(m(t))for(let[n,r]of Object.entries(t))ur(e,n,r)}function Le(e){return We(e!=null,"empty widget response"),We(!m(e)||!Object.prototype.hasOwnProperty.call(e,"data"),"widget response uses a data envelope"),e}var it=v(()=>{"use strict";Q();ro();pn();At()});var Lu={};Y(Lu,{default:()=>Ny});function qe(e){return typeof e=="string"&&e.length>0?e:void 0}function qy(e){return qe(e.configurationId)??qe(e.configId)??qe(e.config)??qe(e.configuration?.id)??qe(e.config?.id)??qe(e.metadata?.configurationId)??qe(e.metadata?.configId)??qe(e.metadata?.configuration?.id)??qe(e.metadata?.config?.id)??null}function Mu(e){let t=e.contextParameter?.options;if(!(Array.isArray(t)&&t.length>0))return Array.isArray(e.supportedContexts)?e.supportedContexts:void 0}function Wu(e,t){let n=[];Ou(n,e.renderParams?.component),hn(n,e.renderParams?.controls),hn(n,e.parameters);let r=typeof e.contextParameter?.field=="string"?e.contextParameter.field:void 0,i=n.find(o=>o.field===r)?.value??oo(m(e.contextParameter)?e.contextParameter:{})??t;return ur(n,r,i),n}var Fy,Ny,qu=v(()=>{"use strict";Q();it();Fy={name:"marketview.asset",columns:["id","title","type"],request:({assetId:e,limit:t,offset:n,includeFilters:r=!0})=>({method:"GET",path:"/v1/marketview/widgets",query:{context:e,...t!==void 0?{limit:t}:{},...n!==void 0?{offset:n}:{},includeFilters:r},hedgeDelaysMs:[1e3,2e3]}),transform:({raw:e,args:t})=>{let n=e,r=n.total_results??n.resultsMap?.widgets?.total??(n.results||[]).length,i=(n.results||n.resultsMap?.widgets?.results||[]).map(o=>({id:o.id,title:o.title,configurationId:qy(o),underlyingChartId:o.underlyingChartId??o.chartId??null,visualizationType:o.visualizationType??null,type:o.type||"widget",metadataParameters:Wu(o,t.assetId),configurationParameters:Wu(o,t.assetId),...o.contextParameter?{contextParameter:o.contextParameter}:{},...Mu(o)?{supportedContexts:Mu(o)}:{},...o.parameters?{parameters:o.parameters}:{},...o.renderParams?{renderParams:o.renderParams}:{}}));return{total:r,widgets:i}}},Ny=Fy});function Nu(e){return typeof e=="string"&&/^relative\s+date$/i.test(e.trim())}function dr(e,t){if(!e)throw new Error(`Unsupported dashboard config response shape: ${t}; record a Scenario before accepting this fallback.`)}function so(e,t){if(!e)throw new Error(`Unsupported dashboard chart response shape: ${t}; record a Scenario before accepting this fallback.`)}function ao(e){if(m(e))return e;if(Array.isArray(e)&&e.length===1&&m(e[0]))return e[0];dr(!1,"missing configuration record")}function Uu(e,t){return e==null?[]:(dr(Array.isArray(e),`${t} is not an array`),e)}function Fu(e,t="parameters"){let n=Uu(e,t);for(let r of n)if(dr(m(r),`malformed ${t} entry`),Nu(r.field)){if(typeof r.value=="string"&&r.value.length>0)return r.value.toLowerCase();if(typeof r.value=="number")return String(r.value).toLowerCase()}}function cr(e){let t=ao(e);return typeof t.relativeDate=="string"&&t.relativeDate.length>0?t.relativeDate:Fu(t.modifiedParameters,"modifiedParameters")??Fu(t.parameters,"parameters")}function lr(e){let t=ao(e);return Uu(t.parameters,"parameters").filter(n=>(dr(m(n),"malformed parameters entry"),!Nu(n.field)))}function fr(e){let t=ao(e);return typeof t.underlyingChartId=="string"&&t.underlyingChartId.length>0?t.underlyingChartId:void 0}function pr(e){if(so(m(e),"expected chart record"),typeof e.relativeEndDate=="string"&&/^\+\d+(d|m|y)$/i.test(e.relativeEndDate))return;let t=e.relativeStartDate;so(typeof t=="string","missing relativeStartDate");let n=t.match(/^-(\d+)(d|m|y)$/i);return so(n,"unsupported relativeStartDate"),`${n[1]}${n[2].toLowerCase()}`}var uo=v(()=>{"use strict";Q()});var Vu={};Y(Vu,{default:()=>Gy});function ju(e){throw new Error(`Unsupported dashboard add-widget response shape: ${e}; record a Scenario before accepting this fallback.`)}function Uy(e,t){return m(e)?e:ju(t)}function co(e,t){return typeof e=="string"&&e.length>0?e:ju(t)}function jy(e,t,n=[]){let r={entity_id:e.entityId,type:e.type,parameters:n.length>0?n:e.parameters,...e.extras};return t&&(r.relativeDate=t),r}var Vy,Gy,Gu=v(()=>{"use strict";Q();uo();Vy={name:"marketview.dashboard-add-widget",columns:["id","title","link"],request:({configurationId:e})=>({method:"GET",path:"/v1/marketview/widgets/configurations",query:{id:e.trim()}}),transform:async({raw:e,args:t,request:n})=>{let r=t.configurationId.trim(),i=r?cr(e):void 0,o=r?lr(e):[];if(r&&!i&&o.length===0){let c=co(fr(e),"anchorless config missing underlying chart id"),d=await n(`/v1/charts/${encodeURIComponent(c)}`);i=pr(d)}let s=await n(`/v1/marketview/dashboards/${encodeURIComponent(t.dashboardId)}/children`,{method:"POST",body:[jy(t.child,i,o)]}),a=Uy(s,"expected object"),u=co(a.id,"missing id"),l=co(a.title,"missing title");return{id:u,title:l,link:`https://marquee.gs.com/s/marketview/dashboards/${u}`}}},Gy=Vy});var Hu={};Y(Hu,{default:()=>zy});function Bu(e,t){if(!e)throw new Error(`Unsupported dashboard create-section response shape: ${t}`)}function By(e,t){let n;for(let r of[e.id,e.uuid,e.sectionId])if(r!==t&&typeof r=="string"&&r.length>0){n=r;break}return Bu(n!==void 0||e.id===t,"missing section id"),n}var Hy,zy,zu=v(()=>{"use strict";Q();Hy={name:"marketview.dashboard-create-section",columns:["dashboardId","title"],request:({dashboardId:e,title:t,childIds:n})=>({method:"POST",path:`/v1/marketview/dashboards/${encodeURIComponent(e)}/sections`,body:{title:t,children:n}}),transform:({raw:e,args:t})=>{Bu(m(e),"expected response record");let n=By(e,t.dashboardId);return{dashboardId:t.dashboardId,title:typeof e.title=="string"&&e.title.length>0?e.title:t.title,...n?{sectionId:n}:{}}}},zy=Hy});var Yu={};Y(Yu,{default:()=>Qy});function Ju(e,t){if(!e)throw new Error(`Unsupported dashboard create response shape: ${t}`)}function Jy(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>0?t:"dashboard"}function Yy(e,t,n){return{title:e,description:"",tags:[],relatedLinks:[],alias:Jy(e),addTagsFromChildren:!0,isRequestable:!1,children:[{entity_id:t,type:"Widget",parameters:[],configurationId:n,rank:1}]}}var Ky,Qy,Ku=v(()=>{"use strict";Q();Ky={name:"marketview.dashboard-create-with-widget",columns:["id","title","link"],request:({title:e,widgetId:t,configurationId:n})=>({method:"POST",path:"/v1/marketview/dashboards/default",body:Yy(e,t,n)}),transform:({raw:e,args:t})=>{Ju(m(e),"expected dashboard record"),Ju(typeof e.id=="string"&&e.id.length>0,"missing dashboard id");let n=e.id,r=typeof e.title=="string"&&e.title.length>0?e.title:t.title;return{id:n,title:r,link:`https://marquee.gs.com/s/marketview/dashboards/${n}`}}},Qy=Ky});var Qu={};Y(Qu,{default:()=>Xy});var Zy,Xy,Zu=v(()=>{"use strict";Zy={name:"marketview.dashboard-delete-section",columns:["dashboardId","sectionId"],request:({dashboardId:e,sectionId:t})=>({method:"DELETE",path:`/v1/marketview/dashboards/${encodeURIComponent(e)}/sections/${encodeURIComponent(t)}`}),transform:({args:e})=>({dashboardId:e.dashboardId,sectionId:e.sectionId})},Xy=Zy});var ed={};Y(ed,{default:()=>nw});function Xu(e,t){if(!e)throw new Error(`Unsupported dashboard lookup response shape: ${t}`)}function ew(e){return Xu(m(e)&&Array.isArray(e.results),"missing results array"),e.results.map(t=>(Xu(m(t)&&typeof t.id=="string"&&t.id.length>0&&typeof t.title=="string"&&t.title.length>0,"malformed dashboard result"),{id:t.id,title:t.title}))}var tw,nw,td=v(()=>{"use strict";Q();tw={name:"marketview.dashboard-find-by-title",columns:["id","title"],request:()=>({method:"GET",path:"/v1/marketview/dashboards",query:{view_as:"edit",size:100,page:1}}),transform:({raw:e,args:t})=>{let n=ew(e),r=t.title.trim().toLowerCase();return n.filter(i=>i.title.trim().toLowerCase()===r)}},nw=tw});var nd={};Y(nd,{default:()=>ow});function rw(e){if(!e)throw new Error("Unsupported dashboard raw response shape: expected dashboard record; record a Scenario before accepting this fallback.")}var iw,ow,rd=v(()=>{"use strict";Q();iw={name:"marketview.dashboard-raw",columns:["id","title","type"],request:({id:e})=>({method:"GET",path:`/v1/marketview/dashboards/${encodeURIComponent(e)}`,query:{expand:!0},hedgeDelaysMs:[1e3,2e3]}),transform:({raw:e})=>(rw(m(e)),e)},ow=iw});var id={};Y(id,{default:()=>aw});var sw,aw,od=v(()=>{"use strict";sw={name:"marketview.dashboard-remove-widget",columns:["dashboardId","childId"],request:({dashboardId:e,childId:t})=>({method:"DELETE",path:`/v1/marketview/dashboards/${encodeURIComponent(e)}/children/${encodeURIComponent(t)}`}),transform:({args:e})=>({dashboardId:e.dashboardId,childId:e.childId})},aw=sw});var sd={};Y(sd,{default:()=>dw});var uw,dw,ad=v(()=>{"use strict";uw={name:"marketview.dashboard-set-section",columns:["dashboardId","sectionId"],request:({dashboardId:e,sectionId:t,childIds:n})=>({method:"PUT",path:`/v1/marketview/dashboards/${encodeURIComponent(e)}/sections/${encodeURIComponent(t)}`,body:{children:n}}),transform:({args:e})=>({dashboardId:e.dashboardId,sectionId:e.sectionId,childIds:e.childIds})},dw=uw});var gd={};Y(gd,{default:()=>Aw});function It(e){throw new Error(`Unsupported dashboard update response shape: ${e}; record a Scenario before accepting this fallback.`)}function xt(e,t){return m(e)?e:It(t)}function xe(e,t){return typeof e=="string"&&e.length>0?e:It(t)}function mr(e,t){return Array.isArray(e)?e:It(t)}function cd(e){return typeof e=="number"&&Number.isFinite(e)?e:It("dashboard child rank is not a finite number")}function gr(e){return mr(e.children,"dashboard.children is not an array").map(t=>xt(t,"dashboard child is not an object"))}function yn(e){return xe(e.entity_id,"dashboard child entity_id is not a non-empty string")}function Je(e){for(let t of[e.id,e.uuid,e.childId])if(typeof t=="string"&&t.length>0)return t;return It("dashboard child id is not a non-empty string")}function vt(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function lo(e){let t=vt(e.configurationId);if(t)return t;if(m(e.configuration)){let n=vt(e.configuration.id);if(n)return n}if(m(e.data)){let n=vt(e.data.configurationId);if(n)return n;if(m(e.data.configuration))return vt(e.data.configuration.id)}}function ud(e,t){let n=gr(e).filter(i=>yn(i)===t);if(n.length>1)throw new Error(`dashboard child ${t} matched multiple dashboard children; refusing ambiguous configuration update`);let r=n[0];if(!r)throw new Error(`dashboard child ${t} was not found`);return r}function cw(e,t,n){let r=gr(xt(e,"add-child response is not an object")).find(i=>yn(i)===t&&!n.has(Je(i)));return r||It("add-child response does not contain the added child")}function lw(e,t,n,r){let i={entity_id:yn(e),type:xe(e.type,"dashboard child type is not a non-empty string"),parameters:r,configurationId:t};return n&&(i.relativeDate=n),i.rank=cd(e.rank),i}function fw(e){return{entity_id:yn(e),type:xe(e.type,"dashboard child type is not a non-empty string"),parameters:e.parameters===void 0?[]:mr(e.parameters,"dashboard child parameters is not an array"),rank:cd(e.rank)}}function ld(e){return mr(e.sections,"dashboard.sections is not an array").map(t=>xt(t,"dashboard section is not an object"))}function fd(e){return xe(e.id,"dashboard section id is not a non-empty string")}function pd(e){return mr(e.children,"dashboard section children is not an array").map(t=>xe(t,"dashboard section child id is not a non-empty string"))}function pw(e,t){return ld(e).find(n=>fd(n)===t)}function gw(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function mw(e,t,n){let r=[];for(let i of e){let o=i===t?n:i;r.includes(o)||r.push(o)}return r}function hw(e,t,n){return ld(e).flatMap(r=>{let i=fd(r),o=pd(r);return o.includes(t)?[{sectionId:i,childIds:mw(o,t,n),originalChildIds:o}]:[]})}function yw(e,t){return Array.isArray(e.sections)&&e.sections.some(n=>m(n)&&Array.isArray(n.children)&&n.children.includes(t))}function ww(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"?String(e):JSON.stringify(e)}function Et(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){let r=xt(n,"dashboard parameter entry is not an object"),i=xe(r.field,"dashboard parameter entry field is not a non-empty string");t.set(i.trim().toLowerCase(),ww(r.value))}return t}function bw(e,t){let n=Et(t);if(n.size===0)return!1;let r=m(e.data)?e.data:void 0,i=new Map([...Et(e.parameters),...Et(e.modifiedParameters),...Et(r?.parameters),...Et(r?.modifiedParameters)]);for(let[o,s]of n)if(i.get(o)!==s)return!1;return!0}function Rw(e,t,n,r){let i=lo(e);if(i===void 0)return!1;let o=bw(e,r);return n?e.relativeDate!==n?!1:Et(r).size===0||o:o||i===t}async function dd(e,t,n,r){throw await e(`/v1/marketview/dashboards/${encodeURIComponent(t)}/children/${encodeURIComponent(r)}`,{method:"DELETE"}),new Error(`widget ${n} configuration did not persist on dashboard ${t}; original tile left unchanged because the service stripped the tile configuration on re-add`)}var kw,Aw,md=v(()=>{"use strict";uo();kw={name:"marketview.dashboard-update-widget-configuration",columns:["id","title","link"],request:({dashboard:e,widgetId:t,configurationId:n})=>{let r=xe(e.id,"dashboard.id is not a non-empty string"),i=ud(e,t);Je(i);let o=vt(n);return o?{method:"GET",path:"/v1/marketview/widgets/configurations",query:{id:o}}:{method:"POST",path:`/v1/marketview/dashboards/${encodeURIComponent(r)}/children`,body:[fw(i)]}},transform:async({raw:e,args:t,request:n})=>{let r=xe(t.dashboard.id,"dashboard.id is not a non-empty string"),i=ud(t.dashboard,t.widgetId),o=Je(i),s=vt(t.configurationId),a,u;if(s?(a=cr(e),u=lr(e)):u=[],s&&!a&&u.length===0){let w=fr(e);if(w){let b=await n(`/v1/charts/${encodeURIComponent(w)}`);a=pr(b)}}let l=new Set(gr(t.dashboard).map(w=>Je(w))),c=s?void 0:e;s&&(c=await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}/children`,{method:"POST",body:[lw(i,s,a,u)]}));let d,f;try{d=Je(cw(c,t.widgetId,l))}catch(w){f=w}let p,g,h,y=!1;try{let w=await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}`,{method:"GET",query:{expand:!0}});if(p=xt(w,"post-add dashboard refetch is not an object"),g=xe(p.title,"post-add dashboard refetch title is not a non-empty string"),h=gr(p).filter(b=>yn(b)===t.widgetId).find(b=>!l.has(Je(b))),f!==void 0){if(h!==void 0){let b=Je(h);await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}/children/${encodeURIComponent(b)}`,{method:"DELETE"})}throw f}h!==void 0&&(y=s?Rw(h,s,a,u):lo(h)===void 0)}catch(w){throw d!==void 0&&await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}/children/${encodeURIComponent(d)}`,{method:"DELETE"}),w}if(h!==void 0){let w=Je(h);if(!y)return dd(n,r,t.widgetId,w);let b=[],R=Array.isArray(p.sections)&&p.sections.length>0?p:yw(t.dashboard,o)?t.dashboard:p;try{for(let C of hw(R,o,w)){await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}/sections/${encodeURIComponent(C.sectionId)}`,{method:"PUT",body:{children:C.childIds}}),b.push(C);let x=await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}`,{method:"GET",query:{expand:!0}}),E=xt(x,"section membership verification refetch is not an object"),j=pw(E,C.sectionId);if(!j||!gw(pd(j),C.childIds))throw new Error(`section membership update ${C.sectionId} did not persist on dashboard ${r}`)}await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}/children/${encodeURIComponent(o)}`,{method:"DELETE"})}catch(C){for(let x of[...b].reverse())await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}/sections/${encodeURIComponent(x.sectionId)}`,{method:"PUT",body:{children:x.originalChildIds}});throw await n(`/v1/marketview/dashboards/${encodeURIComponent(r)}/children/${encodeURIComponent(w)}`,{method:"DELETE"}),C}let S=s?xe(lo(h),"persisted child configurationId is not a non-empty string"):void 0;return{id:r,title:g,link:`https://marquee.gs.com/s/marketview/dashboards/${r}`,...S?{configurationId:S}:{}}}return dd(n,r,t.widgetId,xe(d,"add-child response does not contain the added child"))}},Aw=kw});function bn(e){return/Unknown Value/i.test(e)||/<\s*[^:<>]+\s*:\s*[^<>]+\s*>/.test(e)}function hr(e){return!!e?.startsWith("CH")}function Ie(e,t){typeof t!="string"||t.length===0||e.includes(t)||e.push(t)}function Sw(e,t,n){typeof t!="string"||t.length===0||e.some(r=>r.field===t)||e.push({field:t,kind:n})}function ot(e){return typeof e=="object"&&e!==null&&e.__marqueeSource===fo}function hd(e){return e.underlyingChartId??e.chartId??""}function Cw(e){let t={contextParameter:[],controls:[],params:[],component:[]};Ie(t.contextParameter,e.contextParameter?.field);let n=e.renderParams?.controls??[],r=new Set,i=[];for(let o of n){if(ot(o)){for(let s of[o.field,o.id,o.name])typeof s=="string"&&s.length>0&&r.add(s);continue}i.push(o),Ie(t.controls,o.field),Ie(t.controls,o.id),Ie(t.controls,o.name)}i.length===0&&hr(hd(e))&&e.visualizationType==="Plot"&&Ie(t.controls,wn);for(let o of e.parameters??[])typeof o.field=="string"&&r.has(o.field)&&!io(o)||Sw(t.params,o.field,io(o)?"definition":"fallback");for(let o of Object.keys(e.renderParams?.component??{}))r.has(o)||Ie(t.component,o);return t}function Ew(e,t){return hr(hd(t))&&Ie(e,wn),e}function Ye(e){let t=Cw(e),n=[];for(let r of t.contextParameter)Ie(n,r);for(let r of t.controls)Ie(n,r);for(let r of t.params)Ie(n,r.field);for(let r of t.component)Ie(n,r);return Ew(n,e)}function vw(e){return e.replace(/\s+/g," ").trim()}function Dt(e,t,n,r={}){let i=t.length>0?t.join(", "):"(none)",o=vw(e);return r.store&&r.widget&&r.store.mergeRefs({[n]:{type:"widget",id:r.widget.id,title:r.widget.title??e,configurationId:r.widget.configurationId??""}}),[`- "${o}" [@${n}, load]`,` - params: ${i}`].join(`
13
+ `)}var wn,fo,$e=v(()=>{"use strict";it();wn="Relative Date",fo="configuration-detail"});var Ad={};Y(Ad,{default:()=>Iw});function Dw(e){let t=Rd(e),n=kd(t.contextParameter),r=typeof n?.field=="string"&&n.field.length>0?n.field:void 0,i=[];return hn(i,po(e.parameters,"child.parameters")),r?i.filter(o=>o.field===r):i}function Oe(e,t){if(!e)throw new Error(`Unsupported dashboard response shape: ${t}; record a Scenario before accepting this fallback.`)}function Tw(e){return Oe(m(e),"expected dashboard record"),e}function yd(e,t){return e==null?[]:(Oe(Array.isArray(e),`${t} is not an array`),e)}function po(e,t){if(e!=null)return Oe(Array.isArray(e),`${t} is not an array`),e.map(n=>(Oe(m(n),`malformed ${t} entry`),n))}function yr(e,t){if(e!=null)return Oe(m(e),`${t} is not a record`),e}function ye(e,t){if(!(e==null||e===""))return Oe(typeof e=="string",`${t} is not a string`),e}function bd(e,t){let n=ye(e,t);return Oe(n!==void 0,`${t} is missing`),n}function wd(e,t){if(e!=null)return Oe(m(e),`${t} is not a record`),ye(e.id,`${t}.id`)}function Rd(e){return e.data===void 0?e:(Oe(m(e.data),"child data is not a record"),e.data)}function kd(e){return yr(e,"contextParameter")}function Pw(e){let t=yr(e,"renderParams");if(t)return{controls:po(t.controls,"renderParams.controls"),component:yr(t.component,"renderParams.component")}}function _w(e){let t=yr(e.metadata,"metadata");return(t?ye(t.title,"metadata.title"):void 0)??bd(e.title,"widget title")}function $w(e,t){return ye(e.configurationId,"child.configurationId")??wd(e.configuration,"child.configuration")??ye(t.configurationId,"data.configurationId")??wd(t.configuration,"data.configuration")}var xw,Iw,Sd=v(()=>{"use strict";$e();it();Q();xw={name:"marketview.dashboard",columns:["id","title","type"],formatError:(e,t)=>t===403?`Access denied: dashboard ${e.id}`:void 0,request:({id:e})=>({method:"GET",path:`/v1/marketview/dashboards/${encodeURIComponent(e)}`,query:{expand:!0},hedgeDelaysMs:[1e3,2e3]}),transform:({raw:e,args:t})=>{let n=Tw(e),r=yd(n.tags,"tags"),i=yd(n.children,"children").map(s=>{Oe(m(s),"malformed child entry");let a=Rd(s),u=Dw(s),l={id:bd(a.id,"widget id"),title:_w(a),configurationId:$w(s,a)??null,underlyingChartId:ye(a.underlyingChartId,"underlyingChartId")??ye(a.chartId,"chartId")??null,configurationParameters:u,parameters:po(s.parameters,"child.parameters"),renderParams:Pw(s.renderParams??a.renderParams),contextParameter:kd(a.contextParameter),visualizationType:ye(a.visualizationType,"visualizationType")??null,type:ye(s.type,"child.type")??"widget"},c=Ye(l);return c.length>0?{...l,paramNames:c}:l}),o=ye(n.id,"dashboard id")??t.id;return{title:n.title,author:ye(n.author,"author")??ye(n.createdBy,"createdBy")??null,description:ye(n.description,"description")??null,tags:r,link:`https://marquee.gs.com/s/marketview/dashboards/${o}`,widgetCount:i.length,total:i.length,widgets:i}}},Iw=xw});var Ed={};Y(Ed,{default:()=>qw});function Ow(e,t,n){let r=String(e.type??"").toLowerCase();return r==="widget"||t.startsWith("MW")||n.includes("/widget/")?"widget":r==="dashboard"||t.startsWith("MD")||n.includes("/dashboards/")?"dashboard":r==="asset"||t.startsWith("MA")||n.includes("/asset/")?"asset":r==="link"||n.length>0?"link":r||"item"}function Mw(e){return e.match(/\b(MW[A-Z0-9]+|MD[A-Z0-9]+|MA[A-Z0-9]+)\b/)?.[1]??""}function Cd(e){if(e)return e.startsWith("http://")||e.startsWith("https://")?e:e.startsWith("/dashboards/")?`https://marquee.gs.com/s/marketview${e}`:e.startsWith("/")?`https://marquee.gs.com${e}`:e}function Ww(e){let t=String(e.url??""),n=String(e.entityId??e.id??Mw(t));return{type:Ow(e,n,t),title:String(e.metadata?.title??e.title??e.name??""),...n?{id:n}:{},...Cd(t)?{url:Cd(t)}:{},...e.configurationId?{configurationId:String(e.configurationId)}:{}}}var Lw,qw,vd=v(()=>{"use strict";Lw={name:"marketview.discover",columns:["section","count","items"],request:()=>({method:"GET",path:"/v1/marketview/homepage"}),transform:({raw:e})=>{let t=e;if(t.sections==null)throw new Error("missing sections in MarketView homepage response");if(!Array.isArray(t.sections))throw new Error("invalid sections in MarketView homepage response");return t.sections.map(n=>{let r=n,i=Array.isArray(r.items)?r.items:[],o=i.map(Ww).filter(s=>s.title);return{section:String(r.title??""),count:i.length,items:i.slice(0,3).map(s=>s.title||s.name).join(", "),entries:o}})}},qw=Lw});var xd={};Y(xd,{default:()=>Uw});var Fw,Nw,Uw,Id=v(()=>{"use strict";Fw=[500,1250],Nw={name:"marketview.filter-constituents",columns:["matches"],steps:[{name:"search",request:({groupIds:e,query:t,limit:n})=>({method:"GET",path:"/v1/marketview/constituents",query:{groupIds:e,query:t,limit:n},hedgeDelaysMs:Fw})}],transform:({steps:e})=>({matches:(e.search.results||[]).map(n=>({id:n.constituentId||n.assetId,display:n.bbid||n.name||n.constituentId||n.assetId}))})},Uw=Nw});var Dd={};Y(Dd,{default:()=>Vw});var jw,Vw,Td=v(()=>{"use strict";Q();jw={name:"marketview.preferences",columns:["pins"],request:()=>({method:"GET",path:"/v1/marketview/preferences"}),transform:({raw:e})=>{let t=m(e)&&m(e.value)?e.value:{};return{pins:Array.isArray(t.pins)?t.pins.filter(r=>typeof r=="string"?r.length>0:m(r)?typeof r.widgetId=="string"||typeof r.id=="string":!1):[]}}},Vw=jw});function Gw(e,t="GET"){return e.includes("/marketview/widgets/configurations")?t==="POST"?"configuration.create":"configuration.detail":e.includes("/marketview/widgets/")?"widget.metadata":e.includes("/marketview/dashboards")?"dashboard.list":e.includes("/charts/")?"chart.definition":e.includes("/plots/entities")?"entity.resolve":e.includes("/marketview/constituents")?"constituents.resolve":e.includes("/data/visualizations/")?"dv.render":e.includes("/plots/runner")?"ch.runner":"upstream"}function Bw(e,t){return{method:t?.method??"GET",path:e,...t?.query?{query:t.query}:{},...t?.body!==void 0?{body:t.body}:{}}}function go(e,t){return{schema:"marketview.widget.audit.v1",command:{surface:"marketview",command:"widget",id:e,...t?{context:t}:{}},renderKind:"unknown",calls:[]}}function mo(e,t){return async(n,r)=>{let i=!!process.env.MARQUEE_HTTP_REPLAY,o={name:Gw(n,r?.method??"GET"),request:Bw(n,r),status:"error",ms:0},s=Date.now();t.calls.push(o);try{let a=await e(n,r);return o.status=200,o.ms=i?0:Date.now()-s,o.response=a,a}catch(a){throw o.ms=i?0:Date.now()-s,o.error=a instanceof Error?a.message:String(a),a}}}function Rn(e){let t=e;return typeof t?.id=="string"&&t.id.length>0?t.id:Array.isArray(t)&&typeof t[0]?.id=="string"&&t[0].id.length>0?t[0].id:""}var ho=v(()=>{"use strict"});function Pd(e){let t=String(e).match(/^-(\d+)(d|m|y)$/);return t?`${Number(t[1])}${t[2].toUpperCase()}`:String(e)}function _d(e){return yo.includes(e)?yo:[...yo,e]}var yo,$d=v(()=>{"use strict";yo=["1M","3M","6M","YTD","1Y","2Y","5Y"]});function zw(e,t){return Array.isArray(e)?e.some(n=>typeof n=="string"&&n.startsWith("MA"))||(t||[]).some(n=>typeof n=="string"&&n.startsWith("MA"))?"AssetList":"EnumList":typeof e=="boolean"?"Boolean":typeof e=="number"?"Integer":e&&typeof e=="object"&&"rdate"in e?"Date":typeof e=="string"&&e.startsWith("MA")||typeof e=="string"&&e.startsWith("CG")||(t||[]).some(n=>typeof n=="string"&&n.startsWith("MA"))||(t||[]).some(n=>typeof n=="string"&&n.startsWith("CG"))?"Asset":(t||[]).length>0?"Enum":"String"}function Od(e){if(typeof e=="string"){let n=e.trim().replace(/\s+/g,"").toLowerCase(),r=Hw[n];if(r)return r}}function Tt(e,t,n){return Od(e.type)??Od(e.controlType)??zw(t,n)}var Hw,Md=v(()=>{"use strict";Hw={asset:"Asset",assetlist:"AssetList",asset_list:"AssetList","asset-list":"AssetList",boolean:"Boolean",context:"Context",country:"Country",countryid:"Country",countrylist:"CountryList",date:"Date",enum:"Enum",enumlist:"EnumList",enum_list:"EnumList","enum-list":"EnumList",integer:"Integer",number:"Integer",portfolio:"Portfolio",relativedate:"RelativeDate",relative_date:"RelativeDate","relative-date":"RelativeDate",string:"String"}});function F(e,t){if(!e)throw new Error(`Unsupported widget params response shape: ${t}; record a Scenario before accepting this fallback.`)}function Zw(e,t){return e==null?[]:(F(Array.isArray(e),`${t} is not an array`),e)}function Ke(e,t,n){return e==null?[]:(F(m(e),`${n} parent is not a record`),Zw(e[t],n))}function Pt(e){return Ke(e?.renderParams,"controls","renderParams.controls")}function Ar(e){return Ke(e,"parameters","parameters")}function Wd(e){return Ke(e,"controls","chart.controls")}function Rr(e){return Ke(e?.contextParameter,"options","contextParameter.options")}function Sr(e){let t=e?.renderParams?.component;return t==null?{}:(F(m(t),"renderParams.component is not a record"),t)}function Gd(e,t){return F(m(e),`${t} is not a record`),F(!Object.prototype.hasOwnProperty.call(e,"enums"),`${t} uses enums fallback`),F(!Object.prototype.hasOwnProperty.call(e,"allowedValues"),`${t} uses allowedValues fallback`),Ke(e,"options",`${t}.options`)}function Bd(e,t){return F(m(e),`${t} is not a record`),F(!Object.prototype.hasOwnProperty.call(e,"enums"),`${t} uses enums fallback`),F(!Object.prototype.hasOwnProperty.call(e,"allowedValues"),`${t} uses allowedValues fallback`),Ke(e,"values",`${t}.values`)}function Xw(e){return F(!(m(e)&&"rawValue"in e),"Date option uses a rawValue wrapper"),e}function Ld(e,t,n){if(n!=="Date")return to(e,t);let r=new Set,i=[];for(let o of e){let s=Xw(o),a=ar(s),u=fn(s),l=a&&u!==void 0?`${ln(o,t)}\0${a}\0${String(u)}`:ln(o,t);F(!r.has(l),"Date options contain a duplicate value"),r.add(l),i.push(s)}return i}function kr(e){return e==="Asset"||e==="AssetList"}function Ro(e){let t=new Set;for(let n of Pt(e)){if(!ot(n))continue;let r=ve(n);r&&t.add(r)}return t}function Hd(e,t,n){let r=Tt(e,t,n),i=at(e?.field).toLowerCase();return i==="portfolio"&&F(!["Asset","Enum","String"].includes(r),"context parameter type requires repair"),/^assets?\d*$/.test(i)&&F(r!=="Enum","context parameter type requires repair"),r}function br(e,t){return e.map(n=>({label:ie(n,t),rawValue:n}))}function st(e,t,n=!1,r={}){if(Array.isArray(t)){t.forEach(s=>st(e,s,n,r));return}let i=r.includeControlGroups??!0,o=r.includePortfolios??!0;typeof t=="string"&&(t.startsWith("MA")||i&&t.startsWith("CG")||o&&t.startsWith("MP")||or(t)||n&&St(t))&&e.add(t)}function qd(e){return e.slice(0,Jw)}function Fd(e){return e.length>0&&!ir.test(e)&&!/\bUnknown Value\b/.test(e)}function zd(e,t,n){let r=n.length>0&&n.every(Fd),i=e>0&&n.length===e&&r?n:t.length>0?t:n,o=i.filter(Fd);return e>0&&o.length!==e?[]:o.length>0?o:i}function Nd(e,t){if(!Ct(t)||Ct(e))return;let n=fn(t);F(n!=null,"relative Date default has no concrete value"),F(String(e)!==String(n),"relative Date default requires restoration")}function ko(e){F(m(e),"widget is not a record");let t=Sr(e);for(let n of Pt(e)){F(m(n),"render control is not a record");let r=String(ve(n));Nd(t[r],n.value)}for(let n of Ar(e))F(m(n),"parameter is not a record"),typeof n.field=="string"&&m(n.values)&&Ct(n.values.default)&&Nd(t[n.field],n.values.default);return e}function Ud(e,t){for(let n of t)F(!Array.isArray(n),"control-group options contain a nested array"),typeof n=="string"&&n.startsWith("CG")&&e.add(n)}function wo(e,t){F(!Array.isArray(t),"country value is an array"),typeof t=="string"&&Qw.test(t)&&e.add(t)}function jd(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function bo(e,t){F(m(e),"country param is not a record"),F(!Object.prototype.hasOwnProperty.call(e,"controlType"),"country param uses controlType fallback");let n=jd(e.type),r=jd(t);return n==="country"||n==="countrylist"||r==="country"||r==="countryid"||r==="countries"||r==="countrycode"||r==="countrycodes"}function eb(e){return e.some(t=>typeof t=="string"&&t.startsWith("CG"))}function Vd(e,t){return!(kr(e)&&t.length>Kw&&!eb(t))}function at(e){return[e].join("").trim()}function Jd(e){let t=new Set,n=Sr(e),r=Ro(e),i=e.contextParameter?.field||"context",o=n[i]??e.contextParameter?.value??e.contextParameter?.values?.default,s=Rr(e),a=e.contextParameter?Hd(e.contextParameter,o,s):"Context",u=a==="Portfolio",l=!u,c=Vd(a,s)?e.contextParameter?.field?qd(s):s:[];for(let d of c)st(t,d,l,{includeControlGroups:!u});!u&&Vd(a,s)&&Ud(t,s),st(t,o,l,{includeControlGroups:!u});for(let[d,f]of Object.entries(n))F(!r.has(d),"component overlaps a hidden config control"),st(t,f);for(let d of Pt(e)){if(ot(d))continue;let f=ve(d);if(f===void 0)continue;let p=gn(d,n[f]),g=Ke(d,"values","control.values"),h=Tt(d,p,g),y=kr(h);y&&F(g.length===0,"render control exposes options before chart lookup"),st(t,p,y,{includeControlGroups:h!=="Portfolio"})}for(let d of Ar(e)){F(!r.has(d?.field),"parameter overlaps a hidden config control");let f=Yd(d,n[d.field]),p=Gd(d,"parameter"),g=p.length===1&&Array.isArray(p[0])?p[0]:p,h=Tt(d,f,g),y=kr(h),w=h!=="Portfolio";st(t,f,y,{includeControlGroups:w});let b=qd(g);for(let R of b)st(t,R,y,{includeControlGroups:w});w&&Ud(t,g)}return t}function Yd(e,t){return F(m(e),"parameter is not a record"),F(!Object.prototype.hasOwnProperty.call(e,"value"),"parameter uses value fallback"),F(!Object.prototype.hasOwnProperty.call(e,"defaultValue"),"parameter uses defaultValue fallback"),F(m(e.values)&&Object.prototype.hasOwnProperty.call(e.values,"default"),"parameter.values.default is missing"),t??e.values.default}function Kd(e){let t=new Set,n=Sr(e),r=Ro(e);if(e.contextParameter){let i=e.contextParameter.field||"context",o=Rr(e),s=mn(e,i,o);if(!e.contextParameter.field||bo(e.contextParameter,i)){wo(t,s);for(let a of o)wo(t,a)}}for(let i of Pt(e)){if(ot(i))continue;let o=ve(i);if(!o||!bo(i,o))continue;let s=gn(i,n[o]);wo(t,s);let a=Bd(i,"control");F(a.length===0,"country render control exposes option values")}for(let i of Ar(e))F(!r.has(i?.field),"parameter overlaps a hidden config control"),i.field&&F(!bo(i,i.field),"country parameter definitions are not supported");return t}function Qd({widget:e,entityMap:t,cgMembers:n,chart:r,isDV:i}){let o=Sr(e),s=[],a=new Set,u=Ro(e);if(e.contextParameter&&Rr(e).length>0){let c=Rr(e);F(c.every(g=>typeof g=="string"),"contextParameter.options contain a non-string value");let d=c,f=e.contextParameter.field||"context",p=mn(e,f,d);if(i||e.contextParameter.field){F(typeof p=="string","contextParameter default is not a string");let g=Hd(e.contextParameter,p,d),y=kr(g)?d.filter(x=>x.startsWith("CG")):[];for(let x of y)F(Array.isArray(n[x]),`control group ${x} was not resolved`);let w=y.length>0,b=w?to(y.flatMap(x=>n[x]),t):g==="Portfolio"?d.filter(x=>!x.startsWith("CG")):d,R=w?b.slice(0,wr):Iu(b,t,wr),S=w?y.reduce((x,E)=>x+n[E].length,0):b.length,C=w&&S>wr&&S<Yw?b.map(x=>ie(x,t)):void 0;s.push({field:f,type:g,values:R.map(x=>ie(x,t)),rawValues:R,options:br(R,t),default:ie(p,t),rawDefault:p,...w?{filterable:!0,cgGroupIds:y}:{},...C?{allOptions:C}:{},...S>wr?w?{totalOptions:S}:{totalOptions:S,allRawOptions:d}:{}})}a.add(f)}for(let c of Pt(e)){if(ot(c))continue;let d=ve(c);if(!d||a.has(d))continue;let f=Bd(c,"control");if(f.length===0){let y=Wd(r).find(w=>w.id===d);f=xu(Ke(y,"values","chart control.values"),n)}let p=gn(c,o[d]);F(p!==null,"render control default is null");let g=Tt(c,p,f),h=Ld(f.map(Ee),t,g);s.push({field:d,type:g,values:h.map(y=>ie(y,t)),rawValues:h,options:br(h,t),default:ie(p,t),rawDefault:p}),a.add(d)}for(let c of Wd(r)){let d=ve(c);d&&F(u.has(d)||a.has(d),`chart control ${d} is not represented by widget metadata`)}if(!i&&(r.relativeStartDate||r.startDate)){let c=r.relativeStartDate,d=c?Pd(c):"\u2014",f=_d(c?d:"1Y");s.push({field:"Relative Date",type:"Enum",values:[],rawValues:[],options:br(f,t),display:f,default:d,rawDefault:c??r.startDate})}let l=Pt(e).some(c=>!ot(c));for(let c of Ar(e)){if(F(!u.has(c?.field),"parameter overlaps a hidden config control"),!c.field||a.has(c.field))continue;F(i||!l||!/^asset\d+$/i.test(c.field),"CH asset# parameter requires suppression");let d=Gd(c,"parameter"),f=d.length===1&&Array.isArray(d[0])?d[0]:d,p=Yd(c,o[c.field]),g=Tt(c,p,f),h=Ld(f,t,g);s.push({field:c.field,type:g,values:h.map(y=>ie(y,t)),rawValues:h,options:br(h,t),default:ie(p,t),rawDefault:p}),a.add(c.field)}for(let c of s)c.display||(c.display=c.options.map(d=>String(d.label)));return s}var wr,Jw,Yw,Kw,Qw,Ao=v(()=>{"use strict";pn();$d();ro();it();Q();Md();At();$e();sr();wr=30,Jw=50,Yw=100,Kw=1500,Qw=/^[A-Z]{2}$/});function Cr(e){return typeof e=="string"?[e]:Array.isArray(e)?e.map(t=>String(t)):[]}function nb(e){return String(e??"").toLowerCase().replace(/[^a-z0-9]/g,"")}function So(e){return[...Cr(e?.tags),...Cr(e?.metadata?.tags),...Cr(e?.metadata?.dataSources),...Cr(e?.dataAttribution)].map(n=>n.toLowerCase().replace(/[^a-z0-9]/g,"")).some(n=>n.includes("quickpoll"))}function Er(e){return nb(e)==="surveydate"}function Xd(e,t){return So(t)?e.map(n=>Er(n.field)?{...n,fillBlocked:{reason:tb}}:n):e}var tb,Zd,Co=v(()=>{"use strict";tb="quickpoll-survey-date",Zd="QuickPoll surveyDate depends on question; changing surveyDate from the CLI can render mismatched title/data/description. Load the QuickPoll result for the desired survey date, or choose a valid question in Marquee UI before reading data"});function ec(e){return typeof e=="string"&&e.length>0}function vr(e){if(e==null)return;if(typeof e=="string"){let r=e.trim();return r.length>0?r:void 0}if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e)){let r=e.map(i=>vr(i)).filter(ec);return r.length>0?r.join(" "):void 0}if(typeof e!="object")return;let t=e;for(let r of rb){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let i=vr(t[r]);if(i)return i}let n=ib.map(r=>vr(t[r])).filter(ec);if(n.length>0)return n.join(" ")}function tc(e){let t=[],n=new Set;for(let r of e){let i=vr(r);!i||n.has(i)||(n.add(i),t.push(i))}return t}var rb,ib,nc=v(()=>{"use strict";rb=["id","source","name","label","displayName"],ib=["service","queryType","dataset","type","field","measure","vendor"]});import oc from"node:assert/strict";function ob(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function te(e,t){oc(e,`Unsupported CH render response shape: ${t}; record a Scenario before accepting this fallback.`)}function _t(e,t){oc(e,`Unsupported DV render response shape: ${t}; record a Scenario before accepting this fallback.`)}function Eo(e,t){te(Qe(t.renderParams),"widget renderParams is not an object"),te(Array.isArray(t.renderParams.controls),"widget renderParams.controls is not an array");let n=t.renderParams.controls;if(!e||typeof e!="object"||n.length===0)return e;let r=Array.isArray(e.controls)?[...e.controls]:[];for(let i of n){let o=ve(i);te(o,"widget control has no field"),te(i.value!==void 0,`widget control ${o} has no value`);let s=i.value,a=r.findIndex(u=>ve(u)===o);if(a>=0){let u=r[a];r[a]={...u,controlType:u.controlType??u.type??i.controlType??i.type,value:s}}else r.push({id:o,name:o,controlType:i.controlType??i.type??"Enum",value:s,values:i.values||[]})}return{...e,controls:r}}function sb(e){let t=e?.description;return te(typeof t=="string","chart description is not a string"),t.split(`
14
+ `).map(n=>{let r;for(let i=0;i<n.length;i++){let o=n[i];if(r&&te(o!=="\\","escaped chart expression strings are unsupported"),(o==='"'||o==="'")&&(!r||r===o)){r=r?void 0:o;continue}if(o==="#"&&!r)return n.slice(0,i)}return n}).filter(n=>{let r=n.trim();return r.length>0&&!r.startsWith("#")}).map(n=>n.trimEnd())}function ab(e,t){return e}function rc(e,t){let n=t.match(/^([+-])(\d+)(d|m|y)$/),r=Number(n[2])*(n[1]==="+"?1:-1),i=n[3];i==="y"?e.setFullYear(e.getFullYear()+r):i==="m"?e.setMonth(e.getMonth()+r):e.setDate(e.getDate()+r)}function ic(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${r}`}function ub(){return process.env.MARQUEE_NOW?new Date(process.env.MARQUEE_NOW):new Date}function db(e){let t=ub(),n=new Date(t),r=e?.relativeStartDate;if(r==="-max")n.setFullYear(n.getFullYear()-100);else if(typeof r=="string")te(/^-(\d+)(d|m|y)$/.test(r),`unsupported relativeStartDate ${r}`),rc(n,r);else{te(typeof e?.startDate=="string"&&/^\d{4}-\d{2}-\d{2}/.test(e.startDate),"chart has no supported start date");let[a,u,l]=e.startDate.slice(0,10).split("-").map(Number);n.setFullYear(a,u-1,l)}let i=new Date(t),o=e?.relativeEndDate;te(o==null||typeof o=="string"&&/^\+?(\d+)(d|m|y)$/.test(o),`unsupported relativeEndDate ${o}`),typeof o=="string"&&o.startsWith("+")&&rc(i,o);let s={Daily:"1D",Weekly:"1W",Monthly:"1M"};return te(e?.interval in s,`unsupported chart interval ${e?.interval}`),{startDate:ic(n),endDate:ic(i),interval:s[e.interval]}}function xr(e=process.env){let t=e.MARQUEE_WIDGET_RENDER_TIMEOUT_MS;if(t!==void 0&&t.trim().length>0){let n=Number(t);if(Number.isFinite(n)&&n>0)return Math.floor(n)}return cb}function lb(e){return e.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1]}function fb(e,t){return new RegExp(`(^|[^A-Za-z0-9_])${ob(t)}([^A-Za-z0-9_]|$)`).test(e)}function pb(e,t,n){return t.slice(n+1).some(r=>fb(r,e))}function gb(e,t,n){te(Qe(e.values),"result.values is not an object");let r=e.values,i=Object.keys(r).sort();return te(i.length>0,"result.values is empty"),i.length===1&&te(n?.keepSinglePoint===!0,"unlabeled single-point result is unsupported"),{text:[t],x:i,y:i.map(o=>r[o])}}function mb(e){let t=[];for(let n of e?.controls||[]){let r=n.id||n.name;if(!r)continue;te(n.value!==void 0,`chart control ${r} has no value`);let i=n.value;te(typeof n.controlType=="string",`chart control ${r} has no controlType`);let o=n.controlType;t.push({id:r,type:o,value:String(i)})}return t}async function sc(e,t){let n=sb(t);te(n.length>0,"chart has no expressions");let r=ab(n,t),{startDate:i,endDate:o,interval:s}=db(t);te(Array.isArray(t.expressions),"chart expressions metadata is not an array");let a=t.expressions.map(g=>g.label),u=mb(t),l=0,c=n.map((g,h)=>{let y=l+h,w=r[y],b=t.expressions[h],R=a[h]?.trim(),S=lb(w),C=!!b?.hide&&!R,x=!R&&!!S;return x&&te(pb(S,n,h),`terminal assignment ${S} has no label`),{labelIndex:h,resultIndex:y,explicitLabel:R,render:!C&&!x}}).filter(g=>g.render),d=await e("/v1/plots/runner",{method:"POST",body:{expressions:r,startDate:i,endDate:o,statistics:!0,realTime:!1,hints:[],variables:{},interval:s,...u.length>0?{controls:u}:{}},timeoutMs:xr()});te(Qe(d),"response is not an object"),te(Array.isArray(d.results),"results is not an array");let f=d.results,p=[];for(let g of c){let h=f[g.resultIndex];te(Qe(h),`result ${g.resultIndex} is not an object`);let y=g.explicitLabel||r[g.resultIndex];te(typeof y=="string"&&y.length>0,`result ${g.resultIndex} has no label`);let w=gb(h,y,{keepSinglePoint:!!g.explicitLabel});p.push(w)}return{data:p,warnings:[]}}async function ac(e,t,n){let r=t.underlyingChartId;_t(typeof r=="string"&&r.length>0,"widget has no underlyingChartId"),_t(Qe(t.renderParams?.component),"widget render component is not an object");let i=t.renderParams.component,o=await e(`/v1/data/visualizations/${encodeURIComponent(r)}/render`,{method:"POST",body:{component:i,visualization:{},references:{configId:n,useTableViz:!1}},timeoutMs:xr()});return _t(Qe(o),"response is not an object"),_t(Qe(o.renderData),"renderData is not an object"),_t(Array.isArray(o.renderData.data),"renderData.data is not an array"),_t(Qe(o.renderData.layout),"renderData.layout is not an object"),{data:o.renderData.data,layout:o.renderData.layout}}var cb,vo=v(()=>{"use strict";it();cb=6e4});function lc(e){return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}/.test(e)}function hb(e){let t=e[0];return!!t?.x?.length&&lc(t.x[0])}function yb(e){let t=e[0];return e.length>1&&!!t?.x?.length&&typeof t.x[0]=="string"&&!lc(t.x[0])}function Fe(e,t){return e.some(n=>n.type===t)}function $t(e){return String(e??"").replace(/<[^>]*>/g,"").trim()}function xo(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function fc(e){let t=[],n={};for(let r of e)n[r]=(n[r]??0)+1,t.push(n[r]>1?`${r}_${n[r]}`:r);return t}function kn(e){return wb.has(e)||/\bUnknown Value\b/.test(e)}function pc(e){let t=e.text?.find(i=>typeof i=="string"&&i.trim().length>0);if(!t)return;let n=$t(t).trim();if(!n||kn(n))return;let r=n.match(/^([^=]+?)\s*=/)?.[1]?.trim();return r&&!kn(r)?r:n.length<=80?n:void 0}function To(e,t,n=t,r={}){let i=new Set(t),o=t.length>e.length,s=t.length>0&&t.length<e.length,a=e.map((u,l)=>{if(u.name&&!kn(u.name))return u.name;let c=pc(u);if(r.preferMatchedTextLabels&&c&&i.has(c)||o&&c&&i.has(c)||s&&c)return c;let d=n[l]??t[l];return d&&!kn(d)?d:c||`series_${l+1}`});return fc(a.map(u=>u.trim()))}function bb(e){let t=e.trim().match(/^[A-Za-z][\w\s./-]{0,40}\s*=\s*([A-Za-z0-9_.:+/%-]+)$/);if(!t)return!1;let n=t[1];return/^[+-]?\d+(?:\.\d+)?[A-Za-z%]*$/.test(n)||/^[A-Z]{3,8}(?:[A-Z]{3})?$/.test(n)}function Rb(e){let t=e.text?.find(n=>typeof n=="string"&&n.trim().length>0);return typeof t=="string"&&bb($t(t))}function kb(e,t){if(t.length===0||e.length<=t.length)return e;let n=e.filter(r=>!Rb(r));return n.length>=t.length?n:e}function Ab(e,t){let n=[],r=[];for(let i=0;i<e.length;i+=1){let o=e[i];(o.x?.length??0)!==0&&(n.push(o),r.push(i))}return t.length!==e.length?{traces:n,seriesLabels:t}:{traces:n,seriesLabels:r.map(i=>t[i]??"")}}function Sb(e){let t=e.find(s=>s.type==="treemap"&&s.labels?.length);if(!t)return;let n=t.labels??[],r=t.parents??[],i=t.values??[],o=n.map((s,a)=>({label:$t(String(s)),parent:String(r[a]??""),value:i[a]}));return{summary:`treemap, ${o.length} nodes`,columns:["label","parent","value"],rows:o}}function Cb(e){let t=e.find(a=>a.type==="sankey"&&a.node?.label?.length);if(!t)return;let n=(t.node?.label??[]).map(String),r=t.link?.source??[],i=t.link?.target??[],o=t.link?.value??[],s=r.map((a,u)=>({source:n[Number(a)]??String(a),target:n[Number(i[u])]??String(i[u]),value:o[u]}));return{summary:`sankey, ${n.length} nodes x ${s.length} links`,columns:["source","target","value"],rows:s}}function Eb(e){let t=e.filter(r=>r.type==="scatter3d"&&(r.x?.length??0)>0);if(t.length===0)return;let n=[];for(let r of t){let i=r.x??[],o=r.y??[],s=r.z??[],a=r.text??[];for(let u=0;u<i.length;u+=1)n.push({label:a[u]??r.name??"",x:i[u],y:o[u],z:s[u]})}return{summary:`scatter3d, ${t.length} series, ${n.length} points`,columns:["label","x","y","z"],rows:n}}function vb(e){let t=e.match(/<a\b[^>]*\bhref=(["'])(.*?)\1/i);if(!t)return;let n=xo(t[2]);return n.startsWith("/")?`https://marquee.gs.com${n}`:n}function xb(e){if(e)try{return new URL(e).searchParams.get("quickEntryText")??void 0}catch{return}}function Ib(e){if(!e||typeof e!="object")return;let t=e.text;if(typeof t!="string"||!t.includes("visualstructuring"))return;let n=t.match(/<b>(.*?)<\/b>/i),r=n?xo($t(n[1])):void 0;if(!r)return;let i=vb(t),o=xo($t(t.replace(/<br\s*\/?>/gi," "))).replace(/\s+/g," ").trim(),s=o.startsWith(r)?o.slice(r.length).trim():o,a=s.match(/^([★✬✩☆]+)\s+([A-Za-z][A-Za-z\s/%-]*):\s*(.+)$/),u={strategy:r};if(a){let c=a[2].trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");u.rating=a[1],u[c||"value"]=a[3].trim(),c==="price"&&(u.premium=a[3].trim())}else s&&(u.detail=s);i&&(u.visualStructuringLink=i);let l=xb(i);return l&&(u.quickEntryText=l),u}function Db(e){let t=Array.isArray(e.annotations)?e.annotations:[],n=[],r=new Set;for(let o of t){let s=Ib(o);if(!s)continue;let a=String(s.visualStructuringLink??s.strategy);r.has(a)||(r.add(a),n.push({rank:n.length+1,...s}))}if(n.length===0)return;let i=["rank","strategy"];for(let o of["rating","price","premium","volatility","skew","carry","detail"])n.some(s=>s[o]!==void 0)&&(o!=="premium"||!i.includes("price"))&&i.push(o);return{summary:`strategy table, ${n.length} rows`,columns:i,rows:n}}function Tb(e){return typeof e=="string"&&e.includes("<")?e.replace(/<br\s*\/?>/gi,", ").replace(/<[^>]*>/g,"").trim():e}function Pb(e){let t=e.find(s=>s.type==="table"&&s.cells?.values?.length);if(!t)return;let n=fc((t.header?.values??[]).map((s,a)=>{let u=$t(s);return u.length>0?u:`column_${a+1}`})),r=t.cells?.values??[],i=r[0]?.length??0,o=Array.from({length:i},(s,a)=>{let u={};for(let l=0;l<n.length;l+=1)u[n[l]]=Tb(r[l]?.[a]??null);return u});return{summary:`table, ${n.length} columns x ${i} rows`,columns:n,rows:o}}function _b(e,t,n=t){let r=e.filter(a=>(a.r?.length??0)>0);if(r.length===0)return;let i=To(r,t,n),o=[...new Set(r.flatMap(a=>(a.theta??[]).map(String)))],s=o.map(a=>{let u={axis:a};for(let l=0;l<r.length;l+=1){let c=r[l],d=(c.theta??[]).findIndex(f=>String(f)===a);u[i[l]]=d>=0?c.r?.[d]:null}return u});return{summary:`radar, ${r.length} series, ${o.length} points`,columns:["axis",...i],rows:s}}function uc(e,t){let n=e.find(a=>a.type===t&&a.z?.length);if(!n)return;let r=(n.x??[]).map(String),i=(n.y??[]).map(String),o=n.z??[],s=i.map((a,u)=>{let l={"":a},c=o[u]??[];for(let d=0;d<r.length;d+=1)l[r[d]]=c[d]??null;return l});return{summary:`${t}, ${r.length} x ${i.length}`,columns:["",...r],rows:s}}function $b(e){let t=e.filter(i=>i.type==="bar"&&(i.x?.length??0)>0);if(t.length===0)return;let n=t.length>1,r=[];for(let i of t){let o=i.orientation==="h",s=o?i.y??[]:i.x??[],a=o?i.x??[]:i.y??[];for(let u=0;u<s.length;u+=1){let l={category:s[u],value:a[u]};n&&(l.series=i.name??""),r.push(l)}}return{summary:`bar, ${r.length} categories`,columns:n?["category","value","series"]:["category","value"],rows:r}}function Ob(e,t,n){let r=e.y??[];if(r.length>3||r.length===0||t<5||r.length>=t*.5||r.length<=1&&n)return!1;let i=r[0];return r.every(o=>o===i)}function Mb(e){let t=e.y??[];return t.length===0?!1:t.every(n=>n===0||n===1)}function Wb(e,t,n){return Ob(e,t,n)||Mb(e)}function Lb(e,t=[]){let n=Math.max(...e.map(i=>i.x?.length??0)),r=e.filter((i,o)=>{let s=!!(i.name||i.text?.[0]||t[o]);return!Wb(i,n,s)});return r.length>0?r:e}function dc(e,t){return!e||!t||e.length!==t.length?!1:e.every((n,r)=>Object.is(n,t[r]))}function Io(e){return e.type==="scatter"||e.type==="scattergl"}function Do(e,t){return(e.mode??"").split("+").map(n=>n.trim()).includes(t)}function gc(e){return Do(e,"markers")&&!Do(e,"lines")}function qb(e){return Do(e,"lines")}function cc(e){let t=e.name?.trim();return t&&!kn(t)?t:pc(e)}function Fb(e,t){return Io(e)&&Io(t)&&qb(e)&&gc(t)&&t.showlegend===!1&&dc(e.x,t.x)&&dc(e.y,t.y)}function Nb(e){let t=e.filter((n,r)=>{let i=cc(n);return!i||!Io(n)||!gc(n)||n.showlegend!==!1?!0:!e.some((o,s)=>s!==r&&cc(o)===i&&Fb(o,n))});return t.length>0?t:e}function Ub(e,t,n=t){let r=Po(e,t),i=To(r,t,n,{preferMatchedTextLabels:r.length<e.length}),s=[...new Set(r.flatMap(a=>(a.x??[]).map(String)))].sort().map(a=>{let u={date:a};for(let l=0;l<r.length;l+=1){let c=r[l],d=(c.x??[]).findIndex(f=>String(f)===a);u[i[l]]=d>=0?c.y?.[d]:null}return u});return{summary:`time series, ${r.length} series, ${s.length} points`,columns:["date",...i],rows:s}}function Po(e,t=[]){return Nb(Lb(e,t))}function jb(e,t,n,r=n){let i=t.xaxis?.title?.text||"category",o=(e[0]?.x??[]).map(String),s=To(e,n,r),a=o.map((u,l)=>{let c={[i]:u};for(let d=0;d<e.length;d+=1)c[s[d]]=e[d].y?.[l]??null;return c});return{summary:`box plot, ${e.length} series, ${o.length} points`,columns:[i,...s],rows:a}}function Vb(e,t,n,r=n){let i=t.xaxis?.title?.text??"x",o=t.yaxis?.title?.text??"y",s=e.some(l=>(l.text?.length??0)>0)?"cross":"series",a=[];for(let l=0;l<e.length;l+=1){let c=e[l],d=c.x??[],f=c.y??[],p=c.text??[];for(let g=0;g<d.length;g+=1)d[g]==null||f[g]==null||a.push({[s]:p[g]??c.name??r[l]??n[l]??"",[i]:d[g],[o]:f[g]})}let u=a.some(l=>l[s]!=="");return{summary:`scatter, ${e.length} series, ${a.length} points`,columns:u?[s,i,o]:[i,o],rows:a}}function Gb(e){return e.type==="scatter"||e.type==="scattergl"}function ut(e,t,n={}){let r=n.seriesLabels??[],i=Db(t);if(i&&(e.length===0||e.every(Gb)))return i;if(e.length===0)return;if(Fe(e,"treemap")){let u=Sb(e);if(u)return u}if(Fe(e,"sankey")){let u=Cb(e);if(u)return u}if(Fe(e,"scatter3d")){let u=Eb(e);if(u)return u}if(Fe(e,"table")){let u=Pb(e);if(u)return u}if(Fe(e,"scatterpolar")){let u=_b(e,r);if(u)return u}if(Fe(e,"heatmap")){let u=uc(e,"heatmap");if(u)return u}if(Fe(e,"surface")){let u=uc(e,"surface");if(u)return u}if(Fe(e,"bar")&&!Fe(e,"scatter")){let u=$b(e);if(u)return u}let o=Ab(e,r),s=kb(o.traces,o.seriesLabels),a=o.seriesLabels;return s.length===0?i:hb(s)?Ub(s,r,a):yb(s)?jb(s,t,r,a):i||Vb(s,t,r,a)}var wb,An=v(()=>{"use strict";wb=new Set(["Unknown Value"])});function _o(e){return e.startsWith("CH")?"CH":e.startsWith("DV")?"DV":"unknown"}function mc(e){return String(e??"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Bb(e,t){if(!e||typeof e!="object")return!1;let n=e,r=mc(t);return[n.id,n.field,n.name,n.label].map(mc).filter(o=>o.length>0).includes(r)}function Ir(e){return e==null?"":Array.isArray(e)?e.map(Ir).join(", "):typeof e=="object"?JSON.stringify(e):String(e)}function hc(e,t){return!ir.test(e)&&!/\bUnknown Value\b/.test(e)&&!rr(e,t)&&!/\bMA[A-Z0-9]{10,}\b/.test(e)}function Hb(e,t,n){return e.replace(/<\s*([^:<>]+)\s*:\s*([^<>]+?)\s*>/g,(r,i,o)=>{let s=o.trim();if(n[s])return n[s];let a=(t?.controls||[]).find(u=>Bb(u,i));if(a&&typeof a=="object"){let u=a,l=u.value??u.defaultValue;if(l!==void 0)return Ir(ie(l,n))}return s})}function yc(e,t,n){let r=Hb(e,t,n).trim();return Ir(ie(r,n)).trim()}async function $o(e,t,n,r,i,o,s,a=!1,u){let l=String(t.underlyingChartId??""),c=l.startsWith("DV"),f=s&&Object.prototype.hasOwnProperty.call(s,"chart")?Promise.resolve(Eo(s.chart??{},t)):!c&&l&&s?.chartEnrichment!=="skip"?e(`/v1/charts/${encodeURIComponent(l)}`).then(J=>Eo(J,t)):Promise.resolve({}),p=s?.entityResolution==="fallback",g=p?new Set:Jd(t),h=p?new Set:Kd(t),y=s?.entityResolution==="provided"?Promise.resolve({entityMap:s.entityMap??{},cgMembers:s.cgMembers??{}}):Du(e,g,{entityMap:s?.entityMap,cgMembers:s?.cgMembers},{countryIds:h}),w=o?Promise.resolve(o):i?c?ac(e,t,r):l?f.then(J=>sc(e,J).then(Um=>({data:Um.data,layout:{}}))):Promise.resolve({data:[],layout:{}}):Promise.resolve({data:[],layout:{}}),b=new AbortController,R=u?u(b.signal):Promise.resolve(void 0),S=Promise.all([f,y,w]);S.catch(()=>b.abort());let[[C,x,E],j]=await Promise.all([S,R.catch(J=>{if(!b.signal.aborted)throw J})]),D=E.data,{entityMap:A,cgMembers:I}=x,O=Xd(Qd({widget:t,entityMap:A,cgMembers:I,chart:C,isDV:c}),t),M=(t.metadata?.expressionLabels||[]).map(J=>(J||"").trim()).filter(J=>J.length>0),V=(M.length>0?M:(C.expressions||[]).map(J=>J.label).filter(J=>J&&J.length>0)).map(J=>yc(String(J),C,A)).filter(J=>J.length>0),G=!c&&t.contextParameter&&!t.contextParameter.field&&(t.contextParameter.options||[]).length>0?(t.contextParameter.options||[]).map(J=>Ir(ie(J,A)).trim()):[],W=G.map(J=>yc(J,C,A)).filter(J=>J.length>0),K=Array.isArray(D)?D.length:0,z=W.length>0&&W.every(J=>hc(J,A)),L=(a&&z?W:zd(K,V,G)).filter(J=>hc(J,A)),q=K>0&&L.length!==K?[]:L,U=tc([...t.metadata?.dataSources||[],...t.dataAttribution||[]]),H=Object.keys(E.layout).length>0?E.layout:t.renderData?.layout&&typeof t.renderData.layout=="object"?t.renderData.layout:{},Ce=at(t.metadata?.title)||at(t.title),pe=q.length>0?q:void 0,Pe=ut(D,H,{seriesLabels:pe??[]}),Va=Pe?.rows??[],Ga={id:n,title:Ce,configurationId:r,...l?{chartId:l}:{},chartKind:_o(l),link:`https://marquee.gs.com/s/marketview/widget/${n}${r?`?config=${r}`:""}`,...typeof at(t.description)=="string"&&at(t.description).length>0?{description:at(t.description)}:{},...Array.isArray(t.tags)?{tags:t.tags.map(String)}:{},...U.length>0?{sources:U}:{}};return{view:{widget:Ga,params:O,data:{traces:D,layout:H,...pe?{labels:pe}:{},rows:Va,...Pe?{rowModel:{summary:Pe.summary,columns:Pe.columns}}:{}},...j?{dashboards:j}:{},refs:{},evalPayload:{widget:Ga,params:O,rows:Va}},warnings:[]}}var wc=v(()=>{"use strict";Xi();At();sr();Co();nc();vo();Ao();An()});function Oo(e){if(Array.isArray(e)){if(e.length===0)return"[]";let n=e.slice(0,3).map(i=>Oo(i)),r=e.length>3?`, +${e.length-3} more`:"";return`[${n.join(", ")}${r}]`}if(typeof e=="object"&&e!==null){let n=Object.entries(e);if(n.length===0)return"{}";let r=n.slice(0,2).map(([o,s])=>`${o}:${Oo(s)}`),i=n.length>2?", ...":"";return`{${r.join(", ")}${i}}`}let t=String(e);return t.length>20||/^[A-Z0-9]{15,}$/.test(t)?"...":t}function Yb(e){return Array.isArray(e)?m(e[0])?e[0]:void 0:m(e)&&Array.isArray(e.results)?m(e.results[0])?e.results[0]:void 0:m(e)?e:void 0}function Ot(e){return e==null?"":String(e).trim()}function Kb(e){if(m(e)){for(let t of[e.id,e.field,e.name])if(typeof t=="string"&&t.length>0)return t}}function Qb(e){return Object.prototype.hasOwnProperty.call(e,"value")?e.value:Object.prototype.hasOwnProperty.call(e,"defaultValue")?e.defaultValue:(m(e.values)?e.values:void 0)?.default}function Tr(e){throw new Error(`Unsupported widget module response shape: ${e}; record a Scenario before accepting this fallback.`)}function Zb(e){let t=e.parameters;return t==null?[]:Array.isArray(t)?t.map((n,r)=>m(n)?n:Tr(`configuration.parameters[${r}] is not a record`)):Tr("configuration.parameters is not an array")}function Xb(e){let t=e.renderParams;return t==null?{}:m(t)?t:Tr("widget.renderParams is not a record")}function eR(e){let t=e.controls;return t==null?[]:Array.isArray(t)?[...t]:Tr("widget.renderParams.controls is not an array")}function tR(e,t){if(!(Ot(t.underlyingChartId)||Ot(e.underlyingChartId)).startsWith("CH"))return;let r=Zb(t);if(r.length===0)return;let i=Xb(e),o=eR(i),s=new Set;for(let u of o){let l=Kb(u);l&&s.add(l)}let a=!1;for(let u of r){let l=typeof u.field=="string"&&u.field.length>0?u.field:void 0,c=Qb(u);!l||c===void 0||s.has(l)||(o.push({id:l,value:c,...typeof u.type=="string"?{type:u.type}:{},...typeof u.controlType=="string"?{controlType:u.controlType}:{},__marqueeSource:fo}),s.add(l),a=!0)}return a?{...i,controls:o}:void 0}function Mo(e,t){let n=m(t.metadata)?t.metadata:{},r=Ot(n.title)||Ot(t.title),i=tR(e,t);return{...e,...typeof t.id=="string"?{configurationId:t.id}:{},...typeof t.underlyingChartId=="string"?{underlyingChartId:t.underlyingChartId}:{},...r?{title:r}:{},...i?{renderParams:i}:{},metadata:{...m(e.metadata)?e.metadata:{},...n,...r?{title:r}:{}}}}async function Wo(e,t){let n=await e("/v1/marketview/widgets/configurations",{method:"GET",query:{id:t}}),r=Yb(n);if(!r)throw new Error(`Config detail returned empty response for ${t}`);return r}async function Pr(e,t,n,r){let i=e(`/v1/marketview/widgets/${encodeURIComponent(t)}`,{method:"GET",query:{mergeParams:!0,...n?{context:n}:{}},hedgeDelaysMs:[1e3]}),o;if(r?.configDetail===!0&&n){let[l,c]=await Promise.all([i,Wo(e,n)]);o=Mo(Le(l),c)}else if(r?.configDetail===!1||!n)o=Le(await i);else{o=Le(await i);let l=Ot((m(o.metadata)?o.metadata.title:void 0)??o.title);if(bn(l)){let c=await Wo(e,n);o=Mo(o,c)}}let s=ko(o),a=Ot((m(s.metadata)?s.metadata.title:void 0)??s.title),u=Ye(s);return{title:a,paramNames:u,configurationId:n,raw:s}}function nR(e){if(!m(e)||!Array.isArray(e.results))throw new T("http","Malformed dashboard list response: expected results array",{path:"/v1/marketview/dashboards"});return e.results.map((t,n)=>{if(!m(t)||typeof t.id!="string"||typeof t.title!="string")throw new T("http",`Malformed dashboard list response: expected dashboard id and title strings at results[${n}]`,{path:"/v1/marketview/dashboards"});return{...t,id:t.id,title:t.title}})}async function bc(e,t){let n=await e("/v1/marketview/dashboards",{method:"GET",query:{view_as:"edit",size:100,page:1},timeoutMs:zb,hedgeDelaysMs:Jb,signal:t});return nR(n)}function Ne(e){return e.calls.map(t=>({method:t.request.method,path:t.request.path,ms:t.ms,status:t.status==="error"?"error":"ok"}))}function Dr(e){return e.length>200?e.slice(0,200):e}function rR(e,t){if(typeof e=="string"&&e.length>0)return Dr(e);try{return Dr(JSON.stringify(e)??t)}catch{return Dr(t)}}function iR(e){if(!e||e.length===0)return"";try{let t=JSON.parse(e);if(m(t)){let n=t.errorMessages??t.errors??t.messages??t.message;if(Array.isArray(n)&&n.length>0)return n.map(String).join("; ");if(typeof n=="string"&&n.length>0)return n;if(typeof t.error=="string"&&t.error.length>0)return t.error;if(typeof t.detail=="string"&&t.detail.length>0)return Dr(e)}return rR(t,e)}catch{return"Malformed upstream error body"}}function oR(e){let t=["","v1","data","visualizations",""].join("/");return e.includes(t)&&e.endsWith("/render")?`DV render endpoint ${e}`:e.includes("/v1/plots/runner")?`CH runner endpoint ${e}`:`upstream path ${e}`}function Rc(e,t,n){let r=e instanceof T?e.details?.path:void 0,i=r??t;if(e instanceof T&&e.details?.status===403&&n&&i!=="/v1/marketview/dashboards")return{code:"ACCESS_DENIED",httpStatus:403,message:`Access denied: widget ${n}`};let o=e instanceof Error?e.message:String(e),s=e instanceof T?iR(e.details?.body):"",a=r&&!o.includes(r)?oR(r):"",u=a?`${o} at ${a}`:o,l=s?`${u} \u2014 ${s}`:u;return{code:"UPSTREAM",...e instanceof T&&e.details?.status?{httpStatus:e.details.status}:{},path:r??t,message:l}}function kc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ac(e,t){return e.some(n=>kc(n,t))}function sR(e){let t=e.findIndex(s=>s.field==="columns"),n=e.findIndex(s=>s.field==="sortBy");if(t<0||n<0)return e;let r=e[t].value,i=e[n].value;return!Array.isArray(r)||i===void 0||i===null||Ac(r,i)?e:e[e.length-1]?.field==="columns"&&r.length>0?e.map((s,a)=>a===n?{...s,value:r[0]}:s):e.map((s,a)=>a===t?{...s,value:[...r,i]}:s)}function aR(e,t){let n=e.columns,r=e.sortBy;return!Array.isArray(n)||r===void 0||r===null||Ac(n,r)?e:t==="columns"&&n.length>0?{...e,sortBy:n[0]}:{...e,columns:[...n,r]}}function uR(e){return e?.id||e?.field||e?.name}function dR(){return{code:"INVALID_PARAM",field:"surveyDate",message:Zd}}function cR(e,t){let n=e.renderParams&&typeof e.renderParams=="object"?e.renderParams:{},r=Array.isArray(n.controls)?n.controls.map(i=>{let o=uR(i);return(o==="columns"||o==="sortBy")&&Object.prototype.hasOwnProperty.call(t,o)?{...i,value:t[o],defaultValue:t[o]}:i}):void 0;return{...e,renderParams:{...n,...r?{controls:r}:{},component:t}}}function Mt(e){return{async read(t){let n=t.source.kind==="raw-widget"?Le(t.source.widget):t.source.prefetchedWidget?Le(t.source.prefetchedWidget):void 0,r=t.source.kind==="raw-widget"?String(t.source.id??n?.id??""):t.source.id;if(!r)return{ok:!1,error:{code:"UPSTREAM",message:"Widget id is required"},warnings:[],apiCalls:[]};let i=t.source.contextId,o=t.mode!=="summary"&&t.data!=="skip",s=go(r,i),a=mo((u,l)=>e.request(u,l),s);try{let l=n??Le(await a(`/v1/marketview/widgets/${encodeURIComponent(r)}`,{method:"GET",query:{mergeParams:!0,...i?{context:i}:{}},hedgeDelaysMs:[1e3]})),c=typeof i=="string"&&i.startsWith("WC"),d=(c?i:"")||l.configurationId||"";if(!d&&!(t.mode==="summary"&&t.source.kind==="raw-widget")){let y=String(l.underlyingChartId??""),w=l.contextParameter?.field,b=l.contextParameter?.options||[],R=w?mn(l,w,b):void 0,S=w&&R?[{field:w,value:R}]:[],C=await a("/v1/marketview/widgets/configurations",{method:"POST",body:{widgetId:r||l.id,underlyingChartId:y,parameters:S}});if(d=Rn(C),!d)return{ok:!1,error:{code:"CONFIGURATION_MISSING_ID",widgetId:r,message:"Widget configuration creation did not return id"},warnings:[],apiCalls:Ne(s),audit:s}}if(t.source.kind!=="raw-widget"&&!t.skipConfigDetail&&c&&d){let y=await Wo(a,d);l=Mo(l,y)}l=ko(l);let f=String(l.underlyingChartId??""),p=f.startsWith("DV");s.renderKind=p?"DV":f.startsWith("CH")?"CH":"unknown";let{view:g,warnings:h}=await $o(a,l,r,d,o,void 0,t.summaryContext,t.mode==="summary",t.editableDashboards==="fetch"?y=>bc(a,y):void 0);return t.editableDashboards==="fetch"&&g.dashboards!==void 0&&(s.dashboards=g.dashboards),t.mode==="audit"?{ok:!0,value:{mode:"audit",audit:s},warnings:h,apiCalls:Ne(s),audit:s}:{ok:!0,value:{mode:t.mode,view:g,audit:s},warnings:h,apiCalls:Ne(s),audit:s}}catch(u){return{ok:!1,error:Rc(u,s.calls[s.calls.length-1]?.request.path,r),warnings:[],apiCalls:Ne(s),audit:s}}},async change(t){let n=go(t.id,t.contextId),r=mo((s,a)=>e.request(s,a),n),i=t.params[t.params.length-1]?.field,o=t.params.map(s=>`${s.field}=${Oo(s.displayValue??s.value)}`).join(", ");try{let s=Le(await r(`/v1/marketview/widgets/${encodeURIComponent(t.id)}`,{method:"GET",query:{mergeParams:!0,...t.contextId?{context:t.contextId}:{}},hedgeDelaysMs:[1e3]})),a=String(s.underlyingChartId??"");if(n.renderKind=_o(a),!a.startsWith("CH")&&!a.startsWith("DV"))return{ok:!1,error:{code:"UPSTREAM",message:`Widget param change failed: unsupported chart id ${a||"(missing)"}`},warnings:[],apiCalls:Ne(n),audit:n};let u=s.renderParams?.component,l=u&&typeof u=="object"?Object.entries(u).find(([C])=>Er(C))?.[1]:void 0,c=t.params.some(C=>Er(C.field)&&!kc(C.value,l));if(So(s)&&c)return{ok:!1,error:dR(),warnings:[],apiCalls:Ne(n),audit:n};let d=a.startsWith("DV")?sR(t.params):t.params,f=d.find(C=>/^relative\s+date$/i.test(String(C.field??"").trim())),p=f!==void 0&&typeof f.value=="string",g=await r("/v1/marketview/widgets/configurations",{method:"POST",body:{parameters:(p?d.filter(C=>C!==f):d).map(({field:C,value:x})=>({field:C,value:x})),widgetId:t.id,underlyingChartId:a,...p?{relativeDate:f.value.toLowerCase()}:{}}}),h=Rn(g);if(!h)return{ok:!1,error:{code:"CONFIGURATION_MISSING_ID",widgetId:t.id,message:"Widget configuration creation did not return id"},warnings:[],apiCalls:Ne(n),audit:n};let y=Le(await r(`/v1/marketview/widgets/${encodeURIComponent(t.id)}`,{method:"GET",query:{mergeParams:!0,context:h},hedgeDelaysMs:[1e3]})),w,b=y;if(a.startsWith("DV")){let C=aR(y.renderParams?.component||{},i);b=cR(y,C);let x=await r(`/v1/data/visualizations/${encodeURIComponent(a)}/render`,{method:"POST",body:{component:C,visualization:{},references:{configId:h,useTableViz:!1}},timeoutMs:xr()}),E=x?.renderData?.layout&&typeof x.renderData.layout=="object"?x.renderData.layout:{};w={data:x?.renderData?.data||[],layout:E}}let{view:R,warnings:S}=await $o(r,b,t.id,h,!w,w,void 0,!1,t.editableDashboards==="fetch"?C=>bc(r,C):void 0);return t.editableDashboards==="fetch"&&R.dashboards!==void 0&&(n.dashboards=R.dashboards),{ok:!0,value:R,warnings:S,apiCalls:Ne(n),audit:n}}catch(s){let a=Rc(s,n.calls[n.calls.length-1]?.request.path,t.id),u=o?`Widget param change failed (${o}) \u2014 `:"";return{ok:!1,error:{...a,message:`${u}${a.message}`},warnings:[],apiCalls:Ne(n),audit:n}}}}}var zb,Jb,Wt=v(()=>{"use strict";ge();$e();ho();Ao();it();Q();wc();Co();vo();$e();zb=4e3,Jb=[1e3]});var Ec={};Y(Ec,{default:()=>wR});function Sc(e){return e??10}function pR(e){return Array.isArray(e)?e:[]}function Cn(e,t){if(!e)throw new Error(`Unsupported MarketView search response shape: ${t}; record a Scenario before accepting this fallback.`)}function Cc(e,t){return Cn(m(e),t),e}function Lt(e,t){return Cn(typeof e=="string"&&e.trim().length>0,t),e}function gR(e,t){return Cn(Array.isArray(e),t),e}function mR(e,t){let n=Lt(e,t);return Cn(n.startsWith("/"),t),`https://marquee.gs.com${n}`}function hR(e){return Cc(e.resultsMap,"missing resultsMap")}function Ue(e,t){return e[t]??[]}function Sn(e,t){return Cc(e.data,`${t} entry missing data`)}async function bR(e,t){let n=e.filter(i=>i.type==="widget"&&i.paramNames);if(n.length===0)return;let r=await Promise.all(n.slice(0,lR).map(async i=>({item:i,snippet:await Pr(t,i.id,i.configurationId)})));for(let{item:i,snippet:o}of r)o.title&&(i.title=o.title),o.paramNames.length>0&&(i.paramNames=o.paramNames)}var lR,fR,yR,wR,vc=v(()=>{"use strict";Wt();$e();Q();lR=10,fR=[1e3];yR={name:"marketview.search",columns:["type","id","title","relevance"],request:e=>({method:"GET",path:"/v1/marketview/search",query:{query:e.query,types:e.types,limit:Sc(e.limit),useNewSchema:e.useNewSchema,combineSearchResults:!1},hedgeDelaysMs:fR}),transform:async({raw:e,request:t,args:n})=>{let r=e,i=[],o=new Set,s=pR(n.types),a=(w,b,R,S)=>{let C=Lt(w,`${R} entry missing id`),x=Lt(b,`${R} entry missing title`);Cn(!o.has(C),`duplicate id ${C}`);let E={id:C,title:x.trim(),type:R};return o.add(C),S!=null&&(E.relevance=S),i.push(E),E},u=w=>{let b=Sn(w,"dashboards"),R=a(b.id,b.title,"thematic-dashboard",b.relevance);R.dashboardType=Lt(b.type,"dashboards entry missing type"),R.widgetCount=gR(b.children,"dashboards entry missing children").length;let S=Lt(b.alias,"dashboards entry missing alias");R.url=`https://marquee.gs.com/s/marketview/dashboards/${encodeURIComponent(S)}`},l=w=>{let b=Sn(w,"assets"),R=a(b.id,b.name,"asset-dashboard",b.relevance);typeof b.assetClass=="string"&&(R.assetClass=b.assetClass),typeof b.type=="string"&&b.type!=="Asset"&&(R.assetType=b.type),typeof b.ticker=="string"&&(R.ticker=b.ticker),typeof b.bbid=="string"&&(R.bbid=b.bbid),R.url=mR(b.url,"assets url is not slash-relative")},c=w=>{let b=Sn(w,"countries"),R=a(b.id,b.name,"country-dashboard",b.relevance);typeof b.region=="string"&&(R.region=b.region),typeof b.subRegion=="string"&&(R.subRegion=b.subRegion),R.url=`https://marquee.gs.com/s/marketview/country/${R.id}`},d=w=>{let b=Sn(w,"portfolios"),R=a(b.id,b.name,"portfolio-dashboard",b.relevance);typeof b.currency=="string"&&(R.currency=b.currency),R.url=`https://marquee.gs.com/s/marketview/portfolio/${R.id}`},f=(w,b)=>{w.paramNames=Ye(b)},p=w=>{let b=Sn(w,"widgets"),R=a(b.id,b.metadata?.title??b.title,"widget",b.relevance);f(R,b),R.configurationId=Lt(b.configurationId,"widgets entry missing configurationId")},g=hR(r),h=s.includes("Widget Ranked"),y=Ue(g,"widgets_ranked").length>0;return h&&y||(Ue(g,"widgets").forEach(p),Ue(g,"widgets_llm").forEach(p)),Ue(g,"widgets_ranked").forEach(p),Ue(g,"dashboards").forEach(u),Ue(g,"assets").forEach(l),Ue(g,"countries").forEach(c),Ue(g,"portfolios").forEach(d),i.splice(Sc(n.limit)),await bR(i,t),i}},wR=yR});var xc={};Y(xc,{default:()=>kR});var RR,kR,Ic=v(()=>{"use strict";Wt();RR={name:"marketview.widget-change",columns:[],steps:[{name:"module",request:()=>null}],async transform({args:e,request:t}){return Mt({request:t}).change(e)}},kR=RR});var Tc={};Y(Tc,{default:()=>ER});function Dc(e){return m(e)&&m(e.metadata)?e.metadata:void 0}function AR(e){let t=Dc(e);return typeof t?.title=="string"&&t.title.trim()?t.title:m(e)&&typeof e.title=="string"&&e.title.trim()?e.title:void 0}function SR(e){return Array.isArray(e)?e[0]:e}var CR,ER,Pc=v(()=>{"use strict";ho();Q();CR={name:"marketview.widget-configure",columns:["id"],request:({id:e,underlyingChartId:t,parameters:n=[]})=>({method:"POST",path:"/v1/marketview/widgets/configurations",body:{widgetId:e,underlyingChartId:t,parameters:n},hedgeDelaysMs:[500,1250]}),transform:({raw:e})=>{let t=SR(e),n=Dc(t),r=AR(t);return{id:Rn(e),...r?{title:r}:{},...n?{metadata:n}:{}}}},ER=CR});var _c={};Y(_c,{default:()=>xR});var vR,xR,$c=v(()=>{"use strict";Wt();vR={name:"marketview.widget-load",columns:["field","display","default"],formatError:(e,t)=>t===403?`Access denied: widget ${e.id}`:void 0,steps:[{name:"module",request:()=>null}],async transform({args:e,request:t,apiCalls:n}){let i=await Mt({request:t}).read({source:{kind:"id",id:e.id,contextId:e.context},mode:"view",data:e.includeData===!1?"skip":"render"});if(!i.ok)throw new Error(i.error.message);let o=i.value;if(o.mode==="audit")return{params:[],chartId:"",configurationId:"",audit:o.audit};let s=o.view;return{params:s.params,chartId:s.widget.chartId??"",configurationId:s.widget.configurationId,labels:s.data.labels??[],sources:s.widget.sources??[],warnings:i.warnings,audit:i.audit,apiCalls:n?.().length??0,gqlData:{title:s.widget.title,description:s.widget.description??"",tags:s.widget.tags??[],expressionLabels:s.data.labels??[],layout:s.data.layout,data:s.data.traces},id:e.id}}},xR=vR});var Oc={};Y(Oc,{default:()=>DR});var IR,DR,Mc=v(()=>{"use strict";Wt();IR={name:"marketview.widget-read",columns:[],steps:[{name:"module",request:()=>null}],async transform({args:e,request:t}){return Mt({request:t}).read(e)}},DR=IR});var Wc={};Y(Wc,{default:()=>PR});var TR,PR,Lc=v(()=>{"use strict";Wt();TR={name:"marketview.widget-snippet",columns:[],steps:[{name:"module",request:()=>null}],async transform({args:e,request:t}){let n=await Pr(t,e.widgetId,e.configurationId,e.configDetail!==void 0?{configDetail:e.configDetail}:void 0);return{title:n.title,paramNames:n.paramNames,configurationId:n.configurationId??e.configurationId}}},PR=TR});import{existsSync as _R}from"node:fs";import{dirname as $R,join as Lo}from"node:path";import{fileURLToPath as OR,pathToFileURL as MR}from"node:url";async function qo(e,t,n=qc){if(n===qc){let i=WR.get(`${e}.${t}`);return i?Fc(await i(),t):null}let r=[Lo(n,e,`${t}.js`),Lo(n,e,`${t}.mjs`),Lo(n,e,`${t}.ts`)];for(let i of r)if(_R(i))try{let o=await import(MR(i).href),s=Fc(o,t);if(s)return s}catch(o){throw new T("adapter",`Failed to import adapter ${i}: ${o instanceof Error?o.message:String(o)}`,{adapter:i})}return null}function Fc(e,t){let n=e.default??e[t];return n&&typeof n=="object"&&"name"in n&&typeof n.name=="string"?n:null}var qc,WR,Nc=v(()=>{"use strict";ge();qc=$R(OR(import.meta.url)),WR=new Map([["asset.resolve",()=>Promise.resolve().then(()=>(Za(),Qa))],["asset.search",()=>Promise.resolve().then(()=>(eu(),Xa))],["content.get",()=>Promise.resolve().then(()=>(du(),uu))],["content.search",()=>Promise.resolve().then(()=>(Ru(),bu))],["marketview.asset-identity",()=>Promise.resolve().then(()=>(Au(),ku))],["marketview.asset-options",()=>Promise.resolve().then(()=>($u(),_u))],["marketview.asset",()=>Promise.resolve().then(()=>(qu(),Lu))],["marketview.dashboard-add-widget",()=>Promise.resolve().then(()=>(Gu(),Vu))],["marketview.dashboard-create-section",()=>Promise.resolve().then(()=>(zu(),Hu))],["marketview.dashboard-create-with-widget",()=>Promise.resolve().then(()=>(Ku(),Yu))],["marketview.dashboard-delete-section",()=>Promise.resolve().then(()=>(Zu(),Qu))],["marketview.dashboard-find-by-title",()=>Promise.resolve().then(()=>(td(),ed))],["marketview.dashboard-raw",()=>Promise.resolve().then(()=>(rd(),nd))],["marketview.dashboard-remove-widget",()=>Promise.resolve().then(()=>(od(),id))],["marketview.dashboard-set-section",()=>Promise.resolve().then(()=>(ad(),sd))],["marketview.dashboard-update-widget-configuration",()=>Promise.resolve().then(()=>(md(),gd))],["marketview.dashboard",()=>Promise.resolve().then(()=>(Sd(),Ad))],["marketview.discover",()=>Promise.resolve().then(()=>(vd(),Ed))],["marketview.filter-constituents",()=>Promise.resolve().then(()=>(Id(),xd))],["marketview.preferences",()=>Promise.resolve().then(()=>(Td(),Dd))],["marketview.search",()=>Promise.resolve().then(()=>(vc(),Ec))],["marketview.widget-change",()=>Promise.resolve().then(()=>(Ic(),xc))],["marketview.widget-configure",()=>Promise.resolve().then(()=>(Pc(),Tc))],["marketview.widget-load",()=>Promise.resolve().then(()=>($c(),_c))],["marketview.widget-read",()=>Promise.resolve().then(()=>(Mc(),Oc))],["marketview.widget-snippet",()=>Promise.resolve().then(()=>(Lc(),Wc))]])});async function No(e,t,n,r={}){let i=[],o=(l,c)=>{let d=Uc(c,r.signal),f=d?.method??"GET",p=d?.hedgeDelaysMs??[],g=d?.timeoutMs!==void 0&&p.length>0?Date.now()+d.timeoutMs:void 0,h=y=>{let w=Uc(d,y);return w?.signal?.aborted?Promise.reject(new T("network","aborted",{canceled:!0})):(i.push(`${f} ${l}`),w&&g!==void 0&&(w.timeoutMs=Math.max(1,g-Date.now())),t.request(l,qR(w)))};return p.length>0?FR(h,p,d?.signal):h()},s=()=>[...i];if(qi(e)){let l={};for(let c=0;c<e.steps.length;){let d=e.steps[c];if(d.parallel){let p=[],g={...l};for(;c<e.steps.length&&e.steps[c].parallel;){let y=e.steps[c];p.push({step:y,spec:y.request(n,g)}),c++}let h=await Promise.all(p.map(async({step:y,spec:w})=>{if(w===null)return{step:y,value:{}};let b=o(w.path,Fo(w));if(y.background){let R=b.catch(S=>{throw S});return R.catch(()=>{}),{step:y,value:R}}return{step:y,value:await b}}));for(let y of h)l[y.step.name]=y.value;continue}let f=d.request(n,l);if(f===null){l[d.name]={},c++;continue}l[d.name]=await o(f.path,Fo(f)),c++}try{return{result:await e.transform({steps:l,args:n,request:o,apiCalls:s}),raw:{steps:l,args:n}}}catch(c){throw jc(c,e.name)}}let a=e.request(n),u=await o(a.path,Fo(a));try{return{result:await e.transform({raw:u,args:n,request:o,apiCalls:s}),raw:u}}catch(l){throw jc(l,e.name)}}function Fo(e){let t={method:e.method};return e.query&&(t.query=e.query),e.headers&&(t.headers=e.headers),e.responseType&&(t.responseType=e.responseType),e.body!==void 0&&(t.body=e.body),e.timeoutMs!==void 0&&(t.timeoutMs=e.timeoutMs),e.signal!==void 0&&(t.signal=e.signal),e.hedgeDelaysMs!==void 0&&(t.hedgeDelaysMs=e.hedgeDelaysMs),e.acceptHtml!==void 0&&(t.acceptHtml=e.acceptHtml),t}function Uc(e,t){let n=LR(e?.signal,t);return n?{...e,signal:n}:e}function LR(e,t){if(!e)return t;if(!t||e.aborted)return e;if(t.aborted)return t;let n=new AbortController,r=()=>n.abort();return e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",r,{once:!0}),n.signal}function qR(e){if(!e?.hedgeDelaysMs)return e;let t={...e};return delete t.hedgeDelaysMs,t}function FR(e,t,n){return new Promise((r,i)=>{let o=!1,s=0,a,u=[],l=[],c=[],d=t.length+1,f=!1,p=()=>y(new T("network","Request canceled after caller aborted",{canceled:!0})),g=S=>{for(let C of l)clearTimeout(C);for(let C of c)C!==S&&C.abort();n?.removeEventListener("abort",p)},h=(S,C)=>{o||(o=!0,g(C),r(S))},y=S=>{o||(o=!0,g(),i(S))},w=()=>{f=!0;for(let S of l)clearTimeout(S)},b=()=>{let S=f?c.length:d;!o&&s>=S&&y(u[0]??a)};if(n?.aborted){p();return}n?.addEventListener("abort",p,{once:!0});let R=()=>{if(o)return;let S=c.length,C=new AbortController;c.push(C),e(C.signal).then(x=>{h(x,C)},x=>{if(u[S]=x,a===void 0&&(a=x),s+=1,!o&&NR(x)){w(),b();return}if(!o&&UR(x)){y(x);return}b()})};R();for(let S of t)l.push(setTimeout(R,S))})}function NR(e){return e instanceof T&&e.details?.status===429}function UR(e){if(!(e instanceof T))return!1;let t=e.details?.status;return typeof t!="number"?!1:t===500?!0:t>=400&&t<500&&t!==408}function jc(e,t){if(e instanceof T)return e;let n=e instanceof Error?e.message:String(e);return new T("adapter",`Adapter "${t}" failed: ${n}`,{adapter:t})}var Vc=v(()=>{"use strict";ge();Fi()});var Gc=v(()=>{"use strict";Fi();Nc();Vc()});var Bc=v(()=>{"use strict"});function jR(e,t){let n=e.endsWith("/")?e:`${e}/`,r=VR(t);return new URL(r,n)}function VR(e){let t=e.trim();return t.startsWith("//")?zc(new URL(`https:${t}`),e):/^[a-z][a-z0-9+.-]*:/i.test(t)?zc(new URL(t),e):t.replace(/^\/+/,"")}function zc(e,t){if(e.protocol!=="https:"||e.hostname!=="marquee.gs.com")throw new T("config","Broker transport only accepts marquee.gs.com URLs or paths",{path:t});return`${e.pathname.replace(/^\/+/,"")}${e.search}`}function _r(e,t){let n=e.trim();if(!n)throw new T("config",`Missing broker ${t}`);return n}function GR(e){return Object.fromEntries(Object.entries(e).filter(([t])=>{let n=t.toLowerCase();return n!=="authorization"&&n!=="cookie"}))}async function Jc(e){try{return(await e.text()).slice(0,1024)}catch(t){return`Unable to read broker error response body: ${t instanceof Error?t.message:String(t)}`}}function BR(e){if(!e)return{kind:"missing"};try{let n=JSON.parse(e).detail;if(!n||typeof n!="object"||Array.isArray(n))return{kind:"missing"};let r=n.code,i=n.message;return r!=="relink_required"||typeof i!="string"?{kind:"missing"}:{kind:"matched",code:r,message:i}}catch{return{kind:"malformed"}}}var Hc,$r,Yc=v(()=>{"use strict";ge();Hc=3e4,$r=class{brokerUrl;accountId;sessionId;invocationToken;fetchFn;constructor(t){this.brokerUrl=_r(t.brokerUrl,"brokerUrl"),this.accountId=_r(t.accountId,"accountId"),this.sessionId=_r(t.sessionId,"sessionId"),this.invocationToken=_r(t.invocationToken,"invocationToken"),this.fetchFn=t.fetchFn??fetch}async request(t,n={}){let r=jR(this.brokerUrl,t);if(n.query){for(let[c,d]of Object.entries(n.query))if(d!=null)if(Array.isArray(d))for(let f of d)r.searchParams.append(c,String(f));else r.searchParams.append(c,String(d))}let i=new AbortController,o=()=>i.abort();n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=!1,a=setTimeout(()=>{s=!0,o()},n.timeoutMs??Hc),u;try{u=await this.fetchFn(r.toString(),{method:n.method??"GET",headers:this.buildHeaders(n),body:n.body===void 0?void 0:JSON.stringify(n.body),signal:i.signal})}catch(c){throw c.name==="AbortError"?n.signal?.aborted&&!s?new T("network","Request canceled after faster hedge completed",{path:t,canceled:!0}):new T("timeout",`Broker request timed out after ${(n.timeoutMs??Hc)/1e3}s`,{path:t}):new T("network",`Cannot reach Marquee broker: ${c.message}`,{path:t})}finally{clearTimeout(a),n.signal?.removeEventListener("abort",o)}if(u.status===401||u.status===403){let c=await Jc(u),d=BR(c);throw new T("auth_expired",d.kind==="matched"?d.message:"Credential broker could not authenticate this Marquee request",{status:u.status,path:t,brokerCode:d.kind==="matched"?d.code:void 0})}if(!u.ok){let c=await Jc(u);throw new T("http",`Credential broker returned ${u.status} for ${t}`,{status:u.status,path:t,body:c})}if(n.responseType==="arrayBuffer")return u.arrayBuffer();if(n.responseType==="text")return u.text();let l=await u.text();if(!l)return{};try{return JSON.parse(l)}catch{throw new T("http",`Unexpected non-JSON broker response for ${t}`,{status:u.status,path:t,body:l.slice(0,256)})}}buildHeaders(t){let r={Accept:"application/json",...GR(t.headers??{}),Authorization:`Bearer ${this.invocationToken}`,"X-MarqueeBot-Account-Id":this.accountId,"X-MarqueeBot-Session-Id":this.sessionId};return t.body!==void 0&&(r["Content-Type"]="application/json;charset=utf-8"),r}}});import{existsSync as HR,mkdirSync as zR,readFileSync as JR,renameSync as YR,writeFileSync as KR}from"node:fs";import{dirname as QR}from"node:path";function dt(e){if(!HR(e))return{cookies:[],updatedAt:0};let t;try{t=JR(e,"utf-8")}catch(r){throw new T("config",`Cookie file unreadable at ${e}: ${r.message}. Run: marquee auth login`)}let n;try{n=JSON.parse(t)}catch{throw new T("config",`Cookie file corrupted at ${e}. Run: marquee auth login`)}if(!n||typeof n!="object"||!Array.isArray(n.cookies))throw new T("config",`Cookie file corrupted at ${e}. Run: marquee auth login`);return n}function Or(e,t){zR(QR(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;KR(n,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),YR(n,e)}function Mr(e,t){let n=Math.floor(Date.now()/1e3);return e.cookies.some(r=>ZR.includes(r.name)&&Xc(r.domain,t)&&Zc(r,n))}function Wr(e,t,n={}){let r=t.hostname,i=Math.floor(Date.now()/1e3);return e.cookies.filter(o=>Zc(o,i)&&Xc(o.domain,r)&&nk(o.path,t.pathname)&&(n.include?.(o)??!0)).map(o=>`${o.name}=${o.value}`).join("; ")}function Qc(e,t,n){let r=typeof n.headers.getSetCookie=="function"?n.headers.getSetCookie():[n.headers.get("set-cookie")].filter(Boolean);for(let i of r){let o=ek(i,t);o&&XR(e,o)}e.updatedAt=Date.now()}function XR(e,t){let n=e.cookies.findIndex(r=>Kc(r,t));n>=0?(e.cookies=e.cookies.filter(r=>!Kc(r,t)),e.cookies.splice(n,0,t)):e.cookies.push(t)}function Kc(e,t){return e.name===t.name&&Uo(e.domain)===Uo(t.domain)&&e.path===t.path}function ek(e,t){let n=e.split(";").map(a=>a.trim()),[r,...i]=n,o=r.indexOf("=");if(o<0)return null;let s={name:r.slice(0,o).trim(),value:r.slice(o+1).trim(),domain:t.hostname,path:"/"};for(let a of i){let u=a.indexOf("="),l=u>=0?a.slice(0,u):a,c=u>=0?a.slice(u+1):void 0,d=l.trim().toLowerCase(),f=c?.trim();d==="domain"&&f?s.domain=f.startsWith(".")?f.slice(1):f:d==="path"&&f?s.path=f:d==="expires"&&f?s.expires=Math.floor(new Date(f).getTime()/1e3):d==="max-age"&&f?s.expires=Math.floor(Date.now()/1e3)+Number(f):d==="httponly"?s.httpOnly=!0:d==="secure"?s.secure=!0:d==="samesite"&&tk(f)&&(s.sameSite=f)}return s}function tk(e){return e==="Lax"||e==="Strict"||e==="None"}function Zc(e,t){return e.expires===void 0||e.expires<0||e.expires>t}function Xc(e,t){let n=Uo(e);return t===n||t.endsWith(`.${n}`)}function Uo(e){return e.startsWith(".")?e.slice(1):e}function nk(e,t){return t===e||t.startsWith(e.endsWith("/")?e:`${e}/`)}var ZR,En=v(()=>{"use strict";ge();ZR=["MarqueeLogin","MarqueeIdToken"]});import{appendFileSync as rk}from"node:fs";function Lr(e){(process.env.MARQUEE_API_LOG||process.env.MARQUEE_API_TIMING_LOG)&&process.stderr.write(`__MQ_TOKEN_EXCHANGE__${e}
15
+ `)}async function jo(e){return al(e,"preserve-classification")}async function Vo(e,t){return al(e,"propagate-abort",t)}async function al(e,t,n){try{return(await e.text()).slice(0,1024)}catch(r){if(t==="propagate-abort"){if((r instanceof Error||r instanceof DOMException)&&r.name==="AbortError")throw r;if(n?.aborted){let i=new Error(r instanceof Error?r.message:String(r));throw i.name="AbortError",i}}return""}}function qr(e,t,n,r,i){let o=process.env.MARQUEE_FAILURE_LOG;if(o)try{let s={};e.headers.forEach((l,c)=>{s[c]=sk.has(c.toLowerCase())?ak:l});let a=/entity\s*=\s*'([^']+)'/.exec(i)?.[1],u={ts:new Date().toISOString(),method:n,path:r,url:t.toString(),status:e.status,entity:a,headers:s,body:i};rk(o,`${JSON.stringify(u)}
16
+ `)}catch(s){process.stderr.write(`__MQ_FAILURE_LOG_ERROR__${s instanceof Error?s.message:String(s)}
17
+ `)}}function uk(e){return/error getting entity/i.test(e)}async function dk(e,t){if((e.headers.get("content-type")??"").includes("text/html"))return Vo(e,t)}function ck(e,t,n){let r=t.method??"GET";return lk(e,r)&&!fk(n)}function lk(e,t){return t==="GET"&&e.pathname.startsWith("/v1/")}function fk(e){let t=De(e);return/\b(login|sign[- ]?in|sso|saml|oauth|idfs)\b/i.test(e)||/\b(login|sign[- ]?in|sso|saml|oauth|idfs)\b/i.test(t)||/<input\b[^>]*type\s*=\s*['"]?password\b/i.test(e)||/<form\b[^>]*(?:login|sign[- ]?in|sso|saml|oauth|idfs)/i.test(e)||/<(?:form|input)\b[\s\S]{0,500}\b(?:username|password|pf\.username|pf\.pass)\b/i.test(e)}function pk(e){let t=De(e);if(/<input\b[^>]*type\s*=\s*['"]?password\b/i.test(e)||/<form\b[^>]*(?:login|sign[- ]?in|sso|saml|oauth|idfs)/i.test(e)||/<(?:form|input)\b[\s\S]{0,500}\b(?:username|password|pf\.username|pf\.pass)\b/i.test(e))return!0;if(!/\b(login|sign[- ]?in|sso|saml|oauth|idfs|session (?:has )?expired|access denied)\b/i.test(e)&&!/\b(login|sign[- ]?in|sso|saml|oauth|idfs|session (?:has )?expired|access denied)\b/i.test(t))return!1;let n=e,r=gk(e),i=r.map(o=>e.slice(o.innerStart,o.innerEnd));if(i.length>0){if(yk(i))return!0;wk(i)||(n=mk(e,r))}return ul(n)}function De(e){return e.replace(/<script\b[\s\S]*?<\/script>/gi," ").replace(/<style\b[\s\S]*?<\/style>/gi," ").replace(/<[^>]+>/g," ").replace(/&(?:nbsp|\x23160|\x23x0*a0);/gi," ").replace(/\s+/g," ").trim()}function gk(e){let t=[],n=/<\/?([a-zA-Z][\w:-]*)\b[^>]*>/g,r;for(;(r=n.exec(e))!==null;){let i=r[0],o=r[1].toLowerCase();if(i.startsWith("</")||rl(i)||o!=="article"&&!hk(i))continue;let s=r.index,a=n.lastIndex,u=e.length,l=e.length,c=1,d=!1;for(;(r=n.exec(e))!==null;){let f=r[0];if(r[1].toLowerCase()===o)if(f.startsWith("</")){if(c-=1,c===0){l=r.index,u=n.lastIndex,d=!0;break}}else rl(f)||(c+=1)}if(t.push({outerStart:s,outerEnd:u,innerStart:a,innerEnd:l}),!d)break}return t}function mk(e,t){let n=e;for(let r of[...t].reverse())n=`${n.slice(0,r.outerStart)} ${n.slice(r.outerEnd)}`;return n}function rl(e){return/\/\s*>$/.test(e)||/^<\s*(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)\b/i.test(e)}function hk(e){return/\sdata-testid\s*=\s*(?:"Chapter"|'Chapter'|Chapter)(?:\s|>|\/)/i.test(e)}function yk(e){for(let t of e)if(bk(t)||Rk(t)||De(t).length<=120&&ul(t))return!0;return!1}function wk(e){for(let t of e)if(De(t).length>80)return!1;return!0}function bk(e){for(let t of e.matchAll(/<h[1-6]\b[^>]*>([\s\S]*?)<\/h[1-6]>/gi))if(ct(De(t[1]??"")))return!0;return!1}function Rk(e){let t=e.replace(/<blockquote\b[\s\S]*?<\/blockquote>/gi," ");for(let n of t.matchAll(/<(p|li|button|a|span|label)\b[^>]*>([\s\S]*?)<\/\1>/gi))if(ct(De(n[2]??"")))return!0;for(let n of t.matchAll(/<(div|section)\b[^>]*>([\s\S]*?)<\/\1>/gi)){let r=De(n[2]??"");if(r.length<=240&&ct(r))return!0}return!1}function ul(e){let t=De(e);if(!/\b(login|sign[- ]?in|sso|saml|oauth|idfs|session (?:has )?expired|access denied)\b/i.test(t))return!1;for(let n of e.matchAll(/<(title|h[1-6])\b[^>]*>([\s\S]*?)<\/\1>/gi)){let r=n[1]?.toLowerCase(),i=De(n[2]??"");if(ct(i)||r==="title"&&kk(i))return!0}for(let n of e.matchAll(/<(p|li|button|a|span|label)\b[^>]*>([\s\S]*?)<\/\1>/gi))if(ct(De(n[2]??"")))return!0;for(let n of e.matchAll(/<(div|section)\b[^>]*>([\s\S]*?)<\/\1>/gi)){let r=De(n[2]??"");if(r.length<=240&&ct(r))return!0}return t.length>240?!1:!!ct(t)}function ct(e){let t=e.replace(/[.!?]+$/g,"").trim();return/^(?:(?:your\s+)?session\s+(?:has\s+)?expired|(?:your\s+)?access\s+denied)(?:[.!?]*\s*(?:(?:please\s+)?(?:login|sign[- ]?in)(?:\s+again)?|contact\s+your\s+administrator))?$/i.test(t)?!0:/^(?:please\s+)?(?:login(?:\s+(?:to\s+(?:continue|proceed)|again))?|sign[- ]?in(?:\s+(?:with|using)\s+(?:sso|saml|oauth|idfs|single sign[- ]?on))?(?:\s+(?:to\s+(?:continue|proceed)|again))?|(?:sso|saml|oauth|idfs)\s+login|idfs)$/i.test(t)}function kk(e){let t=e.replace(/[.!?]+$/g,"").trim();return/^(?:goldman\s+sachs|goldmansachs|gs|marquee)(?:\s*[-:]\s*|\s+)(?:idfs|sso|login|sign[- ]?in)(?:\s+login)?$/i.test(t)}function il(e,t){let n=Bo(e,t,"MARQUEE-CSRF-TOKEN");if(n)try{return decodeURIComponent(n)}catch{return n}}function Ak(e){return e.pathname.startsWith("/content/research/")}function ol(e,t){return Wr(e,t,{include:n=>Go(t)||!Sk(n)})}function Go(e){return e.pathname.startsWith("/research/")||Ak(e)}function Sk(e){return ok.has(e.name)}function Ck(e,t){let n=t.method??"GET";return e.pathname.startsWith("/v1/marketview/dashboards")&&!e.pathname.endsWith("/children")&&(n==="POST"||n==="PUT"||n==="DELETE")?"MQSITE":"MarketView"}function sl(e,t){return(t.method??"GET")==="POST"&&e.pathname.startsWith("/v1/data/visualizations/")&&e.pathname.endsWith("/render")}function Bo(e,t,n){let r=e.cookies.filter(i=>i.name===n&&Ek(i.domain,t.hostname)&&vk(i.path||"/",t.pathname));return r.find(i=>i.domain===t.hostname)?.value||r[0]?.value}function Ek(e,t){let n=e.startsWith(".")?e.slice(1):e;return t===n||t.endsWith(`.${n}`)}function vk(e,t){return t===e||t.startsWith(e.endsWith("/")?e:`${e}/`)}var ik,el,tl,nl,ok,Fr,sk,ak,dl=v(()=>{"use strict";ge();En();ik="https://marquee.gs.com",el=3e4,tl="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",nl="en-US,en;q=0.9",ok=new Set(["JSESSIONID","session","panama_scope_id","panama_scope_started"]),Fr=class{jar;jarPath;fetchFn;saveFn;baseUrl;accessToken;constructor(t){this.jar=t.jar,this.jarPath=t.jarPath,this.fetchFn=t.fetchFn??fetch,this.saveFn=t.saveFn??Or,this.baseUrl=t.baseUrl??ik}async request(t,n={}){let r=new URL(t,this.baseUrl);if(n.query){for(let[f,p]of Object.entries(n.query))if(p!=null)if(Array.isArray(p))for(let g of p)r.searchParams.append(f,String(g));else r.searchParams.append(f,String(p))}let i=r.pathname.startsWith("/v1/content/feed/article/"),o=new AbortController,s=()=>o.abort();n.signal?.aborted?s():n.signal?.addEventListener("abort",s,{once:!0});let a=!1,u=setTimeout(()=>{a=!0,s()},n.timeoutMs??el),l,c,d;try{(i||sl(r,n))&&!this.currentAccessToken()&&await this.exchangeAccessToken(o.signal);let f=this.buildHeaders(r,n),p={method:n.method??"GET",headers:f,signal:o.signal};if(n.body!==void 0&&(p.body=JSON.stringify(n.body)),l=await this.fetchFn(r.toString(),p),this.persistCookies(r,l),l.status===401&&!Go(r)){let y=await this.exchangeAccessToken(o.signal);y&&(f.Authorization=`Bearer ${y}`,l=await this.fetchFn(r.toString(),p),this.persistCookies(r,l))}if(c=l.ok&&!n.acceptHtml?await dk(l,o.signal):void 0,c!==void 0&&ck(r,n,c)&&(l=await this.fetchFn(r.toString(),p),this.persistCookies(r,l),c=void 0),l.status===401&&(d=await jo(l)),l.status===401){let y=sl(r,n),w=d??"";if(qr(l,r,n.method??"GET",t,w),uk(w))throw new T("http",`Marquee returned 401 for ${t}`,{status:401,path:t,body:w});let b={status:401,path:t};y&&w&&(b.body=w);let R=y?w.length>0?` \u2014 ${w.slice(0,300)}`:" \u2014 (empty 401 body)":"";throw new T("auth_expired",`Not authenticated. Run: marquee auth login${R}`,b)}if(!l.ok){let y=await Vo(l,o.signal);throw qr(l,r,n.method??"GET",t,y),new T("http",`Marquee returned ${l.status} for ${t}`,{status:l.status,path:t,body:y})}let g=l.headers.get("content-type")??"";if(g.includes("text/html")&&(c??=await Vo(n.acceptHtml?l.clone():l,o.signal),!n.acceptHtml||pk(c)))throw new T("auth_expired",`Access denied or session expired for ${t}. Run: marquee auth login`,{status:l.status,path:t,contentType:g,body:c.slice(0,256)});if(n.responseType==="arrayBuffer")return await l.arrayBuffer();if(n.responseType==="text")return await l.text();let h=await l.text();if(!h)return{};try{return JSON.parse(h)}catch{throw new T("http",`Unexpected non-JSON response for ${t}`,{status:l.status,path:t,body:h.slice(0,256)})}}catch(f){throw f instanceof T?f:f.name==="AbortError"?n.signal?.aborted&&!a?new T("network","Request canceled after faster hedge completed",{path:t,canceled:!0}):new T("timeout",`Request timed out after ${(n.timeoutMs??el)/1e3}s`,{path:t}):new T("network",`Cannot reach ${this.baseUrl}: ${f.message}`,{path:t})}finally{clearTimeout(u),n.signal?.removeEventListener("abort",s)}}buildHeaders(t,n){let r=t.pathname.startsWith("/v1/content/feed/article/"),i=Go(t),o={Origin:this.baseUrl,Referer:r?`${this.baseUrl}/content/`:i?`${this.baseUrl}/content/research/site/search.html`:`${this.baseUrl}/s/marketview/`,Accept:"application/json","Accept-Language":nl,"User-Agent":tl,"X-Dash-AppId":Ck(t,n),"X-Application":"mqda-mv","X-Flatten-Status":"true"},s=ol(this.jar,t);s&&(o.Cookie=s);let a=i?{source:"none",value:void 0}:this.authTokenForRequest(t);if(a.value&&(o.Authorization=`Bearer ${a.value}`),t.pathname.startsWith("/v1/")){let u=il(this.jar,t);u&&(o["X-MARQUEE-CSRF-TOKEN"]=u)}return r?o["Content-Type"]="application/json":n.body!==void 0&&(o["Content-Type"]="application/json;charset=utf-8"),n.headers?{...o,...n.headers}:o}authTokenForRequest(t){let n=this.currentAccessToken();if(n)return{source:"accessToken",value:n};let r=Bo(this.jar,t,"MarqueeIdToken");return r?{source:"MarqueeIdToken",value:r}:{source:"none"}}currentAccessToken(){if(this.accessToken){if(this.accessToken.expiresAt<=Date.now()){this.accessToken=void 0;return}return this.accessToken.value}}async exchangeAccessToken(t){let n=new URL("/tokenExchange",this.baseUrl),r=Bo(this.jar,n,"MarqueeIdToken");if(!r)return;let i={Origin:this.baseUrl,Referer:`${this.baseUrl}/s/`,Accept:"application/json","Accept-Language":nl,"User-Agent":tl,"Content-Type":"application/json",Authorization:`Bearer ${r}`},o=ol(this.jar,n);o&&(i.Cookie=o);let s=il(this.jar,n);s&&(i["X-MARQUEE-CSRF-TOKEN"]=s);let a=await this.fetchFn(n.toString(),{method:"POST",headers:i,signal:t});this.persistCookies(n,a);let u=a.headers.get("content-type")??"";if(!a.ok){let c=await jo(a);qr(a,n,"POST",n.pathname,c),Lr(`failed status=${a.status} body=${c.slice(0,200)}`);return}if(u.includes("text/html")){qr(a,n,"POST",n.pathname,await jo(a)),Lr("failed html-response");return}let l=await a.text();if(!l){Lr("failed empty-body");return}try{let c=JSON.parse(l);if(typeof c.accessToken!="string"||c.accessToken.length===0){Lr(`failed no-access-token keys=${Object.keys(c).join(",")}`);return}let d=typeof c.expiryInMillis=="number"&&Number.isFinite(c.expiryInMillis)?Math.max(0,c.expiryInMillis-3e4):24e4;return this.accessToken={value:c.accessToken,expiresAt:Date.now()+d},c.accessToken}catch{return}}persistCookies(t,n){let r=JSON.stringify(this.jar.cookies);if(Qc(this.jar,t,n),JSON.stringify(this.jar.cookies)!==r||n.headers.has("set-cookie"))try{this.saveFn(this.jarPath,this.jar)}catch(i){let o=i instanceof Error?i.message:String(i);throw new T("persistence",`Failed to persist cookie jar ${this.jarPath}: ${o}`,{path:t.pathname,jarPath:this.jarPath})}}};sk=new Set(["set-cookie","authorization","proxy-authorization"]),ak="__REDACTED__"});var cl,ll,fl=v(()=>{"use strict";cl={query:"spx",asset:{id:"asset_spx_index",symbol:"SPX",primary:!0}},ll={query:"spx carry",results:[{id:"mv_widget_spx_carry",type:"widget",title:"SPX Carry vs Spot"}]}});function Nr(){let e={asset:new Ho,marketview:new zo};return{async execute(t){let n=e[t.surface];return n?n.execute(t):{status:"not_implemented",surface:t.surface,action:t.action,data:{},errors:[`${t.surface} not implemented`]}}}}var Ho,zo,pl=v(()=>{"use strict";fl();Ho=class{async execute(t){return t.action!=="resolve"?{status:"not_implemented",surface:"asset",action:t.action,data:{},errors:[`asset.${t.action} not implemented`]}:{status:"ok",surface:"asset",action:"resolve",data:{asset:cl.asset},errors:[]}}},zo=class{async execute(t){return t.action!=="search"?{status:"not_implemented",surface:"marketview",action:t.action,data:{},errors:[`marketview.${t.action} not implemented`]}:{status:"ok",surface:"marketview",action:"search",data:{result:ll.results},errors:[]}}}});function xk(e){let t=[],n=[],r=[];return{transport:{async request(o,s){let a=s?.method??"GET";t.push(`${a} ${o}`);let u=n.length,l=r.length,c=Date.now(),d=performance.now(),f=Math.round(d);n.push({method:a,path:o,ms:0,startMs:f,status:"ok"}),r.push({method:a,path:o,queryKeys:Object.keys(s?.query??{}).sort(),startMs:f,durationMs:0,status:"ok"});try{let p=await e.request(o,s);return n[u]={method:a,path:o,ms:Date.now()-c,startMs:f,status:"ok"},r[l]={...r[l],durationMs:Math.round(performance.now()-d),status:"ok"},p}catch(p){let g=p instanceof Error?p.message:String(p);throw n[u]={method:a,path:o,ms:Date.now()-c,startMs:f,status:"error",error:g},r[l]={...r[l],durationMs:Math.round(performance.now()-d),status:"error",error:g},p}}},getApiCalls:()=>[...new Set(t)],getApiTimings:()=>n.map(o=>({...o})),getTraceAttempts:()=>r.map(o=>({...o,queryKeys:[...o.queryKeys]}))}}function gl(e,t,n){let r=new Map,i=(o,s)=>{let a=`${o}.${s}`,u=r.get(a);return u||(u=t(o,s),r.set(a,u)),u};return{async execute(o){let s;try{s=await i(o.surface,o.action)}catch(d){let f=d instanceof Error?d.message:String(d),p=d instanceof T?d.code:"adapter";return{status:"error",surface:o.surface,action:o.action,data:{error:f,errorCode:p,httpStatus:0},errors:[f],meta:{apiCalls:[]}}}if(!s)return{status:"error",surface:o.surface,action:o.action,data:{},errors:[`No adapter found for ${o.surface}.${o.action}`]};let{transport:a,getApiCalls:u,getApiTimings:l,getTraceAttempts:c}=xk(e);try{let{result:d,raw:f}=await n(s,a,o.input,{signal:o.signal}),p=u();p.length&&process.env.MARQUEE_API_LOG&&process.stderr.write(`__MQ_API__${JSON.stringify(p)}
18
+ `),p.length&&process.env.MARQUEE_API_TIMING_LOG&&process.stderr.write(`__MQ_API_TIMING__${JSON.stringify(l())}
19
+ `),process.env.MARQUEE_TRACE_LOG&&process.stderr.write(`__MQ_TRACE__${JSON.stringify(c())}
20
+ `);let g={apiCalls:p};return s.columns&&(g.columns=s.columns),{status:"ok",surface:o.surface,action:o.action,data:{result:d,raw:f},errors:[],meta:g}}catch(d){let f=d instanceof T||d instanceof Error?d.message:String(d),p=d instanceof T?d.details?.body:void 0,g=p?` \u2014 ${p.length>200?p.slice(0,200):p}`:"",h=d instanceof T?d.code:"http",y=d instanceof T?d.details?.status??0:0,w=f+g,b=s.formatError?.(o.input,y,w)??w,R=u();return R.length&&process.env.MARQUEE_API_LOG&&process.stderr.write(`__MQ_API__${JSON.stringify(R)}
21
+ `),process.env.MARQUEE_TRACE_LOG&&process.stderr.write(`__MQ_TRACE__${JSON.stringify(c())}
22
+ `),{status:"error",surface:o.surface,action:o.action,data:{error:b,errorCode:h,httpStatus:y},errors:[b],meta:s.columns?{columns:s.columns,apiCalls:R}:{apiCalls:R}}}}}}var ml=v(()=>{"use strict";ge();pl()});import{spawn as Ik,execFileSync as wl}from"node:child_process";import{existsSync as Dk}from"node:fs";import{createRequire as Tk}from"node:module";import{dirname as bl,isAbsolute as Pk,join as _k,resolve as $k}from"node:path";import{fileURLToPath as Ok}from"node:url";function Wk(){try{return Tk(import.meta.url).resolve("agent-browser/bin/agent-browser.js")}catch{}for(let e of Lk()){let t=_k(e,"node_modules",".bin","agent-browser");if(Dk(t))return t}try{return wl("which",["agent-browser"],{encoding:"utf-8"}).trim()}catch{}throw new Error("agent-browser not found. Install it: npm install -D agent-browser")}function Lk(){let e=[],t=Mk,n=hl(["rev-parse","--show-toplevel"],t);n&&e.push(n);let r=hl(["rev-parse","--git-common-dir"],t);if(r){let i=Pk(r)?r:$k(t,r);e.push(bl(i))}return[...new Set(e)]}function hl(e,t){try{return wl("git",e,{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function Ur(){return Jo||(Jo=Wk()),Jo}function Yo(e){return/(?:^|[\\/])agent-browser\.js$/.test(e??"")}function qt(e){let t=Ur();return Yo(t)?{file:process.execPath,args:[t,...e]}:{file:t,args:e}}function Uk(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(n=>/^(?:Session|Live View):\s+/.test(n));return t.length>0?`${t.join(`
23
+ `)}
24
+ `:""}function yl(e,t){return t?e?e.endsWith(`
25
+ `)?`${e}${t}`:`${e}
26
+ ${t}`:t:e}function jr(e={}){let t=e.session??"marquee",n=t,r,i,o="",s=e.executor??((R,S,C)=>new Promise((x,E)=>{let j=typeof C.encoding=="string"?C.encoding:"utf-8",D=typeof C.timeout=="number"?C.timeout:0,A=typeof C.input=="string"?C.input:void 0,I=qt(S),O=Ik(I.file,I.args,{stdio:["pipe","pipe","pipe"],env:process.env}),M="",N="",V=!1,G;O.stdout.setEncoding(j),O.stderr.setEncoding(j),O.stdout.on("data",W=>{M+=W}),O.stderr.on("data",W=>{N+=W}),O.on("error",W=>{G&&clearTimeout(G),E(W)}),O.on("close",W=>{if(G&&clearTimeout(G),V){E(new Error("ETIMEDOUT"));return}if(W===0){x({stdout:M,stderr:N});return}let K=N.trim()||M.trim();E(new Error(K?`exit code ${W}: ${K}`:`exit code ${W}`))}),D>0&&(G=setTimeout(()=>{V=!0,O.kill("SIGTERM")},D)),A!==void 0&&O.stdin.write(A),O.stdin.end()}));function a(R){let S=R instanceof Error?R.message:String(R);return S.includes("Session with given id not found")||S.includes("daemon already running")}function u(R){return(R instanceof Error?R.message:String(R)).includes("Session with given id not found")}async function l(){o="";let R=n!==t?["--session",n,"close"]:["close"];try{await s(Ur(),R,{encoding:"utf-8",timeout:5e3})}catch(S){if(!u(S))throw S}}async function c(){!e.pool||r||(i||(i=(async()=>{let R=await e.pool.acquire();r=R,n=R.session})().finally(()=>{i=void 0})),await i)}function d(R,S,C){let x=Uk(C);if(R==="close")return o="",S;if(R!=="open")return o+=x,yl(S,x);let E=yl(S,x||o);return o="",E}async function f(R,S,C=[],x={}){let E=["--session",R];x.headed&&E.push("--headed"),E.push(S,...C);let j={encoding:"utf-8",timeout:x.timeout??3e4};x.stdin!==void 0&&(j.input=x.stdin);try{let{stdout:D,stderr:A}=await s(Ur(),E,j);return d(S,D,A)}catch(D){if(a(D)){await l();let{stdout:A,stderr:I}=await s(Ur(),E,j);return d(S,A,I)}throw D}}async function p(R,S=[],C={}){return await c(),f(n,R,S,C)}function g(R){let S=R.trimStart();return S.startsWith("<!DOCTYPE")||S.startsWith("<html")}function h(R){return(R instanceof Error?R.message:String(R)).includes("Not authenticated")}function y(R){return a({message:R})||R.includes("CDP error")?"Browser session expired. Retrying failed \u2014 try: marquee auth login":R}async function w(){try{let R=e.pool?t:n,S=await f(R,"eval",[Fk],{skipAuthCheck:!0});return g(S)?!1:S.trim()==="true"}catch{return!1}}async function b(R,S,C){try{await p("open",[qk],{skipAuthCheck:!0,timeout:Nk})}catch{throw new Re("Not authenticated. Run: marquee auth login","authentication_failure")}try{let x=await p(R,S,C);if(!g(x))return x}catch(x){if(!h(x))throw x}throw new Re("Not authenticated. Run: marquee auth login","authentication_failure")}return{isAuthenticated:w,async close(){if(!(e.pool&&!r))try{await p("close",[],{skipAuthCheck:!0})}finally{r&&e.pool&&(e.pool.release(r),r=void 0,n=t)}},async saveState(R){let S=e.pool?t:n;await f(S,"state",["save",R],{skipAuthCheck:!0})},async run(R,S=[],C={}){try{let x=await p(R,S,C);return!C.skipAuthCheck&&g(x)?b(R,S,C):x}catch(x){if(x instanceof Re&&x.code==="authentication_failure")throw x;let E=x instanceof Error?x.message:String(x);if(E.includes("ETIMEDOUT")||E.includes("timed out"))throw new Re("Command timed out.","timeout");if(!C.skipAuthCheck&&h(x))try{return await b(R,S,C)}catch(j){if(j instanceof Re&&j.code==="authentication_failure")throw j;let D=j instanceof Error?j.message:String(j);throw D.includes("ETIMEDOUT")||D.includes("timed out")?new Re("Command timed out.","timeout"):new Re(`Command failed: ${R}. ${y(D)}`,"command_failed")}throw new Re(`Command failed: ${R}. ${y(E)}`,"command_failed")}}}}var Mk,Jo,qk,Fk,Nk,Re,Vr=v(()=>{"use strict";Mk=bl(Ok(import.meta.url));qk="https://marquee.gs.com/s/",Fk='(async () => { try { const response = await fetch("/v1/users/self", { credentials: "include" }); return response.ok; } catch { return false; } })()',Nk=6e4,Re=class extends Error{constructor(n,r){super(n);this.code=r;this.name="TransportError"}}});import{execFile as jk}from"node:child_process";import{existsSync as Vk,mkdirSync as Gk,readFileSync as Bk,unlinkSync as Hk,writeFileSync as zk}from"node:fs";import{join as Nt}from"node:path";import{constants as Al,homedir as Sl}from"node:os";import{promisify as Jk}from"node:util";function vn(e,t,n){Ft(Cl(e,t),n)}function Cl(e,t){return Nt(e,`${Gr}${t}.lock`)}function El(e){return`${e}.cleanup`}function Ft(e,t){t.existsSync(e)&&t.unlinkSync(e)}function Qo(e){try{return process.kill(e,0),!0}catch{return!1}}function Ko(e,t){try{let n=t.readFileSync(e,"utf8"),r=Number.parseInt(n.trim(),10);return Number.isFinite(r)&&Qo(r)}catch{return!1}}function Br(e,t){try{return t.writeFileSync(e,`${process.pid}`,{flag:"wx"}),!0}catch{return!1}}function rA(e,t){let n=El(e);return Br(n,t)?!0:Ko(n,t)?!1:(Ft(n,t),Br(n,t))}function iA(e,t,n){let r=Cl(e,t);if(n.existsSync(r)){if(Ko(r,n))return!1;let i=El(r);if(!rA(r,n))return!1;let o=!1,s=()=>{try{Ft(i,n)}catch(a){throw o&&Ft(r,n),a}};try{n.existsSync(r)&&Ko(r,n)||(Ft(r,n),o=Br(r,n))}catch(a){throw s(),a}return s(),o}return Br(r,n)}function sA(e,t){return Zk.map(n=>Nt(e,`${t}.${n}`))}function vl(e,t,n){for(let r of sA(e,t))Ft(r,n)}function kl(e,t,n){let r=Nt(e,`${t}.pid`);if(n.existsSync(r)){try{let i=n.readFileSync(r,"utf8"),o=Number.parseInt(i.trim(),10);if(Number.isFinite(o)&&Qo(o))return}catch{}vl(e,t,n)}}function aA(e){return e.includes("ECONNREFUSED")||e.includes("ENOENT")||e.includes("EPIPE")||e.includes("ETIMEDOUT")||e.includes("timed out")||e.includes("socket")}function uA(e){return(e instanceof Error?e.message:String(e)).includes("Session with given id not found")}function dA(e){throw e instanceof Error&&(e.code="ERR_SESSION_CLEANUP"),e}function xl(e={}){let t=e.poolDir??Yk,n=e.maxSlots??Qk,r=e.sessionDir??Kk,i={...nA,...e.fileSystem},o=e.executor??(async(f,p,g)=>{let h=await oA(f,p,{encoding:"utf8",...g});return{stdout:String(h.stdout),stderr:String(h.stderr)}}),s=e.stateFile,a=new Set,u=new Set;function l(f,p){let g=qt(f);return o(g.file,g.args,p)}i.mkdirSync(t,{recursive:!0});function c(f){let p=Nt(r,`${f}.pid`);if(!i.existsSync(p))return!1;try{let g=i.readFileSync(p,"utf8"),h=Number.parseInt(g.trim(),10);return Number.isFinite(h)&&Qo(h)}catch{return!1}}async function d(f){if(!s||!i.existsSync(s)||a.has(f.slot))return;let p={encoding:"utf8",timeout:1e4};if(c(f.session))try{await l(["--session",f.session,"state","load",s],p),a.add(f.slot);return}catch(g){let h=g instanceof Error?g.message:String(g);if(!aA(h))throw g instanceof Error&&(g.code="ERR_STATE_LOAD"),g}try{kl(r,f.session,i);try{await l(["--session",f.session,"close"],p)}catch(g){if(!uA(g))throw g}vl(r,f.session,i)}catch(g){dA(g)}await l(["--headed","--session",f.session,"open","about:blank"],p),await l(["--session",f.session,"state","load",s],p),a.add(f.slot)}return{async acquire(){let f;for(let p=0;p<n;p+=1)if(iA(t,p,i)){let g={session:`${Gr}${p}`,slot:p};u.add(p);try{return await d(g),g}catch(h){if(u.delete(p),vn(t,p,i),h instanceof Error&&["ERR_STATE_LOAD","ERR_SESSION_CLEANUP"].includes(h.code??""))throw h;f=h instanceof Error?h:new Error(String(h));continue}}throw f??new Error("No available session slots")},release(f){u.delete(f.slot),vn(t,f.slot,i)},releaseAll(){u.forEach(f=>vn(t,f,i)),u.clear()},async closeAll(){await Promise.all(Array.from({length:n},async(f,p)=>{try{await l(["--session",`${Gr}${p}`,"close"],{encoding:"utf8",timeout:1e4})}finally{vn(t,p,i)}})),u.clear(),a.clear()},async warm(f){if(!s||!i.existsSync(s))return;let p=Math.min(f??Xk,n),g={encoding:"utf8",timeout:1e4};for(let h=0;h<p;h+=Rl){let y=Array.from({length:Math.min(Rl,p-h)},(w,b)=>h+b);await Promise.all(y.map(async w=>{let b=`${Gr}${w}`;c(b)||(kl(r,b,i),await l(["--session",b,"open","about:blank"],g),await l(["--session",b,"state","load",s],g),await l(["--session",b,"open","https://marquee.gs.com/s/"],g))}))}},installExitHandlers(){let f=()=>{u.forEach(p=>vn(t,p,i)),u.clear()};process.on("exit",f),process.on("SIGTERM",()=>{f(),process.exit(eA)}),process.on("SIGINT",()=>{f(),process.exit(tA)})}}}var Yk,Kk,Qk,Gr,Zk,Xk,Rl,eA,tA,nA,oA,Il=v(()=>{"use strict";Vr();Yk=Nt(Sl(),".agent-browser","pool"),Kk=Nt(Sl(),".agent-browser"),Qk=10,Gr="marquee-p",Zk=["pid","sock","engine","stream"],Xk=2,Rl=2,eA=128+Al.signals.SIGTERM,tA=128+Al.signals.SIGINT,nA={existsSync:Vk,mkdirSync:Gk,readFileSync:Bk,unlinkSync:Hk,writeFileSync:zk};oA=Jk(jk)});var xn=v(()=>{"use strict";Bc();Yc();ge();dl();ml();Il();Vr()});import{createHash as es}from"node:crypto";import{Buffer as Pl}from"node:buffer";import{appendFileSync as cA,existsSync as _l,mkdirSync as lA,readFileSync as fA,readdirSync as pA,renameSync as gA,writeFileSync as mA}from"node:fs";import{join as zr}from"node:path";import{gzipSync as hA,gunzipSync as yA}from"node:zlib";function Jr(e,t={}){let n=(t.method??"GET").toUpperCase(),r=typeof t.body=="string"?t.body:"";return`${n} ${e}
27
+ ${r}`}function Dl(e,t){let n=Hr(t).slice(0,16);return zr(e,`${n}.json.gz`)}function Hr(e){return es("sha256").update(e).digest("hex")}function Ml(e,t={}){let n=(t.method??"GET").toUpperCase(),r=new URL(e),i=r.pathname.replace(/^\/+/,"").replace(/\/+/g,"_")||"root",o=r.search?`_${r.search.slice(1)}`:"",s=`${n}_${i}${o}.json.gz`;if(s.length<=Zo)return s;let u=`_${es("sha256").update(Jr(e,t)).digest("hex").slice(0,12)}.json.gz`;return`${s.slice(0,Zo-u.length)}${u}`}function ts(e){if(_l(e))return JSON.parse(yA(fA(e)).toString("utf-8"))}function Wl(e){try{return ts(e)}catch{return}}function RA(e,t){if(_l(e))for(let n of pA(e)){if(!n.endsWith(".json.gz"))continue;let r=ts(zr(e,n));if(r&&Ll(r,t))return r}}function Ll(e,t){return e.request.signatureHash?e.request.signatureHash===Hr(t):kA(e)===t}function kA(e){return e.request.signature??Jr(e.request.url,{method:e.request.method,body:e.request.body??""})}function AA(e,t,n,r){let i=Ml(t,n),o=(n.method??"GET").toUpperCase(),s=r.slice(r.indexOf(`
28
+ `)+1).length>0;if(o!=="GET"&&s)return Tl(i,r);let a=Wl(zr(e,i));return!a||Ll(a,r)?i:Tl(i,r)}function Tl(e,t){let n=`_${es("sha256").update(t).digest("hex").slice(0,8)}.json.gz`;return`${e.replace(/\.json\.gz$/,"").slice(0,Zo-n.length)}${n}`}function SA(e,t){let n=`${e}.${process.pid}.tmp`;mA(n,t),gA(n,e)}async function CA(e){let t=e.headers.get("content-type")??"";return DA(t)?{status:e.status,contentType:t,body:Pl.from(await e.arrayBuffer()).toString("base64"),bodyEncoding:"base64"}:{status:e.status,contentType:t,body:ql(t,await e.text())}}function ql(e,t){if(!t)return t;let n=t.replace($l,Ol),r=t.trimStart(),i=r.startsWith("{")||r.startsWith("[");if(!e.toLowerCase().includes("json")&&!i)return n;try{let o=Xo(JSON.parse(t));return o.changed?JSON.stringify(o.value):t}catch{return n}}function Xo(e,t){let n=EA(t);if(typeof e=="string"){let o=n&&e.trim()!==""?wA:e.replace($l,Ol);return{value:o,changed:o!==e}}if(Array.isArray(e)){let o=!1;return{value:e.map(a=>{let u=Xo(a,t);return o=o||u.changed,u.value}),changed:o}}if(!IA(e))return{value:e,changed:!1};let r=!1;return{value:Object.fromEntries(Object.entries(e).map(([o,s])=>{let a=Xo(s,n?t:o);return r=r||a.changed,[o,a.value]})),changed:r}}function EA(e){return e!==void 0&&bA.has(e.toLowerCase())}function vA(e){let t=e.headers;return t?t instanceof Headers?t.get("content-type")??"":Array.isArray(t)?t.find(([n])=>n.toLowerCase()==="content-type")?.[1]??"":Object.entries(t).find(([n])=>n.toLowerCase()==="content-type")?.[1]??"":""}function Fl(e){let t=typeof e.body=="string"?e.body:"";return t?ql(vA(e),t):""}function xA(e,t){return Jr(e,{method:t.method,body:Fl(t)})}function IA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DA(e){let t=e.toLowerCase();return!t||t.startsWith("text/")?!1:!(t.includes("json")||t.includes("xml")||t.includes("javascript")||t.includes("x-www-form-urlencoded"))}function TA(e){let t=e.bodyEncoding==="base64"?Pl.from(e.body,"base64"):e.body;return new Response(t,{status:e.status,headers:e.contentType?{"content-type":e.contentType}:{}})}function In(e){let t=e.realFetch??fetch;if(e.mode==="record")return lA(e.dir,{recursive:!0}),(async(r,i={})=>{let o=String(r),s=await t(r,i),a=Fl(i),u={...i,body:a},l=Jr(o,u),c=e.naming==="readable"?AA(e.dir,o,u,l):Ml(o,u),d=e.naming==="readable"?zr(e.dir,c):Dl(e.dir,l),p=Wl(d)??{request:{method:(i.method??"GET").toUpperCase(),url:o,...a?{body:a}:{},signatureHash:Hr(l)},responses:[]};p.request.signatureHash=Hr(l),delete p.request.signature,a&&(p.request.body=a);let g=await CA(s.clone());return p.responses.push(g),SA(d,hA(JSON.stringify(p))),e.manifestPath&&cA(e.manifestPath,`${c}
29
+ `),s});let n=new Map;return(async(r,i={})=>{let o=String(r),s=xA(o,i),a=ts(Dl(e.dir,s))??RA(e.dir,s);if(!a||a.responses.length===0)throw new Error(`cassette replay miss: no recorded response for ${s}`);let u=Math.min(n.get(s)??0,a.responses.length-1);return n.set(s,u+1),TA(a.responses[u])})}var Zo,$l,wA,Ol,bA,Nl=v(()=>{"use strict";Zo=200,$l=/eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,wA="redacted.contract.fixture.credential",Ol="redacted.contract.fixture.jwt",bA=new Set(["accesstoken","access_token","token","set-cookie"])});import{spawn as PA}from"node:child_process";import{copyFileSync as _A,existsSync as $A,mkdirSync as OA,readFileSync as MA,unlinkSync as WA,writeFileSync as LA}from"node:fs";import{homedir as Ul,tmpdir as qA}from"node:os";import{dirname as FA,join as Kr}from"node:path";function VA(){let e=process.env.AGENT_BROWSER_NAMESPACE?.trim(),t=e?Kr(Ul(),".agent-browser","namespaces",e,"run"):Kr(Ul(),".agent-browser");return Kr(t,`${Bl}.pid`)}function zA(e,t){let n=t.readFileSync(e,"utf-8"),r=JSON.parse(n);if(!Array.isArray(r.cookies))throw new T("auth_login_failed",`agent-browser state file at ${e} has no cookies array`);return r.cookies.map(i=>({name:String(i.name??""),value:String(i.value??""),domain:String(i.domain??"marquee.gs.com"),path:String(i.path??"/"),expires:typeof i.expires=="number"&&i.expires>=0?i.expires:void 0,httpOnly:i.httpOnly===!0,secure:i.secure===!0,sameSite:Hl(i.sameSite)})).filter(i=>i.name&&i.value)}function Hl(e){if(e==="Lax"||e==="Strict"||e==="None")return e}function zl(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"){let n=e;if(n.path==="agent-browser"||n.syscall==="spawn agent-browser"||n.syscall==="spawn"&&n.path==="agent-browser")return!0}let t=e instanceof Error?e.message:String(e);return t.includes("spawn agent-browser ENOENT")||t.includes("agent-browser: command not found")}function Gl(e){return e instanceof T?e:zl(e)?new T("auth_login_failed",ns):new T("auth_login_failed",`Login failed: ${e.message}. Run: marquee auth login --headed`)}var NA,UA,Bl,jA,jl,Vl,Yr,ns,GA,BA,HA,Dn,JA,Jl=v(()=>{"use strict";ge();Vr();En();NA="https://marquee.gs.com/s/",UA="https://marquee.gs.com/s/research",Bl="marquee-login",jA="research";jl=120,Vl=15,Yr=250,ns="agent-browser is not installed or not on PATH. Install agent-browser or add it to PATH, then rerun `marquee auth login`.",GA=`(async () => { let authed = false; try { if (location.hostname === "marquee.gs.com") { const r = await fetch("/v1/users/self", { credentials: "include" }); authed = r.ok; } } catch (e) { authed = false; } if (authed) return "authed"; return document.querySelector('input[name="username"]') ? "form" : "pending"; })()`,BA='(async () => { try { const r = await fetch("/research/session-exchange", { credentials: "include" }); return r.ok; } catch { return false; } })()',HA={copyFileSync:_A,existsSync:$A,mkdirSync:OA,readFileSync:MA,unlinkSync:WA,writeFileSync:LA},Dn=class{jarPath;spawnFn;statePathFactory;loginUrl;sleep;fileSystem;loginPidPath;constructor(t){this.jarPath=t.jarPath,this.spawnFn=t.spawnFn??JA,this.statePathFactory=t.statePathFactory??(()=>Kr(qA(),`marquee-state-${Date.now()}.json`)),this.loginUrl=t.loginUrl??NA,this.fileSystem={...HA,...t.fileSystem},this.loginPidPath=t.loginPidPath??VA(),this.sleep=t.sleep??(async n=>{await new Promise(r=>{setTimeout(r,n)})})}async login(t){let n=this.statePathFactory(),r,i=!1;try{this.fileSystem.existsSync(this.loginPidPath)&&await this.run(["close"],5e3);let s=t.headed===!1?[]:["--headed"];if(await this.run([...s,"open",this.loginUrl],6e4),i=!0,await this.waitForAuth(t.sso!==void 0)==="form"&&t.sso){let{user:c,pass:d}=t.sso;await this.run(["wait",'input[name="username"]'],3e4),await this.run(["fill",'input[name="username"]',c],3e4),await this.run(["press","Enter"],3e4),await this.run(["wait",'input[type="password"]'],3e4),await this.run(["fill",'input[type="password"]',d],3e4),await this.run(["press","Enter"],3e4),await this.waitForAuth(!1)}await this.captureState(n),this.persistState(n,t.extraStatePaths);let u=await this.run(["tab"],1e4),l=/→\s*\[(t\d+)\]/.exec(u.stdout)?.[1];if(await this.run(["tab","new","--label",jA,UA],6e4),l&&await this.run(["tab",l],1e4),!await this.waitForResearchSession())throw new T("auth_login_failed",`Research session could not be established within ${Vl} seconds. Rerun: marquee auth login`);await this.captureState(n),this.persistState(n,t.extraStatePaths),await this.run(["close"],5e3),i=!1}catch(s){r=s}let o;if(i||r!==void 0&&this.fileSystem.existsSync(this.loginPidPath))try{await this.run(["close"],5e3)}catch(s){i&&(o=s)}if(this.fileSystem.existsSync(n))try{this.fileSystem.unlinkSync(n)}catch(s){o===void 0&&(o=s)}if(r)throw Gl(r);if(o)throw Gl(o)}async assertAgentBrowserAvailable(){let t;try{t=qt(["--version"])}catch{throw new T("auth_login_failed",ns)}try{await this.spawnFn(t.file,t.args,{timeoutMs:5e3})}catch(n){throw zl(n)?new T("auth_login_failed",ns):n}}async isAuthenticated(){return dt(this.jarPath).cookies.length>0}run(t,n){let r=qt(["--session",Bl,...t]);return this.spawnFn(r.file,r.args,{timeoutMs:n})}async waitForAuth(t){let n=jl*1e3/Yr;for(let r=0;r<n;r+=1){let{stdout:i}=await this.run(["eval",GA],1e4),o=i.trim().replace(/^"|"$/g,"");if(o==="authed")return"authed";if(t&&o==="form")return"form";await this.sleep(Yr)}throw new T("auth_login_failed",`Login did not complete within ${jl} seconds`)}persistState(t,n){let i={cookies:zA(t,this.fileSystem),updatedAt:Date.now()};if(Or(this.jarPath,i),n)for(let o of n)this.fileSystem.mkdirSync(FA(o),{recursive:!0}),this.fileSystem.copyFileSync(t,o)}async captureState(t){let{stdout:n}=await this.run(["cookies","get","--json"],1e4),i=(JSON.parse(n).data?.cookies??[]).map(o=>({name:String(o.name??""),value:String(o.value??""),domain:String(o.domain??""),path:String(o.path??"/"),expires:typeof o.expires=="number"?o.expires:-1,httpOnly:o.httpOnly===!0,secure:o.secure===!0,sameSite:Hl(o.sameSite)??"Lax"}));if(i.length===0)throw new T("auth_login_failed","Login captured no cookies from the browser. Rerun: marquee auth login");this.fileSystem.writeFileSync(t,JSON.stringify({cookies:i,origins:[]}))}async waitForResearchSession(){let t=Vl*1e3/Yr;for(let n=0;n<t;n+=1){let{stdout:r}=await this.run(["eval",BA],1e4);if(r.trim()==="true")return!0;await this.sleep(Yr)}return!1}};JA=(e,t,n={})=>new Promise((r,i)=>{let o=PA(e,t,{stdio:["pipe","pipe","pipe"]}),s="",a="",u=!1,l=n.timeoutMs?setTimeout(()=>{u=!0,o.kill("SIGTERM")},n.timeoutMs):void 0;o.stdout.on("data",c=>{s+=c.toString()}),o.stderr.on("data",c=>{a+=c.toString()}),o.on("close",c=>{if(l&&clearTimeout(l),u){i(new Error("ETIMEDOUT"));return}if(c===0){r({stdout:s,stderr:a});return}i(new Error(a.trim()||`agent-browser exit ${c}`))}),o.on("error",i),n.input&&o.stdin.write(n.input),o.stdin.end()})});function rs(e,t){return e==null?"\u2014":typeof e=="number"?Number.isInteger(e)?String(e):e.toFixed(t):String(e)}function YA(e){let t=e.filter(o=>typeof o=="number"&&!Number.isInteger(o));if(t.length===0)return 2;let n=2,r=t.filter(o=>{let s=Math.abs(o);return s>0&&s<.01});if(r.length>0&&r.length>=Math.max(1,Math.ceil(t.length*.1)))for(let o of r){let a=Math.floor(-Math.log10(Math.abs(o)))+2;a>n&&(n=Math.min(a,6))}let i=new Set(t.map(o=>o.toString())).size;if(i>1){let o=Math.min(Math.max(2,Math.ceil(i/2)),10);for(;n<6&&!(new Set(t.map(a=>a.toFixed(n))).size>=o);)n++}return n}function is(e,t){return e.padEnd(t)}function KA(e,t,n=5,r=5){let i=t.length<=n+r?t:t.slice(0,n),o=t.length<=n+r?[]:r>0?t.slice(-r):[],s=t.length-i.length-o.length,a=[...i,...o],u=e.map(d=>YA(t.map(f=>f[d]))),l=e.map((d,f)=>Math.max(d.length,...a.map(p=>rs(p[d],u[f]).length))),c=[e.map((d,f)=>is(d,l[f])).join(" ")];for(let d of i)c.push(e.map((f,p)=>is(rs(d[f],u[p]),l[p])).join(" "));s>0&&c.push(`... ${s} more`);for(let d of o)c.push(e.map((f,p)=>is(rs(d[f],u[p]),l[p])).join(" "));return c.map(d=>` ${d.trimEnd()}`).join(`
30
+ `)}function Tn(e,t={}){let n=t.firstN??5,r=t.lastN??5;return` - data ${e.summary} [@data, expand|eval]
31
+ ${KA(e.columns,e.rows,n,r)}`}var os=v(()=>{"use strict";An()});function Yl(e){return e==null?"":Array.isArray(e)?e.map(t=>Yl(t)).join(","):typeof e=="object"?JSON.stringify(e):String(e)}function Qr(e,t){return e.length===0?"":e.map(n=>t.map(r=>{let i=n[r],o=Yl(i);return o.length>120?`${o.slice(0,117)}...`:o}).join(" ")).join(`
32
+ `)}var ss=v(()=>{"use strict"});function Kl(e){return Number.isFinite(e)&&e>=0?Math.floor(e):0}function Ql(e){return Number.isFinite(e)&&e>=1?Math.floor(e):1}function Pn(e,t,n){let r=Kl(e),i=Ql(t),o=Math.max(1,Math.ceil(r/i)),s=Number.isFinite(n)?Math.floor(n):1,a=Math.min(Math.max(1,s),o),u=r===0?1:(a-1)*i+1,l=Math.min(a*i,r),c=Math.max(0,r-l);return{start:u,end:l,lastPage:o,hasNext:a<o,hasPrev:a>1,remaining:c}}function Zl(e,t,n,r){let i=Kl(e),o=Ql(t);if(i<=o)return"";let s=Pn(i,o,n);if(!s.hasNext)return" ... end of list.";let a=Number.isFinite(n)?Math.floor(n):1,l=Math.min(Math.max(1,a),s.lastPage)+1;return` ... ${s.remaining} more. \`marquee next @${r}\` for page ${l}.`}var as=v(()=>{"use strict"});function lt(e){let t=Array.isArray(e.options)?e.options:[],n=Array.isArray(e.rawValues)?e.rawValues:[],r=t.map((o,s)=>m(o)&&"rawValue"in o?{label:"label"in o?o.label:o.rawValue,rawValue:o.rawValue,rawExplicit:!0}:Object.prototype.hasOwnProperty.call(n,s)?{label:o,rawValue:n[s],rawExplicit:!0}:{label:o,rawValue:o}),i=Array.isArray(e.display)?e.display:r.map(o=>o.label);return{field:String(e.field??""),default:e.default,rawDefault:e.rawDefault,options:r,type:String(e.type??"String"),rawValues:n.length>0?n:void 0,totalOptions:typeof e.totalOptions=="number"?e.totalOptions:void 0,display:i.length>0?i:void 0,notParam:!!e.notParam,filterable:!!e.filterable,cgGroupIds:Array.isArray(e.cgGroupIds)?e.cgGroupIds.map(String):void 0,allOptions:Array.isArray(e.allOptions)?e.allOptions.map(String):void 0,allRawOptions:Array.isArray(e.allRawOptions)?e.allRawOptions.map(String):void 0,fillBlocked:us(e.fillBlocked)}}function us(e){return typeof e=="object"&&e!==null&&typeof e.reason=="string"?{reason:e.reason}:void 0}function ue(e){return e.replace(/\s+/g," ").trim()}var _n=v(()=>{"use strict";Q()});function jt(e){if(e==null)return"";if(Array.isArray(e))return e.map(t=>jt(t)).join(", ");if(typeof e=="object"){let t=e;return t.rdate&&typeof t.rdate=="object"?String(t.rdate.rule??""):JSON.stringify(e)}return String(e)}function nS(e){if(!Array.isArray(e))return jt(e);let t=e.map(i=>jt(i)).filter(Boolean),n=t.slice(0,XA),r=t.length-n.length;return`${n.join(", ")}${r>0?`, +${r} more`:""}`}function Ut(e){if(!m(e)||!m(e.rdate))return;let t=e.rdate.rule,n=e.value;if(!(typeof t!="string"||t.length===0||typeof n!="string"&&typeof n!="number"))return{rule:t,concrete:String(n)}}function ef(e){let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function ds(e,t){if(e.rule!==t.rule||e.concrete===t.concrete)return;let n=ef(e.concrete),r=ef(t.concrete);if(!(n===void 0||r===void 0||n<=r))return n}function nf(e,t,n){let r={rule:t,concrete:n},i;for(let o of e.options||[]){let s=Ut(o.rawValue);if(!s)continue;let a=ds(s,r);a!==void 0&&(!i||a>i.ms)&&(i={rawValue:o.rawValue,concrete:s.concrete,ms:a})}return i}function rS(e,t,n){return nf(e,t,n)?.concrete}function iS(e){let t=Ut(e.rawDefault);return e.type==="Date"&&t?nf(e,t.rule,t.concrete)?.rawValue??e.rawDefault:e.rawDefault}function oS(e,t=!1){let n=nS(e.default);if(!t||e.type!=="Date")return n;let r=Ut(e.rawDefault);if(!r)return n;let i=rS(e,r.rule,r.concrete),o=n||r.rule;if(!o||o===r.concrete||o.includes(r.concrete))return o;let s=i??r.concrete;return`${o} [${s}]`}function sS(e){let t=[],n=new Map,r=new Set;for(let i of e){let o=(n.get(i)??0)+1;n.set(i,o);let s=o>1?`${i}_${o}`:i;for(;r.has(s);){let a=(n.get(i)??0)+1;n.set(i,a),s=`${i}_${a}`}r.add(s),t.push(s)}return t}function rf(e){return e.split(/\s+/).filter(Boolean).map((t,n)=>{let r=/^[A-Z0-9]+$/.test(t)?t.toLowerCase():t;return n===0?`${r[0]?.toLowerCase()??""}${r.slice(1)}`:`${r[0]?.toUpperCase()??""}${r.slice(1)}`}).join("")}function $n(e){return e==="Context"?"Asset":e==="RelativeDate"?"Enum":e}function aS(e){let t=$n(e.type),r=(Array.isArray(e.display)&&e.display.length>0?e.display:e.options).map(a=>jt(a)).filter(Boolean),i=r.slice(0,tf);if(!QA.has(e.type)||i.length===0)return`(${t})`;let o=Math.max(e.totalOptions??r.length,r.length);if((t==="Asset"||t==="AssetList")&&o>eS)return`(${t}: ${o} options)`;let s=o-i.length;return`(${t}: ${i.join(", ")}${s>0?`, +${s} more`:""})`}function cs(e,t){return t?`${t}.${e}`:e}function uS(e){let t=e.map(i=>i.title).filter(Boolean);if(t.length===0)return"new dashboard";let n=t.slice(0,3),r=t.length>n.length?", ...":"";return`${n.join(", ")}${r}`}function fs(e,t="",n,r,i=!1){let o=$n(e.type),s=Xl[e.type]??Xl[o]??"fill",a=`${t}${rf(e.field)}`,u,c=(Array.isArray(e.display)&&e.display.length>0?e.display:e.options).map(h=>jt(h)).filter(Boolean).length,f=Math.max(e.totalOptions??c,c)-Math.min(c,tf);(e.filterable||f>0)&&ZA.has(o)?u=`${s}|filter`:u=s;let p=oS(e,i),g=p&&!tS.test(p);return` - ${e.field}${g?` = ${p}`:""} ${aS(e)} [@${cs(a,n)}, ${u}]`}function of(e){if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e}function Zr(e){if(Array.isArray(e)){let n=e.map(r=>Zr(r));return n.every(r=>r!==void 0)?n:void 0}let t=of(e);if(t!==void 0)return t;if(e&&typeof e=="object"){let r=Object.entries(e).map(([i,o])=>[i,Zr(o)]);if(r.every(([,i])=>i!==void 0))return Object.fromEntries(r)}}function dS(e,t,n){if(e.type!=="Date")return!0;let r=Ut(e.rawDefault),i=Ut(t),o=Ut(n);if(!r||!o)return!0;let s=i?ds(i,r):void 0,a=ds(o,r);if(a!==void 0)return s===void 0||a>s;if(s!==void 0)return!1;let u=i?.rule===r.rule&&i.concrete===r.concrete,l=o.rule===r.rule&&o.concrete===r.concrete;return!(u&&!l)}function cS(e){let t={},n=$n(e.type);for(let r of e.options){let i=of(r.label),o=Zr(r.rawValue);if(i===void 0||o===void 0||i===o&&n!=="Asset"&&n!=="AssetList"&&!r.rawExplicit)continue;let s=String(i);Object.prototype.hasOwnProperty.call(t,s)&&!dS(e,t[s],o)||(t[s]=o)}return Object.keys(t).length>0?t:void 0}function sf(e){let t=e.map(n=>lt(n)).filter(n=>!n.notParam);return t.length===0?"No results found.":["- params:",...t.map(n=>fs(n,"",void 0,void 0,!0).replace(/^ {4}/," "))].join(`
33
+ `)}function ps(e,t,n=""){if(!t.store)return;let r={},i=n||t.namespace,o=i?`${i}.`:"",s=`https://marquee.gs.com/s/marketview/widget/${e.id}${e.configurationId?`?config=${e.configurationId}`:""}`;if(r[`${o}link`]={type:"link",url:s},r[`${o}data`]={type:"data",widgetId:e.id,configurationId:e.configurationId,...e.chartId?{chartId:e.chartId}:{}},i){let a={type:"widget",id:e.id,title:e.title,configurationId:e.configurationId,...e.chartId?{chartId:e.chartId}:{}},u=e.params.find(l=>!l.notParam&&$n(l.type)==="Asset");u&&(a.contextField=u.field),r[i]=a}i&&Array.isArray(e.dashboards)&&(r[`${i}.dash`]={type:"dash",entityId:e.id,configurationId:e.configurationId,dashboards:e.dashboards});for(let a of e.params.filter(u=>!u.notParam)){let u=(Array.isArray(a.display)&&a.display.length>0?a.display:a.options).map(f=>jt(f)).filter(Boolean),l=Zr(iS(a)),c=cS(a),d={type:"param",field:a.field,value:a.default,paramType:$n(a.type),options:u,widgetId:e.id,configurationId:e.configurationId,...l!==void 0?{rawValue:l}:{},...c?{optionRawValues:c}:{},...e.chartId?{chartId:e.chartId}:{},...a.filterable&&a.cgGroupIds?{cgGroupIds:a.cgGroupIds}:{},...Array.isArray(a.allRawOptions)&&a.allRawOptions.length>0?{rawOptions:a.allRawOptions}:{}};Array.isArray(a.allOptions)&&a.allOptions.length>0&&((a.totalOptions??0)>u.length||a.allOptions.length>u.length)&&(d.allOptions=a.allOptions),r[`${o}${rf(a.field)}`]=d}t.store.mergeRefs(r)}function Xr(e,t={}){let n=t.namespace,r=[`- "${ue(e.title)}"`,` - link https://marquee.gs.com/s/marketview/widget/${e.id}${e.configurationId?`?config=${e.configurationId}`:""} [@${cs("link",n)}, open]`],i=e.params.map(o=>lt(o)).filter(o=>!o.notParam);if(i.length>0&&(r.push(" - params:"),r.push(...i.map(o=>fs(o,"",n,e.chartId,t.showConcreteDateDefaults)))),e.description){let[o,...s]=e.description.split(`
34
+ `).map(a=>a.trimEnd());r.push(` - description: ${o}`),r.push(...s.filter(a=>a.trim()!=="").map(a=>` ${a}`))}if(e.tags?.length&&r.push(` - tags: ${e.tags.join(", ")}`),e.sources?.length&&r.push(` - sources: ${e.sources.join(", ")}`),e.warnings?.length)for(let o of e.warnings)r.push(` - warning: ${ue(o)}`);return e.dataPreview&&r.push(n?e.dataPreview.replace(/@data/g,`@${n}.data`).replace(/@link/g,`@${n}.link`):e.dataPreview),Array.isArray(e.dashboards)&&r.push(` - add to dashboard: ${uS(e.dashboards)} [@${cs("dash",n)}, add]`),ps({...e,params:i},t),r.join(`
35
+ `)}function ft(e,t){let n=[];if(n.push(`- dashboard "${e.title}"`),e.identity&&n.push(` - ${e.identity}`),e.author&&n.push(` - author: ${e.author}`),e.description&&n.push(` - description: ${e.description}`),e.tags.length>0&&n.push(` - tags: ${e.tags.join(", ")}`),n.push(` - link ${e.link} [@${t.ns}.link, open]`),e.sections&&e.sections.length>0){let a=n.length;return n.push(` - ${e.total} widgets (${e.sections.length} sections)`),lS(n,e,t)&&(n[a]+=` [@${t.ns}, expand]`),n.join(`
36
+ `)}let{start:r,end:i}=Pn(t.cursor.total,t.cursor.pageSize,t.cursor.page);if(t.cursor.total<=t.cursor.pageSize)n.push(` - ${t.cursor.total} widgets:`);else{let a=r===i?`${r}`:`${r}\u2013${i}`;n.push(` - ${t.cursor.total} widgets (showing ${a}, page ${t.cursor.page}):`)}e.widgets.slice(r-1,i).forEach((a,u)=>{let l=r+u;af(n,a,`${t.ns}.w${l}`,t," ")});let s=Zl(t.cursor.total,t.cursor.pageSize,t.cursor.page,t.ns);return s&&n.push(s),n.join(`
37
+ `)}function lS(e,t,n){let r=n.expandSections==="all",i=new Set(Array.isArray(n.expandSections)?n.expandSections:[]),o=0,s=!1,a=!1;return t.sections?.forEach((u,l)=>{let c=l+1,d=!s&&o+u.widgetCount<=n.cursor.pageSize,f=d||l===0,p=null;f?d?o+=u.widgetCount:(p=Math.max(n.cursor.pageSize-o,0),o+=p,s=!0):s=!0;let g=r||i.has(c),h=g||f,y=`${n.ns}.s${c}`;if(n.store?.mergeRefs({[y]:{type:"section",dashboardRef:n.ns,sectionIndex:c,...u.sectionId?{sectionId:u.sectionId}:{},...n.dashboardId?{dashboardId:n.dashboardId}:{}}}),!h){a=!0,e.push(` - ${u.title} (${u.widgetCount}) [@${y}, expand]`);return}let w=!g&&p!==null&&p<u.widgetCount,b=w?p:u.widgetCount;if(e.push(` - ${u.title} (${u.widgetCount}):`),t.widgets.slice(u.startIndex,u.startIndex+b).forEach((S,C)=>{let x=u.startIndex+C+1;af(e,S,`${n.ns}.w${x}`,n," ")}),w){a=!0;let S=u.widgetCount-b;e.push(` ... ${S} more. \`marquee expand @${y}\` for all ${u.widgetCount}.`)}}),a}function af(e,t,n,r,i){if(r.expand&&t.full){let o=Xr(t.full,{store:r.store,namespace:n,showConcreteDateDefaults:!0}).split(`
38
+ `);o[0]=`${o[0]} [@${n}, load]`;for(let s of o)e.push(`${i}${s}`);return}for(let o of Dt(t.title,t.paramNames??[],n).split(`
39
+ `))e.push(`${i}${o}`);if(r.store){let o={type:"widget",id:t.id,title:t.title,configurationId:t.configurationId??"",...t.underlyingChartId?{underlyingChartId:t.underlyingChartId}:{},...Array.isArray(t.configurationParameters)&&t.configurationParameters.length>0?{configurationParameters:t.configurationParameters}:{},...t.childId?{childId:t.childId}:{},...r.dashboardId?{dashboardId:r.dashboardId}:{}};r.store.mergeRefs({[n]:o})}}function fS(e,t,n={}){let r={title:e.title,id:e.id,configurationId:e.configurationId??"",chartId:e.chartId,params:e.params??[],labels:e.labels},i=[];i.push(`- "${e.title}" [@${t}, load]`),i.push(` - link https://marquee.gs.com/s/marketview/widget/${e.id}${e.configurationId?`?config=${e.configurationId}`:""} [@${t}.link, open]`),e.labels?.length&&i.push(` - labels: ${sS(e.labels).join(", ")}`);let o=(e.params??[]).map(s=>lt(s)).filter(s=>!s.notParam);return o.length>0&&(i.push(" - params:"),i.push(...o.map(s=>fs(s,`${t}.`,void 0,e.chartId,!0)))),ps({...r,params:o},n,t),i.join(`
40
+ `)}function ls(e){return pS[e]}function gS(e,t){if(e.url)return e.url.startsWith("http://")||e.url.startsWith("https://")?e.url:`https://marquee.gs.com${e.url.startsWith("/")?"":"/"}${e.url}`;let n=e.contextId??e.id;return t==="thematic"?`https://marquee.gs.com/s/marketview/dashboards/${n}`:t==="asset"?`https://marquee.gs.com/s/marketview/asset/${n}`:t==="country"?`https://marquee.gs.com/s/marketview/country/${n}`:`https://marquee.gs.com/s/marketview/portfolio/${n}`}function mS(e){let t=e.dashboardType&&e.dashboardType!=="Dashboard"?e.dashboardType:"Thematic";return t.slice(0,1).toUpperCase()+t.slice(1)}function hS(e,t){if(t==="thematic"){let n=mS(e);return typeof e.widgetCount=="number"?[`${n} \xB7 ${e.widgetCount} widgets`]:[n]}if(t==="asset"){let n=[e.assetClass,e.assetType,e.ticker,e.bbid].filter(r=>typeof r=="string"&&r.length>0).join(" \xB7 ");return n?[n]:[]}return t==="country"?e.subRegion?[e.subRegion]:[]:e.currency?[e.currency]:[]}function yS(e,t,n,r){let i=gS(e,n),o=[`- "${e.title}" [@${t}, load]`,...hS(e,n).map(s=>` - ${s}`)];return r.store&&r.store.mergeRefs({[t]:{type:"dashboard",id:e.contextId??e.id,contextId:e.contextId??e.id,contextType:n},[`${t}.link`]:{type:"link",url:i}}),o.join(`
41
+ `)}function wS(e,t){let n=t.searchNamespace,r=e.filter(l=>l.type==="widget"),i=e.map(l=>({item:l,subtype:ls(l.type)})).filter(l=>!!l.subtype),o=[],s=new Set(r.map(l=>l.searchMode).filter(Boolean)).size>1,a=[];if(s){let l=["keyword","semantic","llm-reranked"],c=new Map;for(let d of r){let f=d.searchMode??"keyword",p=c.get(f)??[];p.push(d),c.set(f,p)}for(let d of l){let f=c.get(d);f&&f.length>0&&a.push({label:`widgets \u2014 ${d} (${f.length})`,widgets:f})}for(let[d,f]of c)l.includes(d)||a.push({label:`widgets \u2014 ${d} (${f.length})`,widgets:f})}else r.length>0&&a.push({label:`widgets (${r.length})`,widgets:r});let u=0;for(let l of a){o.length>0&&o.push(""),o.push(`${l.label}:`);for(let c of l.widgets){u+=1;let d=`w${u}`,f=n?`${n}.${d}`:d;if(c.full){let g=Xr(c.full,{...t,namespace:f,showConcreteDateDefaults:!0}).split(`
42
+ `);g[0]=`${g[0]} [@${f}, load]`;for(let h of g)o.push(` ${h}`);continue}let p=c.paramNames??c.params?.filter(g=>!g.notParam).map(g=>g.field)??[];for(let g of Dt(c.title,p,f,{...t,widget:{id:c.id,title:c.title,configurationId:c.configurationId??""}}).split(`
43
+ `))o.push(` ${g}`)}}return i.length>0&&(o.length>0&&o.push(""),o.push(`dashboards (${i.length}):`),i.forEach(({item:l,subtype:c},d)=>{let f=`d${d+1}`,p=n?`${n}.${f}`:f;for(let g of yS(l,p,c,t).split(`
44
+ `))o.push(` ${g}`)})),o.join(`
45
+ `)}function uf(e,t={}){let n=e.some(a=>a.type==="widget"||ls(a.type)),r=e.every(a=>a.type==="widget"||ls(a.type));if(n&&r)return wS(e,t);let i=t.searchNamespace,o={},s=[];for(let a of e){o[a.type]=(o[a.type]??0)+1;let l=`${a.type[0]}${o[a.type]}`,c=i?`${i}.${l}`:l;if(s.length>0&&s.push(""),a.type==="widget")s.push(fS(a,c,t));else if(a.type==="article"){s.push(`- content "${a.title}" [@${c}, open|load]`);let d=[];a.publicationDate&&d.push(a.publicationDate.slice(0,10)),a.authors?.length&&d.push(a.authors.join(", ")),a.source&&d.push(a.source),d.length>0&&s.push(` ${d.join(" \xB7 ")}`);let f=a.quote??a.synopsis;f&&s.push(` ${ue(f)}`),t.store&&t.store.mergeRefs({[c]:{type:"article",id:a.id,...a.url?{url:a.url}:{}}})}else if(a.type==="country")s.push(`- "${a.title}"`),a.id&&s.push(` - id: ${a.id}`),a.region&&s.push(` - region: ${a.region}`),a.subRegion&&a.subRegion!==a.region&&s.push(` - sub-region: ${a.subRegion}`);else if(a.type==="asset"){s.push(`- "${a.title}" [@${c}, load]`);let d=[a.assetClass,a.assetType,a.ticker,a.bbid].filter(f=>typeof f=="string"&&f.length>0);d.length>0&&s.push(` - ${d.join(" \xB7 ")}`),t.store&&t.store.mergeRefs({[c]:{type:a.type,id:a.id}})}else s.push(`- ${a.type} "${a.title}" [@${c}, load]`),t.store&&t.store.mergeRefs({[c]:{type:a.type,id:a.id}})}return s.join(`
46
+ `)}function bS(e){if(e==="widget")return"w";if(e==="dashboard")return"d";if(e==="asset")return"a";if(e==="link")return"l"}function df(e,t={}){let n=t.searchNamespace,r={},i=["- discover"],o={},s=e.reduce((l,c)=>l+(c.entries?.length??0),0),a=t.entryLimit&&t.entryLimit>0?t.entryLimit:void 0,u=0;for(let l of e){if(a!==void 0&&u>=a)break;i.push(` - ${ue(l.section)}`);let c=l.entries??[];for(let d of c){if(a!==void 0&&u>=a)break;u+=1;let f=d.type.toLowerCase(),p=bS(f);if(!p){i.push(` - "${d.title}"`);continue}r[f]=(r[f]??0)+1;let g=n?`${n}.${p}${r[f]}`:`${p}${r[f]}`;if(f==="widget"){let h={title:d.title,id:d.id??"",configurationId:d.configurationId??"",params:[]};i.push(` - "${d.title}" [@${g}, load]`),ps(h,t,g)}else f==="link"?(i.push(` - link "${d.title}" [@${g}, open]`),d.url&&(o[g]={type:"link",url:d.url})):(i.push(` - "${d.title}" [@${g}, load]`),o[g]={type:f,id:d.id??""})}}return a!==void 0&&s>u&&i.push(` ... ${s-u} more entries not shown`),t.store&&Object.keys(o).length>0&&t.store.mergeRefs(o),i.join(`
47
+ `)}var Xl,QA,ZA,tf,XA,eS,tS,pS,Vt=v(()=>{"use strict";as();_n();$e();Q();Xl={Asset:"fill",AssetList:"select",Context:"fill",Enum:"select",EnumList:"select",String:"fill",Date:"fill",Boolean:"check",Integer:"fill",Portfolio:"fill",RelativeDate:"select"},QA=new Set(["Asset","AssetList","Enum","EnumList","Context","Portfolio","RelativeDate"]),ZA=new Set(["Asset","AssetList","Enum","EnumList","Portfolio"]),tf=30,XA=8,eS=1500,tS=/^[A-Z0-9]{15,}$/;pS={"thematic-dashboard":"thematic","asset-dashboard":"asset","country-dashboard":"country","portfolio-dashboard":"portfolio"}});function Gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.type==="content-search"&&typeof e.query=="string"&&typeof e.link=="string"&&typeof e.totalRecords=="number"&&Array.isArray(e.results)}function RS(e){return e.documentSource==="sec_div"?"cm":"cr"}function gs(e,t){let n=RS(e);return t[n]+=1,`${n}${t[n]}`}function kS(e){let t={link:{type:"link",url:e.link}};if(e.results.length===0)return t;t.sort={type:"search-control",control:"sort",paramType:"Enum",value:e.sort==="relevance"?"relevance":"time",options:["time","relevance"]},t.from={type:"search-control",control:"from",paramType:"Date",...typeof e.from=="string"&&e.from.length>0?{value:e.from}:{}},t.to={type:"search-control",control:"to",paramType:"Date",...typeof e.to=="string"&&e.to.length>0?{value:e.to}:{}};let n={cm:0,cr:0};return e.results.forEach(r=>{let i=typeof r.url=="string"&&r.url.length>0?r.url:void 0;t[gs(r,n)]={type:"article",id:String(r.id??""),title:String(r.title??""),...i?{url:i}:{},...typeof r.path=="string"?{path:r.path}:{},...typeof r.downloadPath=="string"?{downloadPath:r.downloadPath}:{},...typeof r.documentSource=="string"?{source:r.documentSource}:{},...typeof r.source=="string"?{sourceDisplayName:r.source}:{}}}),Array.isArray(e.facets)&&e.facets.forEach(r=>{let i=typeof r.field=="string"?r.field:"";if(!i)return;let o=Array.isArray(r.values)?r.values.length:0;t[i]={type:"facet",field:i,...typeof r.label=="string"?{label:r.label}:{},valueCount:o}}),t}function ei(e,t,n){e.storeArtifact({namespace:t,root:{type:"search",surface:"content",query:n.query,link:n.link,totalRecords:n.totalRecords,limit:typeof n.limit=="number"&&Number.isFinite(n.limit)&&n.limit>0?n.limit:10,sort:n.sort==="relevance"?"relevance":"time",...typeof n.from=="string"&&n.from.length>0?{from:n.from}:{},...typeof n.to=="string"&&n.to.length>0?{to:n.to}:{},...Array.isArray(n.appliedFilters)?{appliedFilters:n.appliedFilters}:{},...Array.isArray(n.appliedFacets)?{appliedFacets:n.appliedFacets}:{}},refs:kS(n),payload:n})}var On=v(()=>{"use strict"});function Te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function AS(e){return{type:String(e.type??""),title:String(e.title??e.name??""),id:String(e.id??""),configurationId:e.configurationId?String(e.configurationId):void 0,chartId:e.chartId?String(e.chartId):void 0,params:Array.isArray(e.params)?e.params.map(t=>lt(t)):void 0,paramNames:Array.isArray(e.paramNames)?e.paramNames.map(String):void 0,labels:Array.isArray(e.labels)?e.labels.map(String):void 0,region:typeof e.region=="string"?e.region:void 0,subRegion:typeof e.subRegion=="string"?e.subRegion:void 0,publicationDate:typeof e.publicationDate=="string"?e.publicationDate:void 0,synopsis:typeof e.synopsis=="string"?e.synopsis:void 0,quote:typeof e.quote=="string"?e.quote:void 0,authors:Array.isArray(e.authors)?e.authors.map(String):void 0,source:typeof e.source=="string"?e.source:void 0,url:typeof e.url=="string"?e.url:void 0,assetClass:typeof e.assetClass=="string"?e.assetClass:void 0,assetType:typeof e.assetType=="string"?e.assetType:void 0,ticker:typeof e.ticker=="string"?e.ticker:void 0,bbid:typeof e.bbid=="string"?e.bbid:void 0,dashboardType:typeof e.dashboardType=="string"?e.dashboardType:void 0,widgetCount:typeof e.widgetCount=="number"?e.widgetCount:void 0,currency:typeof e.currency=="string"?e.currency:void 0,contextId:typeof e.contextId=="string"?e.contextId:void 0,contextType:typeof e.contextType=="string"?e.contextType:void 0,full:Te(e.full)?e.full:void 0,searchMode:typeof e.searchMode=="string"?e.searchMode:void 0}}function SS(e){let t=[],n=e.warning;typeof n=="string"&&n.length>0&&t.push(`warning: ${n}`);let r=e.hint;return typeof r=="string"&&r.length>0&&t.push(`hint: ${r}`),t}function CS(e){return Te(e)&&e.type==="content-search"&&typeof e.query=="string"&&typeof e.link=="string"&&typeof e.totalRecords=="number"&&Array.isArray(e.results)}function ms(e){return e>1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:String(e)}function ES(e){let t=typeof e.name=="string"?e.name:"";if(!t)return;let n=typeof e.count=="number"&&Number.isFinite(e.count)?e.count:0;return`${e.selected===!0?"\u2713 ":""}${ue(t)} (${ms(n)})`}function cf(e){return e.selected===!0?!0:Array.isArray(e.values)&&e.values.some(t=>Te(t)&&t.selected===!0)}function vS(e){return e.map((t,n)=>({facet:t,index:n})).sort((t,n)=>Number(cf(n.facet))-Number(cf(t.facet))||t.index-n.index).map(({facet:t})=>t)}function xS(e){let t=typeof e.field=="string"?e.field:"";if(!t||!Array.isArray(e.values))return;let n=e.values.filter(Te).map((s,a)=>({value:s,index:a})).sort((s,a)=>+(a.value.selected===!0)-+(s.value.selected===!0)||s.index-a.index).map(({value:s})=>s),r=n.slice(0,5).map(ES).filter(s=>!!s);if(r.length===0)return;let i=n.length-r.length,o=i>0?`, +${ms(i)} more`:"";return` - ${t}: ${r.join(", ")}${o}`}function Bt(e,t){return t?`${t}.${e}`:e}function lf(e){return Array.isArray(e)?e.flatMap(t=>{if(!Te(t))return[];let n=typeof t.field=="string"?t.field:"",r=typeof t.value=="string"?t.value:"";return n&&r?[`${n}=${ue(r)}`]:[]}):[]}function ff(e){return Array.isArray(e)?e.flatMap(t=>{if(!Te(t))return[];let n=typeof t.field=="string"?t.field:"",r=typeof t.name=="string"?t.name:"";return n&&r?[`${n}=${ue(r)}`]:[]}):[]}function pf(e,t){let n=typeof e=="string"&&e.length>0?e:void 0,r=typeof t=="string"&&t.length>0?t:void 0;if(!(!n&&!r))return`${n??""}..${r??""}`}function IS(e){if(!Array.isArray(e))return;let t=e.map(String).filter(r=>r.length>0);if(t.length===0)return;let n=t.slice(0,4);return t.length>n.length?`${n.join(", ")}, and others\u2026`:n.join(", ")}function DS(e,t){let n=[`- link ${e.link} [@${Bt("link",t)}, open]`,""];if(e.totalRecords===0||e.results.length===0)return n.push(`No contents match "${e.query}".`),n.join(`
48
+ `);let r=e.sort==="relevance"?"relevance":"time",i=[...lf(e.appliedFilters),...ff(e.appliedFacets),pf(e.from,e.to),r==="relevance"?"sort=relevance":void 0].filter(d=>typeof d=="string"&&d.length>0),o=[...lf(e.appliedFilters),...ff(e.appliedFacets)],s=pf(e.from,e.to);o.length>0&&s&&o.push(s);let a=i.length>0?` \xB7 ${i.join(" \xB7 ")}`:"";n.push(`contents (${e.results.length} of ${ms(e.totalRecords)}${a}):`);let u={cm:0,cr:0};e.results.forEach(d=>{let f=Bt(gs(d,u),t);n.push(` - "${ue(String(d.title??""))}" [@${f}, open|load]`);let p=[typeof d.publicationDate=="string"?d.publicationDate:void 0,typeof d.source=="string"?d.source:void 0,IS(d.authors)].filter(h=>typeof h=="string"&&h.length>0);p.length>0&&n.push(` - ${p.join(" \xB7 ")}`);let g=typeof d.snippet=="string"&&d.snippet.length>0?d.snippet:typeof d.synopsis=="string"?d.synopsis:void 0;g&&n.push(` - ${ue(g)}`)}),n.push("",`sort = ${r} (Enum: time, relevance) [@${Bt("sort",t)}, select]`),typeof e.from=="string"&&e.from.length>0&&n.push(`from = ${e.from} [@${Bt("from",t)}, fill]`),typeof e.to=="string"&&e.to.length>0&&n.push(`to = ${e.to} [@${Bt("to",t)}, fill]`);let c=(Array.isArray(e.facets)?vS(e.facets):[]).map(xS).filter(d=>!!d);if(c.length>0){let d=`expand|filter|select|unselect @${Bt("<field>",t)}`,f=o.length>0?`refine (narrowed to ${o.join(" \xB7 ")}) \u2014 \`${d}\`:`:`refine \u2014 \`${d}\`, or up-front \`--select <field>=<value>\`:`;n.push("",f,...c)}return n.join(`
49
+ `)}function TS(e,t,n){let r=`${e.surface}.${e.action}`;if(r==="marketview.widget-load"&&Te(t)){let i=Array.isArray(t.params)?t.params:[];return sf(i.map(o=>lt(o)))}if((r==="marketview.search"||r==="content.search"||r==="asset.search")&&Array.isArray(t)){let i=t.length===0?"No results found.":uf(t.map(s=>AS(s)),{store:n.store,searchNamespace:n.searchNamespace}),o=SS(t);return o.length>0?`${o.join(`
50
+ `)}
51
+ ${i}`:i}if(r==="content.search"&&CS(t))return DS(t,n.searchNamespace);if(r==="marketview.discover"&&Array.isArray(t))return df(t,{store:n.store,searchNamespace:n.searchNamespace,entryLimit:n.entryLimit});if(r==="content.get"&&Te(t))return gf(t,n.namespace,n.articleActions)}function PS(e){let t=String(e.id??""),n=String(e.symbol??e.name??e.short_name??e.bbid??"");return n.length>0?`${n} ${t}`:t}function Ht(e){return typeof e=="string"&&e.length>0?ue(e):void 0}function _S(e){let t=e.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/);return t?`${t[1]} ${t[2]}`:e.slice(0,10)}function $S(e){return typeof e!="string"||e.trim().length===0?[]:e.replace(/\r/g,"").split(`
52
+ `).map(t=>ue(t)).filter(Boolean)}function OS(e){let t=$S(e);return t.length===0?[]:t}function gf(e,t,n="get|open"){let r=ue(String(e.title??"")),i=t!==void 0&&/^(?:s\d+\.)?(?:cm|cr)\d+$/.test(t),o=t&&!i?` [@${t}, ${n}]`:"",s=t?` [@${/^(?:cm|cr)\d+$/.test(t)?`${t}.link`:t}, open]`:"",u=[`- ${i?"content":"article"} "${r}"${o}`],l=Ht(e.url);l&&u.push(` - link ${l}${s}`);let c=Ht(e.publicationDate);c&&u.push(` - date: ${_S(c)}`),Array.isArray(e.authors)&&e.authors.length>0&&u.push(` - authors: ${e.authors.map(String).join(", ")}`);let d=Ht(e.source);d&&u.push(` - source: ${d}`);let f=Ht(e.quote);f&&u.push(` - quote: ${f}`);let p=Ht(e.synopsis);if(p&&u.push(` - synopsis: ${p}`),typeof e.body=="string"&&(e.body.startsWith("opened in browser")||e.body.startsWith("browser open failed")))return u.push(` - body: ${ue(e.body)}`),u.join(`
53
+ `);let g=OS(e.body);if(g.length>0){u.push(" - body:");for(let h of g)u.push(` ${h}`)}else{let h=Ht(e.bodyUnavailableReason);h&&u.push(` - body unavailable: ${h}`)}return u.join(`
54
+ `)}function oe(e,t={}){if(e.status==="error"){let i=e.data?.result;return e.surface==="content"&&e.action==="get"&&Te(i)?gf(i,t.namespace,t.articleActions):`Error: ${e.errors[0]??e.data.error??"Unknown error"}`}if(e.status==="not_implemented")return`${e.surface} ${e.action} is not yet available.`;let n=e.data.result,r=TS(e,n,t);if(r!==void 0)return r;if(Array.isArray(n)&&n.length===0)return"No results found.";if(e.meta?.columns&&Array.isArray(n))return Qr(n,e.meta.columns);if(e.surface==="asset"&&e.action==="resolve"){let i=Te(e.data.result)?e.data.result:Te(e.data.asset)?e.data.asset:void 0;if(i)return PS(i)}return JSON.stringify(e.data,null,2)}var Me=v(()=>{"use strict";ss();Vt();_n();On()});function MS(e){return m(e)&&(e.status==="ok"||e.status==="error"||e.status==="not_implemented")&&(e.surface==="asset"||e.surface==="marketview"||e.surface==="content")&&typeof e.action=="string"&&m(e.data)&&Array.isArray(e.errors)}function Mn(e){return MS(e)?e:void 0}function Ze(e){return m(e)&&typeof e.type=="string"}function Wn(e){return e instanceof Re||e instanceof Error&&e.name==="TransportError"}function zt(e){return e.startsWith("@")?e.slice(1):e}function me(e){let t=e.trim();return/^(?:mw|md|ma|mp)[a-z0-9]+$/i.test(t)?t.toUpperCase():t}function ti(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let t=me(e);return t.startsWith("MW")?`https://marquee.gs.com/s/marketview/widget/${t}`:t.startsWith("MD")?`https://marquee.gs.com/s/marketview/dashboards/${t}`:t.startsWith("MA")?`https://marquee.gs.com/s/marketview/asset/${t}`:t.startsWith("MP")?`https://marquee.gs.com/s/marketview/portfolio/${t}`:e}function WS(e){return e.startsWith("/")?`https://marquee.gs.com${e}`:e}function ys(e){if(e.type==="link"&&typeof e.url=="string"&&e.url.length>0)return e.url;if(e.type==="widget"&&typeof e.id=="string"&&e.id.length>0){let t=typeof e.configurationId=="string"&&e.configurationId.length>0?`?config=${e.configurationId}`:"";return`https://marquee.gs.com/s/marketview/widget/${e.id}${t}`}if(e.type==="dashboard"&&typeof e.id=="string"&&e.id.length>0)return e.contextType==="asset"?`https://marquee.gs.com/s/marketview/asset/${e.id}`:e.contextType==="portfolio"?`https://marquee.gs.com/s/marketview/portfolio/${e.id}`:`https://marquee.gs.com/s/marketview/dashboards/${e.id}`;if(e.type==="asset"&&typeof e.id=="string"&&e.id.length>0)return`https://marquee.gs.com/s/marketview/asset/${e.id}`;if(e.type==="article"){let t=typeof e.url=="string"&&e.url.length>0?e.url:typeof e.path=="string"&&e.path.length>0?e.path:void 0;return t?WS(t):void 0}}function hf(e,t){if(!t.startsWith("@"))return{url:ti(t)};let n=fe(e,t);if(!n.ok)return{error:n.message};let r=ys(n.ref);return r?{url:r}:{error:`Error: ref @${n.cleanRef} cannot be opened in browser`}}function ke(e){let t=zt(e),[n]=t.split(".");return n??t}function je(e){if(e===void 0||!/^[1-9]\d*$/.test(e))return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function P(e,t){e(t.endsWith(`
55
+ `)?t:`${t}
56
+ `)}function k(e,t){process.exitCode=1,P(e,t)}function $(e,t){t&&P(e,t)}function LS(e,t){let n=Object.keys(e.getAllRefs()),r=ke(t),i=t[0]??"";return n.map((o,s)=>{let a=o===r?0:o.startsWith(`${r}.`)?1:i&&o.startsWith(i)?2:3;return{name:o,index:s,score:a}}).sort((o,s)=>o.score-s.score||o.index-s.index).map(({name:o})=>o)}function hs(e,t){let n=LS(e,t),r=n.slice(0,6);if(r.length===0)return["Hint: run the previous command again or use one of the refs printed above."];let i=n.length>r.length?", ...":"";return[`Hint: current refs include ${r.map(o=>`@${o}`).join(", ")}${i}.`,"Run the previous command again or use one of the refs printed above."]}function mf(e){return e.endsWith(".data")?e.slice(0,-5):ke(e)}function qS(e){return e.type==="widget"||e.type==="dashboard"||e.type==="asset"}function Jt(e,t,n={}){return[`${n.prefix??"Error"}: ref @${t} not found`,...hs(e,t)].join(`
57
+ `)}function ws(e,t){let n=e.resolveRef(t);if(Ze(n)){let r=mf(t);return[`Error: ref @${t} is a ${n.type} ref, not a data ref`,t.endsWith(".data")?`Hint: load @${r} again and use the printed @${t} ref.`:`Hint: use a @${t}.data ref if it was printed, or load @${t} again.`].join(`
58
+ `)}if(t.endsWith(".data")){let r=mf(t),i=e.resolveRef(r);return Ze(i)?[`Error: ref @${t} not found; @${r} exists but has no data ref`,...qS(i)?[`Hint: load @${r} again and use the printed @${t} ref.`]:hs(e,t)].join(`
59
+ `):[`Error: ref @${t} not found because @${r} is unknown`,...hs(e,t)].join(`
60
+ `)}return[Jt(e,t),`Hint: use a @${t}.data ref if it was printed, or load @${t} again.`].join(`
61
+ `)}function _(e,t){return Wn(t)?t.message:`${e} failed: ${t instanceof Error?t.message:String(t)}`}function le(e,t){return{mergeRefs(n){e.setRefs(t,n)}}}function Xe(e,t){let n=zt(t),r=e.resolveRef(n);return{cleanRef:n,ref:Ze(r)?r:void 0}}function fe(e,t){let{cleanRef:n,ref:r}=Xe(e,t);return r?{ok:!0,cleanRef:n,ref:r}:{ok:!1,cleanRef:n,message:Jt(e,n)}}var Z=v(()=>{"use strict";xn();Q()});function bs(){let e={};return{refs:e,store:{mergeRefs(t){Object.assign(e,t)}}}}function Rs(e,t,n,r,i){let o=n.refs[t]??r,s=Object.fromEntries(Object.entries(n.refs).filter(([a])=>a!==t));e.storeArtifact({namespace:t,root:o,refs:s,payload:i})}function kf(e){e.status==="error"&&(process.exitCode=1)}function Ln(e,t,n=!1){if(kf(t),n){let{raw:r,...i}=t.data??{};e(`${JSON.stringify({...t,data:i})}
62
+ `)}else e(`${oe(t)}
63
+ `)}function FS(e){return`marketview widget expects a widget ID like MW..., got "${e}". Use \`marquee marketview search "${e}"\` to find widgets by query.`}function NS(){let e=process.env.MARQUEE_NOW;if(e){let t=new Date(e);if(!Number.isNaN(t.getTime())&&US(e))return t;throw new Error(`Invalid MARQUEE_NOW value: ${e}`)}return new Date}function US(e){let t=/^(\d{4})-(\d{2})-(\d{2})(?:T|$)/.exec(e);if(!t)return!0;let[,n,r,i]=t,o=Number(n),s=Number(r),a=Number(i),u=new Date(Date.UTC(o,s-1,a));return u.getUTCFullYear()===o&&u.getUTCMonth()===s-1&&u.getUTCDate()===a}function Yt(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}function jS(e){let t=String(e.getUTCFullYear()).padStart(4,"0"),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0");return`${t}-${n}-${r}`}function VS(e){let t=NS(),n;switch(e.toUpperCase()){case"YTD":n=new Date(Date.UTC(t.getUTCFullYear(),0,1));break;case"1M":n=Yt(t),n.setUTCMonth(n.getUTCMonth()-1);break;case"3M":n=Yt(t),n.setUTCMonth(n.getUTCMonth()-3);break;case"6M":n=Yt(t),n.setUTCMonth(n.getUTCMonth()-6);break;case"1Y":n=Yt(t),n.setUTCFullYear(n.getUTCFullYear()-1);break;case"2Y":n=Yt(t),n.setUTCFullYear(n.getUTCFullYear()-2);break;case"5Y":n=Yt(t),n.setUTCFullYear(n.getUTCFullYear()-5);break;default:return}return jS(n)}function Kt(e){return Array.isArray(e)&&e.length>0?e.map(String):void 0}function Ss(e){return Array.isArray(e)?e.filter(m):[]}function Af(e){if(!(!m(e)||typeof e.summary!="string"||!Array.isArray(e.columns)))return{summary:e.summary,columns:e.columns.map(String)}}function Sf(e,t=Ss(e.rows)){let n=Af(e.rowModel);return n?{...n,rows:t}:void 0}function Cf(e,t){if(!e||!t||!e.summary.startsWith("time series")||e.columns[0]!=="date"||t.length!==e.columns.length-1||!e.columns.slice(1).every(r=>/^series_\d+$/.test(r)))return e;let n=e.columns.slice(1);return{...e,columns:["date",...t],rows:e.rows.map(r=>({date:r.date,...Object.fromEntries(t.map((i,o)=>[i,r[n[o]]]))}))}}function Ef(e){return typeof e.name=="string"&&e.name.trim().length>0?!0:Array.isArray(e.text)&&e.text.some(t=>typeof t=="string"&&t.trim().length>0)}function GS(e,t){let n=m(e)?e:{},r=Af(n.rowModel);if(r&&r.summary.startsWith("time series")&&r.columns[0]==="date"){let l=r.columns.slice(1);if(l.length===t)return l}let i=Kt(n.labels),o=Ss(n.traces);if(!i||o.length===0)return;let s=m(n.layout)?n.layout:{},a=ut(o,s,{seriesLabels:i});if(!a||!a.summary.startsWith("time series")||a.columns[0]!=="date")return;let u=a.columns.slice(1);return u.length===t?u:void 0}function vf(e,t,n){let r=Object.entries(e.getAllRefs()).filter(([i,o])=>!i.includes(".")&&o.type==="widget"&&String(o.id??"")===t).reverse();for(let[i]of r){let o=GS(e.getPayload(i),n);if(o)return o}}function yf(e){return JSON.stringify(e)??String(e)}function wf(e,t){return yf(e)===yf(t)}function BS(e,t,n=[]){if(!t||e.columns[0]!=="date")return e;let r=e.rows.filter(c=>typeof c.date=="string"&&c.date.slice(0,10)>=t),i=e.columns.slice(1),o=e.summary.startsWith("time series")?Po(n,i):[],a=["date",...(e.summary.startsWith("time series")&&o.length===i.length?e.columns.slice(1).filter((c,d)=>(o[d]?.x??[]).some(p=>typeof p=="string"&&p.slice(0,10)>=t)):void 0)??e.columns.slice(1).filter(c=>r.some(d=>d[c]!==void 0&&d[c]!==null))],u=e.summary.replace(/time series, \d+ series, \d+ points/,`time series, ${Math.max(a.length-1,0)} series, ${r.length} points`);if(a.length===e.columns.length)return{...e,summary:u,rows:r};let l=r.map(c=>Object.fromEntries(a.map(d=>[d,c[d]])));return{...e,summary:u,columns:a,rows:l}}function xf(e,t){return e?Tn(e):t.every(n=>!n.x?.length)?" - data: none (try `open @link` for browser view)":void 0}function HS(e){return{field:String(e.field??""),default:e.default,rawDefault:e.rawDefault,options:Array.isArray(e.options)?e.options:[],type:String(e.type??"String"),totalOptions:typeof e.totalOptions=="number"?e.totalOptions:void 0,display:Array.isArray(e.display)?e.display:void 0,notParam:!!e.notParam,filterable:!!e.filterable,cgGroupIds:Array.isArray(e.cgGroupIds)?e.cgGroupIds.map(String):void 0,allOptions:Array.isArray(e.allOptions)?e.allOptions.map(String):void 0,allRawOptions:Array.isArray(e.allRawOptions)?e.allRawOptions.map(String):void 0,fillBlocked:us(e.fillBlocked)}}function If(e){if(!(!m(e)||e.ok!==!0||!m(e.value)))return e.value}function ks(e){if(!(!m(e)||e.ok!==!1))return m(e.error)&&typeof e.error.message=="string"?e.error.message:"Widget read failed"}function zS(e,t){return!t||e.includes("marquee browser open")?e:`${e}. Use \`marquee browser open @${t}\` to adjust this widget in Marquee UI or try another option.`}function JS(e){if(!(!m(e)||e.ok!==!1||!m(e.error)))return typeof e.error.httpStatus=="number"?e.error.httpStatus:void 0}function YS(e){let t=If(e);if(t&&m(t.audit))return t.audit;if(m(e)&&m(e.audit))return e.audit}function KS(e){return!hr(e.chartId)||e.params.some(t=>t.field===wn)?e:{...e,params:[...e.params,{field:wn,default:void 0,options:[],type:"Enum"}]}}function Df(e){return!m(e)||!Array.isArray(e.warnings)?[]:e.warnings.filter(t=>m(t)&&typeof t.message=="string").map(t=>String(t.message))}function QS(e){return m(e)&&m(e.rdate)&&typeof e.rdate.rule=="string"}function bf(e){if(typeof e=="string")return Tf(e)===void 0?void 0:e}function Tf(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),o=Date.UTC(n,r-1,i),s=new Date(o);if(!(s.getUTCFullYear()!==n||s.getUTCMonth()!==r-1||s.getUTCDate()!==i))return o}function ZS(e,t=new Date){let n=Tf(e);return n===void 0?!1:t.getTime()-n>720*60*60*1e3}function XS(e){let t=`${e.title} ${e.description??""}`;return/\b(upcoming|current|today|tomorrow|next\s+(week|month|quarter)|this\s+(week|month|quarter))\b/i.test(t)}function eC(e){return e.split(/\s+/).filter(Boolean).map((t,n)=>{let r=/^[A-Z0-9]+$/.test(t)?t.toLowerCase():t;return n===0?`${r[0]?.toLowerCase()??""}${r.slice(1)}`:`${r[0]?.toUpperCase()??""}${r.slice(1)}`}).join("")}function Pf(e,t){if(!XS(e))return[];let n=[];for(let r of e.params){if(r.type!=="Date"||QS(r.rawDefault))continue;let i=bf(r.rawDefault)??bf(r.default);if(!(!i||!ZS(i))){if(r.fillBlocked?.reason==="quickpoll-survey-date"){n.push(`Date parameter ${r.field} is ${i} on a current/upcoming QuickPoll widget; surveyDate depends on question, so adjust it in Marquee UI via \`marquee browser open @${t}.link\` or load a result for the desired survey date.`);continue}n.push(`Date parameter ${r.field} is ${i} on a current/upcoming widget; run \`marquee fill @${t}.${eC(r.field)} 0b\` to refresh it.`)}}return n}function _f(e){let t=If(e);if(t&&m(t.view))return t.view;if(t&&m(t.widget)&&m(t.data))return t}function As(e,t){let n=m(e.widget)?e.widget:{},r=m(e.data)?e.data:{},i=Array.isArray(e.dashboards)?e.dashboards.filter(o=>m(o)&&typeof o.id=="string"&&typeof o.title=="string").map(o=>({...o,id:String(o.id),title:String(o.title)})):void 0;return{title:String(n.title??t.title??""),id:String(n.id??t.id),configurationId:String(n.configurationId??t.configurationId??""),chartId:typeof n.chartId=="string"?n.chartId:void 0,params:Array.isArray(e.params)?e.params.filter(o=>m(o)).map(o=>HS(o)):[],labels:Kt(r.labels),description:typeof n.description=="string"&&n.description.length>0?n.description:void 0,tags:Kt(n.tags),sources:Kt(n.sources),...i?{dashboards:i}:{}}}function $f(e,t,n={}){let r=_f(e.data.result);if(!r)return;let i=m(r.widget)?r.widget:{},o=m(r.data)?r.data:{},s=String(i.configurationId??t.configurationId??""),a=Array.isArray(o.traces)?o.traces:[],u=m(o.layout)?o.layout:{},c=Kt(o.labels)??(n.registry&&a.length>0&&a.every(R=>!Ef(R))?vf(n.registry,t.id,a.length):void 0),d=As(r,{id:t.id,title:t.title,configurationId:s}),f=[...Df(e.data.result),...n.namespace?Pf(d,n.namespace):[]],p=Ss(o.rows),g=Cf(Sf(o,p),c),h=xf(g,a),y=d.title||t.title||"",w=s,b=m(e.data.raw)?{...e.data.raw,args:{id:t.id,...w?{context:w}:{}}}:{args:{id:t.id,...w?{context:w}:{}},raw:e.data.raw??null};return{widgetData:{...d,title:y,id:t.id,configurationId:s,labels:c,warnings:f,dataPreview:h},payload:{rows:g?.rows??p,...g?{rowModel:{summary:g.summary,columns:g.columns}}:{},traces:a,layout:u,labels:c,widget:b,params:{configurationId:s,chartId:typeof i.chartId=="string"?i.chartId:void 0,params:Array.isArray(r.params)?r.params:[],labels:c,sources:d.sources??[],warnings:f,gqlData:{title:y,description:d.description??"",tags:d.tags??[],expressionLabels:c??[],data:a,layout:u}}}}}function Rf(e){if(!m(e))return;if(typeof e.title=="string"&&e.title.trim().length>0)return e.title;if(m(e.metadata)&&typeof e.metadata.title=="string"&&e.metadata.title.trim().length>0)return e.metadata.title;if(m(e.widget)&&typeof e.widget.title=="string"&&e.widget.title.trim().length>0)return e.widget.title;let t=m(e.steps)&&m(e.steps.widget)&&m(e.steps.widget.data)&&m(e.steps.widget.data.widget)?e.steps.widget.data.widget:void 0;if(t){if(m(t.metadata)&&typeof t.metadata.title=="string"&&t.metadata.title.trim().length>0)return t.metadata.title;if(typeof t.title=="string"&&t.title.trim().length>0)return t.title}}async function Of(e,t,n){let{write:r,router:i,registry:o}=n,s=me(e);if(!/^MW\S+$/i.test(s)){let L=FS(e);process.exitCode=1,t.json?r(`${JSON.stringify({ok:!1,error:L})}
64
+ `):k(r,`Error: ${L}`);return}let a=t.paramOverrides??[];if(t.json){let L=t.contextId??t.configId,q={kind:"id",id:s};L&&(q.contextId=L);let U=await i.execute({surface:"marketview",action:"widget-read",input:{source:q,mode:"audit",data:"render",...t.editableDashboards?{editableDashboards:"fetch"}:{}}});kf(U);let H=YS(U.data.result),Ce=ks(U.data.result);if(Ce){process.exitCode=1;let pe=JS(U.data.result);r(`${JSON.stringify({ok:!1,...pe?{status:pe}:{},error:Ce,...H?{audit:H}:{}})}
65
+ `);return}if(U.status==="ok"&&H){r(`${JSON.stringify(H)}
66
+ `);return}r(`${JSON.stringify({ok:!1,error:U.errors[0]??"Widget audit unavailable",...H?{audit:H}:{}})}
67
+ `);return}let u=o.claimWidget();if(t.snippet&&a.length===0){let L=t.contextId??t.configId??"";if(L){let q=await i.execute({surface:"marketview",action:"widget-snippet",input:{widgetId:s,configurationId:L}}),U=m(q.data?.result)?q.data.result:void 0;if(q.status==="ok"&&U&&typeof U.title=="string"&&Array.isArray(U.paramNames)){let H=U,Ce=bs(),pe=Dt(H.title,H.paramNames,u,{store:Ce.store,widget:{id:s,title:H.title,configurationId:H.configurationId}});Rs(o,u,Ce,{type:"widget",id:s,title:H.title,configurationId:H.configurationId},null),r(`${pe}
68
+ `);return}}}let l,c=t.configId;if(a.length>0){let L={id:s,params:a};if(c&&(L.contextId=c),l=await i.execute({surface:"marketview",action:"widget-change",input:{...L,...t.editableDashboards?{editableDashboards:"fetch"}:{}}}),l.status!=="ok"){Ln(r,l,!1);return}let q=ks(l.data.result);if(q){let U=zS(q,t.mutationFallbackRef);Ln(r,{status:"error",surface:"marketview",action:"widget-change",data:{error:U},errors:[U]},!1);return}}else{let L=t.contextId??c,q={kind:"id",id:s};if(L&&(q.contextId=L),l=await i.execute({surface:"marketview",action:"widget-read",input:{source:q,mode:t.snippet?"summary":"view",data:t.snippet?"skip":"render",...t.editableDashboards&&!t.snippet?{editableDashboards:"fetch"}:{},...t.snippet?{summaryContext:{chartEnrichment:"skip",entityResolution:"fallback"}}:{}}}),l.status!=="ok"){Ln(r,l,!1);return}let U=ks(l.data.result);if(U){Ln(r,{status:"error",surface:"marketview",action:"widget-read",data:{error:U},errors:[U]},!1);return}}let d=_f(l.data.result);if(!d){Ln(r,{status:"error",surface:"marketview",action:a.length>0?"widget-change":"widget-read",data:{error:"Widget view unavailable"},errors:["Widget view unavailable"]},!1);return}if(t.snippet){let L=KS(As(d,{id:s,title:Rf(l.data.raw),configurationId:c})),q=bs(),U=Dt(L.title,L.params.filter(H=>!H.notParam).map(H=>H.field),u,{store:q.store,widget:{id:L.id,title:L.title,configurationId:L.configurationId}});Rs(o,u,q,{type:"widget",id:L.id,title:L.title,configurationId:L.configurationId},null),r(`${U}
69
+ `);return}let f=m(d.widget)?d.widget:{},p=m(d.data)?d.data:{};c=String(f.configurationId??c??"");let g=Rf(l.data.raw),h=Array.isArray(p.traces)?p.traces:[],y=a.find(L=>L.field==="Relative Date"),w=typeof f.chartId=="string"&&f.chartId.startsWith("CH"),b;if(y&&w&&h.length>0&&(b=VS(String(y.value)),b)){let L=b;for(let q of h){let U=q.x??[],H=q.y??[],Ce=U.map(pe=>typeof pe=="string"&&pe.slice(0,10)>=L);q.x=U.filter((pe,Pe)=>Ce[Pe]),q.y=H.filter((pe,Pe)=>Ce[Pe]),q.text&&q.text.length===U.length&&(q.text=q.text.filter((pe,Pe)=>Ce[Pe]))}}let R=m(p.layout)?p.layout:{},C=Kt(p.labels)??(h.length>0&&h.every(L=>!Ef(L))?vf(o,s,h.length):void 0),x=Df(l.data.result),E=As(d,{id:s,title:g,configurationId:c}),j=E.params;x=[...x,...Pf({...E,params:j},u)];let D=a[a.length-1];if(a.length>0)for(let L of a){if(L.field!==D?.field)continue;let q=j.find(U=>U.field===L.field);if(q){let U=q.options.find(H=>m(H)&&wf(H.rawValue,L.value));q.default=U&&m(U)?ie(U.label,{}):q.rawDefault!==void 0&&wf(q.rawDefault,L.value)&&q.default!==void 0?q.default:q.type==="Asset"?t.assetLabel??L.value:ie(L.value,{})}}let A=E.title||g||"";if(a.length>0)for(let L of a){if(L.field!==D?.field)continue;let q=j.find(U=>U.field===L.field);if(q&&q.type==="Asset"){let U=q.default!=null?String(q.default):String(L.value),H=U.startsWith("MA")&&t.assetLabel?t.assetLabel:U;H&&!A.includes(H)&&(A=`${A} (${H})`)}}let I=Cf(Sf(p),C),O=I?BS(I,b,h):void 0,M=O?.rows??[],N=xf(O,h),V=bs(),G=Xr({...E,title:A,id:s,configurationId:c,params:j,labels:C,warnings:x,dataPreview:N},{store:V.store,namespace:u,showConcreteDateDefaults:!0}),W=c,K=m(l.data.raw)?{...l.data.raw,args:{id:s,...W?{context:W}:{}}}:{args:{id:s,...W?{context:W}:{}},raw:l.data.raw??null},z={rows:M,...O?{rowModel:{summary:O.summary,columns:O.columns}}:{},traces:h,layout:R,labels:C,widget:K,params:{configurationId:c,chartId:typeof f.chartId=="string"?f.chartId:void 0,params:Array.isArray(d.params)?d.params:[],labels:C,sources:E.sources??[],warnings:x,gqlData:{title:A,description:E.description??"",tags:E.tags??[],expressionLabels:C??[],data:h,layout:R}}},Wi={type:"widget",id:s,title:A,configurationId:c,...typeof f.chartId=="string"?{chartId:f.chartId}:{}};Rs(o,u,V,Wi,z),r(`${G}
70
+ `)}var Cs=v(()=>{"use strict";At();os();Me();Vt();An();_n();$e();Z()});function tC(e){if(!Array.isArray(e))throw new Error("Dashboard widget is missing metadataParameters; record a Scenario before inferring title parameters from raw widget fields.")}function Mf(e){let t=e;return tC(t.metadataParameters),t.metadataParameters.filter(n=>typeof n.field=="string"&&n.field.length>0&&n.value!==void 0&&n.value!==null&&n.value!=="")}var Wf=v(()=>{"use strict"});function ri(e,t){let n=e.trim();return/\s/.test(n)?!1:new RegExp(`^${t}[A-Z0-9_]+$`,"i").test(n)}function Vf(e){return ri(e,"MD")?"thematic":ri(e,"MA")?"asset":/^[A-Z]{2}$/.test(e)?"country":ri(e,"MP")?"portfolio":"unknown"}function rC(e){return{status:"error",surface:"marketview",action:"dashboard",data:{},errors:[`could not resolve dashboard "${e}"`]}}function qn(e){return e==="asset"||e==="country"||e==="portfolio"}function iC(e){return/^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/.test(e)}function Gf(e){return/\s/.test(e.trim())}function Lf(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function oC(e){if(Array.isArray(e))return e.filter(m);if(!m(e))return[];let t=["results","items","dashboards"];for(let n of t){let r=e[n];if(Array.isArray(r))return r.filter(m)}return[]}function qf(e){return m(e)?Array.isArray(e.pins)?e.pins:m(e.value)&&Array.isArray(e.value.pins)?e.value.pins:[]:[]}function Qt(e){let t=me(e);return/^(?:mw|wc)[a-z0-9]+$/i.test(t.trim())?t.trim().toUpperCase():t}function sC(e){let t=e.trim().match(/^(MW[A-Z0-9]+)(?:[-:?|](WC[A-Z0-9]+))?$/i);return t?{widgetId:Qt(t[1]),...t[2]?{configurationId:Qt(t[2])}:{}}:null}function aC(e){if(typeof e=="string")return sC(e);if(!m(e))return null;let t=typeof e.widgetId=="string"?e.widgetId:typeof e.id=="string"?e.id:void 0;if(!t)return null;let n=typeof e.configurationId=="string"?e.configurationId:typeof e.configId=="string"?e.configId:void 0;return{widgetId:Qt(t),...n?{configurationId:Qt(n)}:{}}}function Ff(e){let t=[];for(let n of e){let r=aC(n);r&&t.push(r)}return t}function Nf(e){return e.filter(t=>t.configurationId).length}function uC(e){let t=Ff(qf(e.data.result)),n=Ff(qf(e.data.raw));return Nf(n)>Nf(t)?n:t.length>0?t:n}async function ii(e,t){if(!t)return{ok:!0,pins:[]};let n=await e.execute({surface:"marketview",action:"preferences",input:{}});return n.status!=="ok"?{ok:!1,response:n}:{ok:!0,pins:uC(n)}}function dC(e,t){return Qt(e.id)!==t.widgetId?!1:t.configurationId?typeof e.configurationId=="string"&&Qt(e.configurationId)===t.configurationId:!0}function Bf(e,t){if(t.length===0||e.length===0)return e;let n=[...e],r=[];for(let i of t){let o=n.findIndex(s=>dC(s,i));o>=0&&r.push(...n.splice(o,1))}return r.length>0?[...r,...n]:e}async function cC(e,t){if(!Gf(e))return{dashboardId:null,failedResponse:null};let n=await t.execute({surface:"marketview",action:"search",input:{query:e,types:["Dashboard"],limit:nC}});if(n.status!=="ok")return{dashboardId:null,failedResponse:n};let r=Lf(e);for(let i of oC(n.data.result)){let o=typeof i.id=="string"?i.id:void 0,s=typeof i.title=="string"?i.title:void 0,a=typeof i.type=="string"?i.type.toLowerCase():void 0;if(o&&s&&Lf(s)===r&&(a===void 0||a==="dashboard"||Vf(o)==="thematic"))return{dashboardId:me(o),failedResponse:null}}return{dashboardId:null,failedResponse:null}}function lC(e,t){return[typeof e.ticker=="string"&&e.ticker.length>0?e.ticker:t.toUpperCase(),e.assetClass,e.type,e.exchange,e.currency].filter(i=>typeof i=="string"&&i.length>0).join(" \xB7 ")}function fC(e){return["Portfolio",e.currency].filter(n=>typeof n=="string"&&n.length>0).join(" \xB7 ")}function pC(e){return e==="country"?"Country":e==="portfolio"?"Portfolio":"Asset"}function gC(e,t){return e==="country"?`https://marquee.gs.com/s/marketview/country/${t}`:e==="portfolio"?`https://marquee.gs.com/s/marketview/portfolio/${t}`:`https://marquee.gs.com/s/marketview/asset/${t}`}function mC(e){if(!e)return null;let t={ticker:e.ticker,name:e.name,assetClass:e.assetClass,type:e.type,exchange:e.exchange,currency:e.currency};return[t.ticker,t.name,t.assetClass,t.type,t.exchange,t.currency].every(r=>typeof r=="string"&&r.length>0)?t:null}function oi(e){return Array.isArray(e)?e.filter(t=>m(t)&&typeof t.id=="string"&&typeof t.title=="string").map(vs):[]}function vs(e){let t=Ye(e);return t.length>0?e.paramNames=t:delete e.paramNames,e}function Hf(e){let t=e.data.raw;return!m(t)||!Array.isArray(t.children)?[]:t.children.filter(m)}function si(e){let t=m(e.data)?e.data:e;return typeof t.id=="string"?t.id:void 0}function hC(e){for(let t of[e.id,e.uuid,e.childId])if(typeof t=="string"&&t.trim().length>0)return t}function yC(e){for(let t of[e.id,e.uuid,e.sectionId])if(typeof t=="string"&&t.trim().length>0)return t}function wC(e){let t=e.data.raw;return!m(t)||!Array.isArray(t.sections)?[]:t.sections.map((n,r)=>{if(!m(n)||typeof n.title!="string"||!Array.isArray(n.children))return null;let i=n.children.filter(s=>typeof s=="string"&&s.trim().length>0);if(i.length===0)return null;let o=yC(n);return{...o?{id:o}:{},title:n.title,rank:typeof n.rank=="number"&&Number.isFinite(n.rank)?n.rank:r,children:i}}).filter(n=>n!==null).sort((n,r)=>n.rank-r.rank)}function bC(e){let t=m(e.data)?e.data:e;return Array.isArray(t.parameters)?t.parameters.filter(n=>m(n)&&typeof n.field=="string"&&n.field.length>0):void 0}function RC(e,t){let n=Hf(t);if(n.length===0)return e;let r=new Set;return e.map((i,o)=>{let s=n.findIndex((u,l)=>!r.has(l)&&l>=o&&si(u)===i.id);if(s===-1&&(s=n.findIndex((u,l)=>!r.has(l)&&si(u)===i.id)),s===-1)return i;r.add(s);let a=bC(n[s]);return a&&a.length>0?vs({...i,parameters:a}):i})}function zf(e,t){let n=Hf(t);if(n.length===0||e.length===0)return[];let r=new Set,i=[];for(let[o,s]of e.entries()){let a=n.findIndex((l,c)=>!r.has(c)&&c>=o&&si(l)===s.id);if(a===-1&&(a=n.findIndex((l,c)=>!r.has(c)&&si(l)===s.id)),a===-1)continue;r.add(a);let u=hC(n[a]);u&&i.push({childId:u,widget:s})}return i}function kC(e,t){for(let{childId:n,widget:r}of zf(e,t))r.childId=n}function AC(e,t){let n=wC(t);if(n.length===0)return;let r=new Map(zf(e,t).map(l=>[l.childId,l.widget]));if(r.size===0)return;let i=[],o=[],s=new Set;for(let l of n){let c=i.length;for(let f of l.children){if(s.has(f))continue;let p=r.get(f);p&&(s.add(f),i.push(p))}let d=i.length-c;d>0&&o.push({title:l.title,widgetCount:d,startIndex:c,...l.id?{sectionId:l.id}:{}})}if(o.length===0)return;let a=new Set(i),u=e.filter(l=>!a.has(l));return{widgets:[...i,...u],sections:o}}function Uf(e){return Array.isArray(e)?e.filter(t=>m(t)&&typeof t.field=="string"&&t.field.length>0&&t.value!==void 0&&t.value!==null&&t.value!==""):[]}function SC(e,t){let n=Uf(e.configurationParameters);if(n.length>0)return n;let r=Uf(e.metadataParameters);return r.length>0?r:t?Mf(e):[]}function CC(e){let t=e.data.result;if(m(t)&&typeof t.id=="string"&&t.id.length>0)return t.id}function EC(e){let t=e.data.result;if(m(t))return m(t.metadata)&&typeof t.metadata.title=="string"&&t.metadata.title.trim()?t.metadata.title:typeof t.title=="string"&&t.title.trim()?t.title:void 0}async function vC(e,t,n){if(typeof e.configurationId=="string"&&e.configurationId.length>0||!e.underlyingChartId)return;let r=SC(e,n),i=await t.execute({surface:"marketview",action:"widget-configure",input:{id:e.id,underlyingChartId:e.underlyingChartId,parameters:r}});if(i.status!=="ok")return i;let o=CC(i);o&&(e.configurationId=o);let s=EC(i);s&&(e.title=s)}async function IC(e,t){let n=await t.execute({surface:"marketview",action:"widget-snippet",input:{widgetId:e.id,configurationId:e.configurationId}});if(n.status!=="ok")return n;let r=n.data?.result;if(!m(r))return;let i=typeof r.title=="string"?r.title:"",o=Array.isArray(r.paramNames)?r.paramNames:[];i&&!bn(i)&&(e.title=i),o.length>0&&(e.paramNames=o)}async function ai(e,t,n){let r=e.filter(i=>!i.full&&i.underlyingChartId).slice(0,xC);if(r.length!==0)try{await Promise.all(r.map(async i=>{if(!(typeof i.configurationId=="string"&&i.configurationId.length>0)){let s=await vC(i,t,n);if(s)throw s}if(!(typeof i.configurationId=="string"&&i.configurationId.length>0))return;let o=await IC(i,t);if(o)throw o}))}catch(i){let o=Mn(i);if(o)return o;throw i}}function Jf(e,t=0){for(let n of e.slice(t))delete n.supportedContexts}function DC(e,t){let n=/<\s*[^:<>]+\s*:\s*[^<>]+?\s*>/g,r=/\[\s*asset\s*\]/gi;for(let i of e)i.title=i.title.replace(n,t).replace(r,t),vs(i)}async function TC(e,t){if(ri(e,"MA"))return{id:me(e)};let n=await t.execute({surface:"asset",action:"resolve",input:{query:e}});if(n.status!=="ok")return null;let r=n.data.result??n.data.asset;return!m(r)||typeof r.id!="string"?null:{id:r.id,name:typeof r.name=="string"?r.name:void 0,assetClass:typeof r.assetClass=="string"?r.assetClass:void 0,type:typeof r.type=="string"?r.type:void 0,ticker:typeof r.ticker=="string"?r.ticker:void 0,bbid:typeof r.bbid=="string"?r.bbid:void 0,exchange:typeof r.exchange=="string"?r.exchange:void 0,currency:typeof r.currency=="string"?r.currency:void 0}}async function Yf(e,t){let{identifier:n,kind:r,contextId:i,identity:o,resolved:s,router:a}=t,u=e;if(r==="asset"){let d=typeof o.ticker=="string"&&o.ticker.length>0?o.ticker:n.toUpperCase(),f=typeof o.name=="string"&&o.name.length>0?o.name:s?.name??n;DC(u,f||d);let p=await ai(u,a,i);return p?{ok:!1,response:p}:{ok:!0,prepared:{widgets:u,title:f,identityLine:lC(o,d)}}}let l=typeof o.name=="string"&&o.name.length>0?o.name:n,c=await ai(u,a,i);return c?{ok:!1,response:c}:{ok:!0,prepared:{widgets:u,title:l,identityLine:r==="portfolio"?fC(o):""}}}function Kf(e,t){let n=new Set((Array.isArray(e.loadedPages)?e.loadedPages:[]).filter(r=>Number.isInteger(r)&&r>0));n.add(t),e.loadedPages=[...n].sort((r,i)=>r-i)}async function PC(e,t,n){if(!e.contextId||!qn(e.contextType))return;let r=(t.page-1)*t.pageSize,i=m(e.contextIdentity)?e.contextIdentity:{},o=Math.max(0,Math.min(t.pageSize,t.total-r)),s=oi(e.widgets.slice(r,r+t.pageSize));if(s.length<o){let l=await n.execute({surface:"marketview",action:"asset",input:{assetId:e.contextId,limit:t.pageSize,offset:r,includeFilters:!1}});if(l.status!=="ok")return l;let c=m(l.data.result)?l.data.result:{};s=oi(c.widgets)}Jf(s,jf);let a=await Yf(s,{identifier:e.title,kind:e.contextType,contextId:e.contextId,identity:i,resolved:null,router:n});if(!a.ok)return a.response;let{prepared:u}=a;u.widgets.forEach((l,c)=>{e.widgets[r+c]=l}),e.pageSize=t.pageSize,Kf(e,t.page)}async function Qf(e,t,n){if(e.contextId&&qn(e.contextType))return PC(e,t,n);let r=(t.page-1)*t.pageSize,i=e.widgets.slice(r,r+t.pageSize),o=await ai(i,n);if(o)return o;e.pageSize=t.pageSize,Kf(e,t.page)}async function ni(e,t,n,r,i){let o=t==="asset"?n?.id??me(e):me(e),s=t==="asset"?mC(n):null,[a,u,l]=await Promise.all([r.execute({surface:"marketview",action:"asset",input:{assetId:o,includeFilters:!1}}),s?Promise.resolve({status:"ok",surface:"marketview",action:"asset-identity",data:{result:s},errors:[]}):r.execute({surface:"marketview",action:"asset-identity",input:{id:o,type:pC(t)}}),ii(r,i)]);if(a.status!=="ok")return{ok:!1,response:a};if(!l.ok)return{ok:!1,response:l.response};let c=u.status==="ok"&&m(u.data.result)?u.data.result:{},d=m(a.data.result)?a.data.result:{},f=oi(d.widgets),p=typeof d.total=="number"?d.total:f.length,g=Bf(f,l.pins);Jf(g,jf);let h=await Yf(g.slice(0,pt),{identifier:e,kind:t,contextId:o,identity:c,resolved:n,router:r});if(!h.ok)return{ok:!1,response:h.response};let{prepared:y}=h;return{ok:!0,payload:{title:y.title,identity:y.identityLine,contextId:o,contextType:t,contextIdentity:c,author:null,description:null,tags:[],link:gC(t,o),total:p,pageSize:pt,loadedPages:[1],widgets:[...y.widgets,...g.slice(pt)]},root:{type:"dashboard",id:o,contextId:o,contextType:t,cursor:{page:1,pageSize:pt,total:p}}}}function _C(e,t){let n=0;for(let[r,i]of e.entries()){if(r===0){n=Math.min(i.widgetCount,t);continue}if(n+i.widgetCount>t)break;n+=i.widgetCount}return n}async function Es(e,t,n,r){let i=m(t.data.result)?t.data.result:{},o=RC(oi(i.widgets),t);kC(o,t);let s=AC(o,t),a=s?s.widgets:Bf(o,r),u=typeof i.total=="number"?i.total:typeof i.widgetCount=="number"?i.widgetCount:a.length,l=s?_C(s.sections,pt):pt,c=await ai(a.slice(0,l),n);return c?{ok:!1,response:c}:{ok:!0,payload:{title:typeof i.title=="string"?i.title:"",author:typeof i.author=="string"?i.author:null,description:typeof i.description=="string"?i.description:null,tags:Array.isArray(i.tags)?i.tags.map(String):[],link:typeof i.link=="string"?i.link:`https://marquee.gs.com/s/marketview/dashboards/${e}`,total:u,widgets:a,...s?{sections:s.sections}:{}},root:{type:"dashboard",id:e,cursor:{page:1,pageSize:pt,total:u}}}}function Zf(e){let{router:t,useDashboardPreferences:n=!1}=e;return{async read(r){let i=me(r.identifier),o=Vf(i);if(o==="asset")return ni(i,"asset",{id:i},t,n);if(o==="country")return ni(i,"country",null,t,n);if(o==="portfolio")return ni(i,"portfolio",null,t,n);if(o==="unknown"&&iC(i)){let[l,c]=await Promise.all([t.execute({surface:"marketview",action:"dashboard",input:{id:i}}),ii(t,n)]);if(l.status==="ok")return c.ok?Es(i,l,t,c.pins):{ok:!1,response:c.response}}if(o==="unknown"){let l=Gf(i),c=await cC(i,t),d=c.dashboardId;if(d){let[p,g]=await Promise.all([t.execute({surface:"marketview",action:"dashboard",input:{id:d}}),ii(t,n)]);return p.status==="ok"?g.ok?Es(d,p,t,g.pins):{ok:!1,response:g.response}:{ok:!1,response:p}}let f=await TC(i,t);if(f)return ni(i,"asset",f,t,n);if(c.failedResponse)return{ok:!1,response:c.failedResponse};if(l)return{ok:!1,response:rC(i)}}let s=i,[a,u]=await Promise.all([t.execute({surface:"marketview",action:"dashboard",input:{id:s}}),ii(t,n)]);return a.status!=="ok"?{ok:!1,response:a}:u.ok?Es(s,a,t,u.pins):{ok:!1,response:u.response}}}}var pt,nC,jf,xC,ui=v(()=>{"use strict";$e();Z();$e();Wf();pt=10,nC=50,jf=5;xC=20});function $C(e){e.status!=="ok"&&(process.exitCode=1)}function OC(e,t,n=!1){if($C(t),n){let{raw:r,...i}=t.data??{};e(`${JSON.stringify({...t,data:i})}
71
+ `)}else e(`${oe(t)}
72
+ `)}function MC(e,t){if(!e.contextId)return e;let n=(t.page-1)*t.pageSize;return{...e,pageSize:t.pageSize,widgets:e.widgets.slice(n,n+t.pageSize)}}async function Xf(e,t,n){let{write:r,router:i,registry:o}=n,a=await Zf({router:i,useDashboardPreferences:!0}).read({identifier:e});if(!a.ok){OC(r,a.response,t);return}let u=o.claimDashboard();if(o.storeArtifact({namespace:u,root:a.root,refs:{[`${u}.link`]:{type:"link",url:a.payload.link}},payload:a.payload}),t){r(`${JSON.stringify({status:"ok",surface:"marketview",action:"dashboard",data:{result:{...MC(a.payload,a.root.cursor),widgetCount:a.payload.total}},errors:[]})}
73
+ `);return}r(`${ft(a.payload,{ns:u,dashboardId:a.root.id,cursor:a.root.cursor,store:le(o,u)})}
74
+ `)}var ep=v(()=>{"use strict";Me();Vt();Z();ui()});function np(e){e.status!=="ok"&&(process.exitCode=1)}function Zt(e,t,n){np(t),e(`${oe(t,n)}
75
+ `)}function WC(e){let t=[],n=[];for(let r of e){let i=Fn[r];i?t.push(...i):n.push(r)}return{types:t.length>0?[...new Set(t)]:["Widget"],invalidTypes:n}}function LC(e){let t=e.length===1?"type":"types",n=e.map(r=>`"${r}"`).join(", ");return`Unknown marketview search ${t} ${n}. Supported types: ${Object.keys(Fn).join(", ")}`}function NC(e){let t=e.trim();if(!(!t||!FC.some(n=>n.test(t))))return`For articles, try: marquee content search ${JSON.stringify(t)}`}function UC(e,t){let n=e,r=typeof n.hint=="string"&&n.hint.length>0?n.hint:void 0;n.hint=r?`${r}; ${t}`:t}function jC(e){if(!m(e)||!m(e.resultsMap))return;let t=e.resultsMap;for(let[n,r]of Object.entries(t))Array.isArray(r)?e[n]=r.map(i=>{if(!m(i)||!m(i.data))return i;let{data:o,...s}=i;return{...o,...s}}):n in e||(e[n]=r)}function GC(e){let t=e.match(/\b[A-Za-z][A-Za-z0-9./]{1,9}\b/g)??[],n=new Set,r=[];for(let i of t){let o=i.replace(/[./]+$/,"");if(o!==o.toUpperCase())continue;let s=o.replace(/\./g,"/").toUpperCase();s.length<3||s.length>8||VC.has(s)||!/[A-Z]/.test(s)||n.has(s)||(n.add(s),r.push(s))}return r.reverse().slice(0,5)}function gt(e,t){let n=e[t];return typeof n=="string"&&n.length>0?n:void 0}function BC(e){if(e.status!=="ok")return;let t=m(e.data.result)?e.data.result:m(e.data.asset)?e.data.asset:void 0;if(!t)return;let n=gt(t,"id");if(n)return{id:n}}function HC(e){return e.status!=="error"||e.surface!=="asset"||e.action!=="resolve"?!1:(typeof e.data.error=="string"?e.data.error:void 0)==="No asset found"||e.errors.includes("No asset found")}function zC(e){let t=new Map;if(e.status!=="ok"||!m(e.data.result))return t;let n=e.data.result.widgets;if(!Array.isArray(n))return t;for(let r of n){if(!m(r))continue;let i=gt(r,"id");i&&t.set(i,{id:i,title:gt(r,"title"),configurationId:gt(r,"configurationId")})}return t}function JC(e){if(e.status!=="ok"||!Array.isArray(e.data.result))return;let t=e.data.result.filter(n=>m(n)&&n.type==="widget"&&typeof n.id=="string");return t.length>0?t:void 0}function YC(e,t){if(e.status!=="ok"||!Array.isArray(e.data.result)||t.length===0)return;let n=new Set(t.map(r=>String(r.id)));e.data.result=[...e.data.result.filter(r=>m(r)&&r.type==="widget"&&typeof r.id=="string"&&n.has(r.id)),...e.data.result.filter(r=>!(m(r)&&r.type==="widget"&&typeof r.id=="string"&&n.has(r.id)))]}async function KC(e,t,n,r,i=5){let o=e.map((a,u)=>({item:a,index:u})).filter(a=>m(a.item)&&a.item.type==="widget"&&typeof a.item.id=="string").slice(0,i);if(o.length===0)return;let s;try{s=await Promise.all(o.map(async({item:a})=>{let u=gt(a,"configurationId"),l=await t.execute({surface:"marketview",action:"widget-read",input:{source:{kind:"id",id:String(a.id),...u?{contextId:u}:{}},mode:"view",data:"render"}});if(l.status!=="ok")throw l;return l}))}catch(a){let u=Mn(a);if(u)return u;throw a}s.forEach((a,u)=>{let{item:l,index:c}=o[u],d=`${r}.w${c+1}`,f=$f(a,{id:String(l.id),title:gt(l,"title"),configurationId:gt(l,"configurationId")},{registry:n,namespace:d});f&&(l.full=f.widgetData,l.title=f.widgetData.title,l.configurationId=f.widgetData.configurationId,n.setPayload(d,f.payload))})}async function QC(e,t,n,r){for(let i of e){let o=n.get(String(i.id));o&&(o.title&&(i.title=o.title),o.configurationId&&(i.configurationId=o.configurationId))}}async function ZC(e,t,n){let r=JC(t);if(r)for(let i of GC(e)){let o=await n.execute({surface:"asset",action:"resolve",input:{query:i}});if(o.status!=="ok"){if(HC(o))continue;return o}let s=BC(o);if(!s)continue;let a=await n.execute({surface:"marketview",action:"asset",input:{assetId:s.id,limit:250}});if(a.status!=="ok")return a;let u=zC(a);if(u.size===0)continue;let l=r.filter(c=>u.has(String(c.id)));if(l.length!==0){await QC(l,s.id,u,n),YC(t,l);return}}}async function rp(e,t){let{write:n,router:r,registry:i}=t,o=e.query.trim();if(!o){process.exitCode=1,P(n,"Error: marketview search query must not be empty");return}let s=e.type.split(",").map(A=>A.trim()).filter(Boolean),{types:a,invalidTypes:u}=WC(s),l=s.includes("widget-hybrid");if(u.length>0){process.exitCode=1,P(n,`Error: ${LC(u)}`);return}let c=je(e.limit);if(c===void 0){process.exitCode=1,P(n,"Error: --limit must be a positive integer");return}if(e.json){let A=await r.execute({surface:"marketview",action:"search",input:{query:o,types:a,limit:c,useNewSchema:l}});np(A);let I=A.data?.raw;jC(I),n(`${JSON.stringify(I!==void 0?I:A)}
76
+ `);return}let d=5,f=new AbortController,p=A=>r.execute({surface:"marketview",action:"search",input:A,signal:f.signal}),g=[],h=["widget","widget-semantic","widget-hybrid"],y=s.filter(A=>h.includes(A)),w=y.length>1;if(w){let A={widget:"keyword","widget-semantic":"semantic","widget-hybrid":"llm-reranked"};for(let I of y){let O=Fn[I],M=I==="widget-hybrid";g.push({mode:A[I],call:p({query:o,types:[...O],limit:c,useNewSchema:M})})}}else{let A=new Set(a);if(l){for(let N of Fn["widget-hybrid"])A.delete(N);g.push({mode:void 0,call:p({query:o,types:[...Fn["widget-hybrid"]],limit:c,useNewSchema:!0})})}let I=[...A].filter(N=>N.startsWith("Widget")),O=I.filter(N=>N==="Widget"),M=I.filter(N=>N!=="Widget");O.length>0&&g.push({mode:void 0,call:p({query:o,types:O,limit:c,useNewSchema:!1})}),M.length>0&&g.push({mode:void 0,call:p({query:o,types:M,limit:c,useNewSchema:!1})})}let b=a.filter(A=>!A.startsWith("Widget")),R=Math.min(c,d),S=b.filter(A=>tp.has(A)),C=b.filter(A=>!tp.has(A));for(let A of S)g.push({mode:void 0,call:p({query:o,types:[A],limit:c,useNewSchema:!1})});C.length>0&&g.push({mode:void 0,call:p({query:o,types:C,limit:c,useNewSchema:!1})});let x;try{x=await Promise.all(g.map(async A=>{let I=await A.call;if(I.status!=="ok")throw f.abort(),I;return I}))}catch(A){f.abort();let I=Mn(A);if(I){Zt(n,I);return}throw A}let E=g.map(A=>A.mode),j=x.find(A=>A.status!=="ok");if(j){Zt(n,j);return}let D=x[0];if(x.length>1&&D.status==="ok"&&x.every(A=>A.status==="ok")&&(D.data.result=x.flatMap((A,I)=>{let O=Array.isArray(A.data.result)?A.data.result:[],M=E[I];if(M)for(let N of O)N.searchMode=M;return O}),!w)){let A=new Set;D.data.result=D.data.result.filter(I=>{let O=typeof I.id=="string"?I.id:"";return!O||A.has(O)?!1:(A.add(O),!0)})}if(D.status==="ok"&&Array.isArray(D.data.result)){let A={},I=0;D.data.result=D.data.result.filter(O=>{let M=String(O.type);return qC.has(M)?e.expand?(I+=1,I<=R):(A[M]=(A[M]??0)+1,A[M]<=R):!0})}if(D.status==="ok"&&Array.isArray(D.data.result)){let A=await ZC(o,D,r);if(A){Zt(n,A);return}let I=i.claimSearch(),O=`https://marquee.gs.com/s/marketview/search?query=${encodeURIComponent(e.query.trim())}`;if(e.expand){let V=await KC(D.data.result,r,i,I);if(V){Zt(n,V);return}}i.storeArtifact({namespace:I,root:{type:"search",query:e.query},payload:D.data.result});let M=le(i,I);M.mergeRefs({[`${I}.link`]:{type:"link",url:O}});let N=NC(e.query);N&&UC(D.data.result,N),P(n,`- link ${O} [@${I}.link, open]`),P(n,""),Zt(n,D,{store:M,searchNamespace:I});return}Zt(n,D)}var Fn,qC,tp,FC,VC,ip=v(()=>{"use strict";Me();Z();Cs();Fn={widget:["Widget"],"widget-semantic":["Widget LLM"],"widget-hybrid":["Widget","Widget LLM","Widget Ranked"],"thematic-dashboard":["Dashboard"],"asset-dashboard":["Asset"],"country-dashboard":["Country"],"portfolio-dashboard":["Portfolio"]};qC=new Set(["thematic-dashboard","asset-dashboard","country-dashboard","portfolio-dashboard"]),tp=new Set(["Dashboard","Asset","Country","Portfolio"]),FC=[/\b(?:article|articles|content|author|authors|publication|publications|published|commentary)\b/i,/\b(?:research|macro|economic|economics)\s+(?:note|notes|report|reports)\b/i,/\b(?:latest|recent|newest|current)(?:\s+\S+){0,5}\s+(?:view|views|take|takes|note|notes|article|articles|research|insight|insights|report|reports|commentary)\b/i,/\b(?:view|views|take|takes|note|notes|article|articles|report|reports)\s+(?:from|by)\b/i,/\b(?:gs|gir)\s+(?:view|views|take|takes|note|notes|research|insight|insights|report|reports)\b/i,/\b(?:view|views|take|takes|note|notes|research|insight|insights|report|reports)\b.{0,40}\b(?:gs|gir)\b/i];VC=new Set(["APAC","ASEAN","ATM","CPI","DC","EM","EMEA","EOY","EPS","FX","GDP","GIR","LATAM","US","USD","YTD","G10"])});function XC(e){e.status!=="ok"&&(process.exitCode=1)}function xs(e,t,n=!1,r){if(XC(t),n){let{raw:i,...o}=t.data??{};e(`${JSON.stringify({...t,data:o})}
77
+ `)}else e(`${oe(t,r)}
78
+ `)}function sp(e,t){let n=e.command("marketview");n.command("search").argument("<query>","search query").option("--type <types>","result types (widget,widget-semantic,widget-hybrid,thematic-dashboard,asset-dashboard,country-dashboard,portfolio-dashboard)",op.join(",")).option("--limit <limit>","max results","10").option("--json").action(async(r,i,o)=>{await rp({query:r,type:i.type,limit:i.limit,json:i.json,hasExplicitLimit:o.getOptionValueSource("limit")==="cli"},{write:t.write,router:t.getRouter(),registry:t.getRegistry()})}),n.command("discover").option("--limit <limit>","max displayed entries").option("--json").action(async r=>{let i=je(r.limit);if(r.limit!==void 0&&i===void 0){let s={status:"error",surface:"marketview",action:"discover",data:{},errors:["--limit must be a positive integer"]};xs(t.write,s,r.json);return}let o=await t.getRouter().execute({surface:"marketview",action:"discover",input:{}});if(!r.json&&o.status==="ok"&&Array.isArray(o.data.result)){let s=t.getRegistry(),a=s.claimSearch();s.storeArtifact({namespace:a,root:{type:"search",query:"discover"},payload:o.data.result}),xs(t.write,o,!1,{store:le(s,a),searchNamespace:a,entryLimit:i});return}xs(t.write,o,r.json)}),n.command("widget").argument("<id>","widget ID (MW...)").option("--config <id>","widget configuration ID (WC...)").option("--json").option("--snippet",void 0,!1).action(async(r,i)=>{await t.renderWidgetTab(r,{configId:i.config,json:!!i.json,snippet:!!i.snippet,editableDashboards:!0})}),n.command("dashboard").argument("<identifier>","dashboard identifier (MD, MA, MP, ticker, or alias)").option("--json").action(async(r,i)=>{await t.renderDashboardTab(me(r),!!i.json)})}var op,Is=v(()=>{"use strict";Me();Z();ip();op=["widget","thematic-dashboard","asset-dashboard","country-dashboard","portfolio-dashboard"]});function ap(e){e.status!=="ok"&&(process.exitCode=1)}function Xt(e,t,n=!1,r){if(ap(t),n){let{raw:i,...o}=t.data??{};e(`${JSON.stringify({...t,data:o})}
79
+ `)}else e(`${oe(t,r)}
80
+ `)}function up(e,t){let n=e.command("asset");n.command("resolve").argument("[query...]").option("--query <query>").option("--json").action(async(r,i)=>{let o=i.query??(r??[]).join(" ").trim();if(!o){let a={status:"error",surface:"asset",action:"resolve",data:{},errors:["query is required"]};Xt(t.write,a,i.json);return}let s=await t.getRouter().execute({surface:"asset",action:"resolve",input:{query:o}});Xt(t.write,s,i.json)}),n.command("search").argument("[query...]").allowUnknownOption(!0).option("--limit <limit>","max results","10").option("--json").action(async(r,i)=>{let o=(r??[]).join(" ").trim();if(!o){let u={status:"error",surface:"asset",action:"search",data:{},errors:["query is required"]};Xt(t.write,u,i.json);return}let s=je(i.limit);if(s===void 0){let u={status:"error",surface:"asset",action:"search",data:{},errors:["--limit must be a positive integer"]};Xt(t.write,u,i.json);return}let a=await t.getRouter().execute({surface:"asset",action:"search",input:{query:o,limit:s}});if(i.json){ap(a),t.write(`${JSON.stringify(a.data.raw??a)}
81
+ `);return}if(a.status==="ok"&&Array.isArray(a.data.result)){let u=t.getRegistry(),l=u.claimSearch();u.storeArtifact({namespace:l,root:{type:"search",query:o},payload:a.data.result}),Xt(t.write,a,!1,{store:le(u,l),searchNamespace:l});return}Xt(t.write,a,!1)})}var dp=v(()=>{"use strict";Z();Me()});var Nn=re(Ts=>{var di=class extends Error{constructor(t,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=t,this.nestedError=void 0}},Ds=class extends di{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Ts.CommanderError=di;Ts.InvalidArgumentError=Ds});var ci=re(_s=>{var{InvalidArgumentError:eE}=Nn(),Ps=class{constructor(t,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:(n.push(t),n)}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new eE(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function tE(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}_s.Argument=Ps;_s.humanReadableArgName=tE});var Ms=re(Os=>{var{humanReadableArgName:nE}=ci(),$s=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let n=t.commands.filter(i=>!i._hidden),r=t._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((i,o)=>i.name().localeCompare(o.name())),n}compareOptions(t,n){let r=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return r(t).localeCompare(r(n))}visibleOptions(t){let n=t.options.filter(i=>!i.hidden),r=t._getHelpOption();if(r&&!r.hidden){let i=r.short&&t._findOption(r.short),o=r.long&&t._findOption(r.long);!i&&!o?n.push(r):r.long&&!o?n.push(t.createOption(r.long,r.description)):r.short&&!i&&n.push(t.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let n=[];for(let r=t.parent;r;r=r.parent){let i=r.options.filter(o=>!o.hidden);n.push(...i)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(n=>{n.description=n.description||t._argsDescription[n.name()]||""}),t.registeredArguments.find(n=>n.description)?t.registeredArguments:[]}subcommandTerm(t){let n=t.registeredArguments.map(r=>nE(r)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,n){return n.visibleCommands(t).reduce((r,i)=>Math.max(r,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(i)))),0)}longestOptionTermLength(t,n){return n.visibleOptions(t).reduce((r,i)=>Math.max(r,this.displayWidth(n.styleOptionTerm(n.optionTerm(i)))),0)}longestGlobalOptionTermLength(t,n){return n.visibleGlobalOptions(t).reduce((r,i)=>Math.max(r,this.displayWidth(n.styleOptionTerm(n.optionTerm(i)))),0)}longestArgumentTermLength(t,n){return n.visibleArguments(t).reduce((r,i)=>Math.max(r,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(i)))),0)}commandUsage(t){let n=t._name;t._aliases[0]&&(n=n+"|"+t._aliases[0]);let r="";for(let i=t.parent;i;i=i.parent)r=i.name()+" "+r;return r+n+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let n=[];if(t.argChoices&&n.push(`choices: ${t.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&n.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&n.push(`env: ${t.envVar}`),n.length>0){let r=`(${n.join(", ")})`;return t.description?`${t.description} ${r}`:r}return t.description}argumentDescription(t){let n=[];if(t.argChoices&&n.push(`choices: ${t.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),t.defaultValue!==void 0&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return t.description?`${t.description} ${r}`:r}return t.description}formatItemList(t,n,r){return n.length===0?[]:[r.styleTitle(t),...n,""]}groupItems(t,n,r){let i=new Map;return t.forEach(o=>{let s=r(o);i.has(s)||i.set(s,[])}),n.forEach(o=>{let s=r(o);i.has(s)||i.set(s,[]),i.get(s).push(o)}),i}formatHelp(t,n){let r=n.padWidth(t,n),i=n.helpWidth??80;function o(d,f){return n.formatItem(d,r,f,n)}let s=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(t))}`,""],a=n.commandDescription(t);a.length>0&&(s=s.concat([n.boxWrap(n.styleCommandDescription(a),i),""]));let u=n.visibleArguments(t).map(d=>o(n.styleArgumentTerm(n.argumentTerm(d)),n.styleArgumentDescription(n.argumentDescription(d))));if(s=s.concat(this.formatItemList("Arguments:",u,n)),this.groupItems(t.options,n.visibleOptions(t),d=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let p=d.map(g=>o(n.styleOptionTerm(n.optionTerm(g)),n.styleOptionDescription(n.optionDescription(g))));s=s.concat(this.formatItemList(f,p,n))}),n.showGlobalOptions){let d=n.visibleGlobalOptions(t).map(f=>o(n.styleOptionTerm(n.optionTerm(f)),n.styleOptionDescription(n.optionDescription(f))));s=s.concat(this.formatItemList("Global Options:",d,n))}return this.groupItems(t.commands,n.visibleCommands(t),d=>d.helpGroup()||"Commands:").forEach((d,f)=>{let p=d.map(g=>o(n.styleSubcommandTerm(n.subcommandTerm(g)),n.styleSubcommandDescription(n.subcommandDescription(g))));s=s.concat(this.formatItemList(f,p,n))}),s.join(`
82
+ `)}displayWidth(t){return cp(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,n){return Math.max(n.longestOptionTermLength(t,n),n.longestGlobalOptionTermLength(t,n),n.longestSubcommandTermLength(t,n),n.longestArgumentTermLength(t,n))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,n,r,i){let s=" ".repeat(2);if(!r)return s+t;let a=t.padEnd(n+t.length-i.displayWidth(t)),u=2,c=(this.helpWidth??80)-n-u-2,d;return c<this.minWidthToWrap||i.preformatted(r)?d=r:d=i.boxWrap(r,c).replace(/\n/g,`
83
+ `+" ".repeat(n+u)),s+a+" ".repeat(u)+d.replace(/\n/g,`
84
+ ${s}`)}boxWrap(t,n){if(n<this.minWidthToWrap)return t;let r=t.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,o=[];return r.forEach(s=>{let a=s.match(i);if(a===null){o.push("");return}let u=[a.shift()],l=this.displayWidth(u[0]);a.forEach(c=>{let d=this.displayWidth(c);if(l+d<=n){u.push(c),l+=d;return}o.push(u.join(""));let f=c.trimStart();u=[f],l=this.displayWidth(f)}),o.push(u.join(""))}),o.join(`
85
+ `)}};function cp(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}Os.Help=$s;Os.stripColor=cp});var Fs=re(qs=>{var{InvalidArgumentError:rE}=Nn(),Ws=class{constructor(t,n){this.flags=t,this.description=n||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let r=iE(t);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let n=t;return typeof t=="string"&&(n={[t]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_collectValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:(n.push(t),n)}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new rE(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?lp(this.name().replace(/^no-/,"")):lp(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ls=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(t,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let i=this.negativeOptions.get(r).presetArg,o=i!==void 0?i:!1;return n.negate===(o===t)}};function lp(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function iE(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,o=e.split(/[ |,]+/).concat("guard");if(r.test(o[0])&&(t=o.shift()),i.test(o[0])&&(n=o.shift()),!t&&r.test(o[0])&&(t=o.shift()),!t&&i.test(o[0])&&(t=n,n=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${e}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
86
+ - a short flag is a single dash and a single character
87
+ - either use a single dash and a single character (for a short flag)
88
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(s)?new Error(`${a}
89
+ - too many short flags`):i.test(s)?new Error(`${a}
90
+ - too many long flags`):new Error(`${a}
91
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}qs.Option=Ws;qs.DualOptions=Ls});var pp=re(fp=>{function oE(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let o=1;e[i-1]===t[r-1]?o=0:o=1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+o),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function sE(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");n&&(e=e.slice(2),t=t.map(s=>s.slice(2)));let r=[],i=3,o=.4;return t.forEach(s=>{if(s.length<=1)return;let a=oE(e,s),u=Math.max(e.length,s.length);(u-a)/u>o&&(a<i?(i=a,r=[s]):a===i&&r.push(s))}),r.sort((s,a)=>s.localeCompare(a)),n&&(r=r.map(s=>`--${s}`)),r.length>1?`
92
+ (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
93
+ (Did you mean ${r[0]}?)`:""}fp.suggestSimilar=sE});var yp=re(Gs=>{var aE=he("node:events").EventEmitter,Ns=he("node:child_process"),Ve=he("node:path"),li=he("node:fs"),B=he("node:process"),{Argument:uE,humanReadableArgName:dE}=ci(),{CommanderError:Us}=Nn(),{Help:cE,stripColor:lE}=Ms(),{Option:gp,DualOptions:fE}=Fs(),{suggestSimilar:mp}=pp(),js=class e extends aE{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>B.stdout.write(n),writeErr:n=>B.stderr.write(n),outputError:(n,r)=>r(n),getOutHelpWidth:()=>B.stdout.isTTY?B.stdout.columns:void 0,getErrHelpWidth:()=>B.stderr.isTTY?B.stderr.columns:void 0,getOutHasColors:()=>Vs()??(B.stdout.isTTY&&B.stdout.hasColors?.()),getErrHasColors:()=>Vs()??(B.stderr.isTTY&&B.stderr.hasColors?.()),stripColor:n=>lE(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let n=this;n;n=n.parent)t.push(n);return t}command(t,n,r){let i=n,o=r;typeof i=="object"&&i!==null&&(o=i,i=null),o=o||{};let[,s,a]=t.match(/([^ ]+) *(.*)/),u=this.createCommand(s);return i&&(u.description(i),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),i?this:u}createCommand(t){return new e(t)}createHelp(){return Object.assign(new cE,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,n){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
94
+ - specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=t._name),(n.noHelp||n.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,n){return new uE(t,n)}argument(t,n,r,i){let o=this.createArgument(t,n);return typeof r=="function"?o.default(i).argParser(r):o.default(r),this.addArgument(o),this}arguments(t){return t.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(t){let n=this.registeredArguments.slice(-1)[0];if(n?.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,n){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let r=t??"help [command]",[,i,o]=r.match(/([^ ]+) *(.*)/),s=n??"display help for command",a=this.createCommand(i);return a.helpOption(!1),o&&a.arguments(o),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,(t||n)&&this._initCommandGroup(a),this}addHelpCommand(t,n){return typeof t!="object"?(this.helpCommand(t,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,n){let r=["preSubcommand","preAction","postAction"];if(!r.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
95
+ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(n):this._lifeCycleHooks[t]=[n],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(t,n,r){this._exitCallback&&this._exitCallback(new Us(t,n,r)),B.exit(t)}action(t){let n=r=>{let i=this.registeredArguments.length,o=r.slice(0,i);return this._storeOptionsAsProperties?o[i]=this:o[i]=this.opts(),o.push(this),t.apply(this,o)};return this._actionHandler=n,this}createOption(t,n){return new gp(t,n)}_callParseArg(t,n,r,i){try{return t.parseArg(n,r)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${i} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(t){let n=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(n){let r=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
96
+ - already used by option '${n.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let n=i=>[i.name()].concat(i.aliases()),r=n(t).find(i=>this._findCommand(i));if(r){let i=n(this._findCommand(r)).join("|"),o=n(t).join("|");throw new Error(`cannot add command '${o}' as already have command '${i}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);let n=t.name(),r=t.attributeName();if(t.negate){let o=t.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(r,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(r,t.defaultValue,"default");let i=(o,s,a)=>{o==null&&t.presetArg!==void 0&&(o=t.presetArg);let u=this.getOptionValue(r);o!==null&&t.parseArg?o=this._callParseArg(t,o,u,s):o!==null&&t.variadic&&(o=t._collectValue(o,u)),o==null&&(t.negate?o=!1:t.isBoolean()||t.optional?o=!0:o=""),this.setOptionValueWithSource(r,o,a)};return this.on("option:"+n,o=>{let s=`error: option '${t.flags}' argument '${o}' is invalid.`;i(o,s,"cli")}),t.envVar&&this.on("optionEnv:"+n,o=>{let s=`error: option '${t.flags}' value '${o}' from env '${t.envVar}' is invalid.`;i(o,s,"env")}),this}_optionEx(t,n,r,i,o){if(typeof n=="object"&&n instanceof gp)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(n,r);if(s.makeOptionMandatory(!!t.mandatory),typeof i=="function")s.default(o).argParser(i);else if(i instanceof RegExp){let a=i;i=(u,l)=>{let c=a.exec(u);return c?c[0]:l},s.default(o).argParser(i)}else s.default(i);return this.addOption(s)}option(t,n,r,i){return this._optionEx({},t,n,r,i)}requiredOption(t,n,r,i){return this._optionEx({mandatory:!0},t,n,r,i)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,n){return this.setOptionValueWithSource(t,n,void 0)}setOptionValueWithSource(t,n,r){return this._storeOptionsAsProperties?this[t]=n:this._optionValues[t]=n,this._optionValueSources[t]=r,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(t)!==void 0&&(n=r.getOptionValueSource(t))}),n}_prepareUserArgs(t,n){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},t===void 0&&n.from===void 0){B.versions?.electron&&(n.from="electron");let i=B.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(n.from="eval")}t===void 0&&(t=B.argv),this.rawArgs=t.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=t[1],r=t.slice(2);break;case"electron":B.defaultApp?(this._scriptPath=t[1],r=t.slice(2)):r=t.slice(1);break;case"user":r=t.slice(0);break;case"eval":r=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(t,n){this._prepareForParse();let r=this._prepareUserArgs(t,n);return this._parseCommand([],r),this}async parseAsync(t,n){this._prepareForParse();let r=this._prepareUserArgs(t,n);return await this._parseCommand([],r),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
97
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,n,r){if(li.existsSync(t))return;let i=n?`searched for local subcommand relative to directory '${n}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${t}' does not exist
98
+ - if '${r}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
99
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
100
+ - ${i}`;throw new Error(o)}_executeSubCommand(t,n){n=n.slice();let r=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function o(c,d){let f=Ve.resolve(c,d);if(li.existsSync(f))return f;if(i.includes(Ve.extname(d)))return;let p=i.find(g=>li.existsSync(`${f}${g}`));if(p)return`${f}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=li.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=Ve.resolve(Ve.dirname(c),a)}if(a){let c=o(a,s);if(!c&&!t._executableFile&&this._scriptPath){let d=Ve.basename(this._scriptPath,Ve.extname(this._scriptPath));d!==this._name&&(c=o(a,`${d}-${t._name}`))}s=c||s}r=i.includes(Ve.extname(s));let u;B.platform!=="win32"?r?(n.unshift(s),n=hp(B.execArgv).concat(n),u=Ns.spawn(B.argv[0],n,{stdio:"inherit"})):u=Ns.spawn(s,n,{stdio:"inherit"}):(this._checkForMissingExecutable(s,a,t._name),n.unshift(s),n=hp(B.execArgv).concat(n),u=Ns.spawn(B.execPath,n,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{B.on(d,()=>{u.killed===!1&&u.exitCode===null&&u.kill(d)})});let l=this._exitCallback;u.on("close",c=>{c=c??1,l?l(new Us(c,"commander.executeSubCommandAsync","(close)")):B.exit(c)}),u.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(s,a,t._name);else if(c.code==="EACCES")throw new Error(`'${s}' not executable`);if(!l)B.exit(1);else{let d=new Us(1,"commander.executeSubCommandAsync","(error)");d.nestedError=c,l(d)}}),this.runningCommand=u}_dispatchSubcommand(t,n,r){let i=this._findCommand(t);i||this.help({error:!0}),i._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(i._executableHandler)this._executeSubCommand(i,n.concat(r));else return i._parseCommand(n,r)}),o}_dispatchHelpCommand(t){t||this.help();let n=this._findCommand(t);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,n)=>{t.required&&this.args[n]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(r,i,o)=>{let s=i;if(i!==null&&r.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${r.name()}'.`;s=this._callParseArg(r,i,o,a)}return s};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((r,i)=>{let o=r.defaultValue;r.variadic?i<this.args.length?(o=this.args.slice(i),r.parseArg&&(o=o.reduce((s,a)=>t(r,a,s),r.defaultValue))):o===void 0&&(o=[]):i<this.args.length&&(o=this.args[i],r.parseArg&&(o=t(r,o,r.defaultValue))),n[i]=o}),this.processedArgs=n}_chainOrCall(t,n){return t?.then&&typeof t.then=="function"?t.then(()=>n()):n()}_chainOrCallHooks(t,n){let r=t,i=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[n]!==void 0).forEach(o=>{o._lifeCycleHooks[n].forEach(s=>{i.push({hookedCommand:o,callback:s})})}),n==="postAction"&&i.reverse(),i.forEach(o=>{r=this._chainOrCall(r,()=>o.callback(o.hookedCommand,this))}),r}_chainOrCallSubCommandHook(t,n,r){let i=t;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(o=>{i=this._chainOrCall(i,()=>o(this,n))}),i}_parseCommand(t,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(r.operands),n=r.unknown,this.args=t.concat(n),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),n);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,t,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(o,t,n)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,t,n);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,n);this.listenerCount("command:*")?this.emit("command:*",t,n):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(n=>n._name===t||n._aliases.includes(t))}_findOption(t){return this.options.find(n=>n.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(n=>{n.mandatory&&t.getOptionValue(n.attributeName())===void 0&&t.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(r=>{let i=r.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});t.filter(r=>r.conflictsWith.length>0).forEach(r=>{let i=t.find(o=>r.conflictsWith.includes(o.attributeName()));i&&this._conflictingOption(r,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let n=[],r=[],i=n;function o(c){return c.length>1&&c[0]==="-"}let s=c=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(c)?!this._getCommandAndAncestors().some(d=>d.options.map(f=>f.short).some(f=>/^-\d$/.test(f))):!1,a=null,u=null,l=0;for(;l<t.length||u;){let c=u??t[l++];if(u=null,c==="--"){i===r&&i.push(c),i.push(...t.slice(l));break}if(a&&(!o(c)||s(c))){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let d=this._findOption(c);if(d){if(d.required){let f=t[l++];f===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,f)}else if(d.optional){let f=null;l<t.length&&(!o(t[l])||s(t[l]))&&(f=t[l++]),this.emit(`option:${d.name()}`,f)}else this.emit(`option:${d.name()}`);a=d.variadic?d:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let d=this._findOption(`-${c[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,c.slice(2)):(this.emit(`option:${d.name()}`),u=`-${c.slice(2)}`);continue}}if(/^--[^=]+=/.test(c)){let d=c.indexOf("="),f=this._findOption(c.slice(0,d));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,c.slice(d+1));continue}}if(i===n&&o(c)&&!(this.commands.length===0&&s(c))&&(i=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(c)){n.push(c),r.push(...t.slice(l));break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c,...t.slice(l));break}else if(this._defaultCommandName){r.push(c,...t.slice(l));break}}if(this._passThroughOptions){i.push(c,...t.slice(l));break}i.push(c)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let t={},n=this.options.length;for(let r=0;r<n;r++){let i=this.options[r].attributeName();t[i]=i===this._versionOptionName?this._version:this[i]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,n)=>Object.assign(t,n.opts()),{})}error(t,n){this._outputConfiguration.outputError(`${t}
101
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
102
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
103
+ `),this.outputHelp({error:!0}));let r=n||{},i=r.exitCode||1,o=r.code||"commander.error";this._exit(i,o,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in B.env){let n=t.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,B.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new fE(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&t.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(i=>!n(i)).forEach(i=>{this.setOptionValueWithSource(i,r.implied[i],"implied")})})}missingArgument(t){let n=`error: missing required argument '${t}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(t){let n=`error: option '${t.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let n=`error: required option '${t.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,n){let r=s=>{let a=s.attributeName(),u=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),c=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&u===!1||l.presetArg!==void 0&&u===l.presetArg)?l:c||s},i=s=>{let a=r(s),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${i(t)} cannot be used with ${i(n)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let n="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[],o=this;do{let s=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);i=i.concat(s),o=o.parent}while(o&&!o._enablePositionalOptions);n=mp(t,i)}let r=`error: unknown option '${t}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${t.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],n="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(o=>{i.push(o.name()),o.alias()&&i.push(o.alias())}),n=mp(t,i)}let r=`error: unknown command '${t}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(t,n,r){if(t===void 0)return this._version;this._version=t,n=n||"-V, --version",r=r||"output the version number";let i=this.createOption(n,r);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${t}
104
+ `),this._exit(0,"commander.version",t)}),this}description(t,n){return t===void 0&&n===void 0?this._description:(this._description=t,n&&(this._argsDescription=n),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),t===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(t);if(r){let i=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${i}'`)}return n._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(n=>this.alias(n)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>dE(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=Ve.basename(t,Ve.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let n=this.createHelp(),r=this._getOutputContext(t);n.prepareContext({error:r.error,helpWidth:r.helpWidth,outputHasColors:r.hasColors});let i=n.formatHelp(this,n);return r.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(t){t=t||{};let n=!!t.error,r,i,o;return n?(r=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(r=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),r(a)),hasColors:i,helpWidth:o}}outputHelp(t){let n;typeof t=="function"&&(n=t,t=void 0);let r=this._getOutputContext(t),i={error:r.error,write:r.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let o=this.helpInformation({error:r.error});if(n&&(o=n(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",i))}helpOption(t,n){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",n??"display help for command"),(t||n)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let n=Number(B.exitCode??0);n===0&&t&&typeof t!="function"&&t.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(t,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(t))throw new Error(`Unexpected value for position to addHelpText.
105
+ Expecting one of '${r.join("', '")}'`);let i=`${t}Help`;return this.on(i,o=>{let s;typeof n=="function"?s=n({error:o.error,command:o.command}):s=n,s&&o.write(`${s}
106
+ `)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(i=>n.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function hp(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",i="9229",o;return(o=t.match(/^(--inspect(-brk)?)$/))!==null?n=o[1]:(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=o[1],/^\d+$/.test(o[3])?i=o[3]:r=o[3]):(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=o[1],r=o[3],i=o[4]),n&&i!=="0"?`${n}=${r}:${parseInt(i)+1}`:t})}function Vs(){if(B.env.NO_COLOR||B.env.FORCE_COLOR==="0"||B.env.FORCE_COLOR==="false")return!1;if(B.env.FORCE_COLOR||B.env.CLICOLOR_FORCE!==void 0)return!0}Gs.Command=js;Gs.useColor=Vs});var kp=re(Ae=>{var{Argument:wp}=ci(),{Command:Bs}=yp(),{CommanderError:pE,InvalidArgumentError:bp}=Nn(),{Help:gE}=Ms(),{Option:Rp}=Fs();Ae.program=new Bs;Ae.createCommand=e=>new Bs(e);Ae.createOption=(e,t)=>new Rp(e,t);Ae.createArgument=(e,t)=>new wp(e,t);Ae.Command=Bs;Ae.Option=Rp;Ae.Argument=wp;Ae.Help=gE;Ae.CommanderError=pE;Ae.InvalidArgumentError=bp;Ae.InvalidOptionArgumentError=bp});var Ap,bP,RP,kP,AP,SP,CP,EP,Sp,vP,Cp,xP,Hs=v(()=>{Ap=Ba(kp(),1),{program:bP,createCommand:RP,createArgument:kP,createOption:AP,CommanderError:SP,InvalidArgumentError:CP,InvalidOptionArgumentError:EP,Command:Sp,Argument:vP,Option:Cp,Help:xP}=Ap.default});function Js(e){e.status!=="ok"&&(process.exitCode=1)}function mE(e,t){Js(t),e(`${JSON.stringify(t)}
107
+ `)}function we(e,t,n=!1,r){if(Js(t),n){let{raw:i,...o}=t.data??{};e(`${JSON.stringify({...t,data:o})}
108
+ `)}else e(`${oe(t,r)}
109
+ `)}function zs(e){if(!(typeof e!="string"||e.length===0))return/^https?:\/\//i.test(e)?e:`https://marquee.gs.com${e.startsWith("/")?"":"/"}${e}`}function Ep(e){return e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]}function vp(e){if(e.startsWith("/content/")||e.startsWith("/s/content/"))return e;try{return new URL(e).pathname}catch{return}}function hE(e,t,n="en"){let[r,i,o]=t.split("-");return`/content/research/${n}/reports/${r}/${i}/${o}/${e}.html`}function yE(e){let t=e.trim(),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)throw new Error(`invalid date "${t}"; expected YYYY-MM-DD`);let r=Number(n[1]),i=Number(n[2])-1,o=Number(n[3]),s=new Date(Date.UTC(r,i,o));if(s.getUTCFullYear()!==r||s.getUTCMonth()!==i||s.getUTCDate()!==o)throw new Error(`invalid date "${t}"; expected YYYY-MM-DD`);return t}function wE(e,t){let n=typeof e.url=="string"?e.url:zs(String(t.url??t.path??""));return{type:"article",id:String(e.id??t.id??""),title:String(e.title??t.title??""),...n?{url:n}:{},...typeof e.source=="string"?{source:e.source}:typeof t.source=="string"?{source:t.source}:{},...typeof t.documentSource=="string"?{documentSource:t.documentSource}:{}}}function bE(e,t,n,r){if(n.status!=="ok"||!m(n.data.result))return;let i=wE(n.data.result,r),o=typeof i.url=="string"?i.url:void 0;e.storeArtifact({namespace:t,root:i,refs:o?{[`${t}.link`]:{type:"link",url:o}}:{},payload:n.data.result})}async function xp(e,t,n,r=!1){let i=await e.getRouter().execute({surface:"content",action:"get",input:n});bE(e.getRegistry(),t,i,n),we(e.write,i,r,{namespace:t})}function RE(){return{status:"error",surface:"content",action:"search",data:{},errors:["--limit is not supported for content search; page size is fixed at 10 in V1"]}}function kE(e=[]){return e.some(t=>t==="--author"||t.startsWith("--author="))}function AE(e,t=[]){return[...t,e]}function SE(e){let t=[];for(let n of e??[]){let r=n.indexOf("=");if(r<=0||r===n.length-1)return{error:"--select must use <field>=<value>"};let i=n.slice(0,r).trim(),o=n.slice(r+1).trim();if(!i||!o)return{error:"--select must use <field>=<value>"};t.push({field:i,value:o})}return t.length>0?{filters:t}:{}}function CE(e){return e==="time"||e==="relevance"}function Ip(e,t){let n=e.command("content");n.command("search").argument("[query...]").allowUnknownOption(!0).addOption(new Cp("--limit <limit>","deferred page-size override").default("10").hideHelp()).option("--select <field=value>","apply a facet filter before querying",AE,[]).option("--from <date>","publication date lower bound (YYYY-MM-DD)").option("--to <date>","publication date upper bound (YYYY-MM-DD)").option("--sort <sort>","sort by time or relevance").option("--json").action(async(r,i,o)=>{if(kE(r)){let c={status:"error",surface:"content",action:"search",data:{},errors:["--author is not supported by this content search slice; use a plain query instead."]};we(t.write,c,i.json);return}let s=(r??[]).join(" ").trim();if(!s){let c={status:"error",surface:"content",action:"search",data:{},errors:["query is required"]};we(t.write,c,i.json);return}if(o.getOptionValueSource("limit")==="cli"){we(t.write,RE(),i.json);return}let a=SE(i.select);if(a.error){let c={status:"error",surface:"content",action:"search",data:{},errors:[a.error]};we(t.write,c,i.json);return}if(i.sort!==void 0&&!CE(i.sort)){let c={status:"error",surface:"content",action:"search",data:{},errors:["--sort must be time or relevance"]};we(t.write,c,i.json);return}let u={query:s,limit:10,...a.filters?{select:a.filters}:{},...typeof i.from=="string"&&i.from.length>0?{from:i.from}:{},...typeof i.to=="string"&&i.to.length>0?{to:i.to}:{},...i.sort?{sort:i.sort}:{}},l=await t.getRouter().execute({surface:"content",action:"search",input:u});if(i.json){mE(t.write,l);return}if(l.status==="ok"&&Gt(l.data.result)){let c=t.getRegistry(),d=c.claimSearch();ei(c,d,l.data.result),we(t.write,l,!1,{searchNamespace:d});return}if(l.status==="ok"&&Array.isArray(l.data.result)){let c=t.getRegistry(),d=c.claimSearch();c.storeArtifact({namespace:d,root:{type:"search",query:s},payload:l.data.result}),we(t.write,l,!1,{store:le(c,d),searchNamespace:d});return}we(t.write,l,!1)}),n.command("markets").argument("<input>","content markets UUID or URL").option("--json").action(async(r,i)=>{let o=Ep(r);if(!o){we(t.write,{status:"error",surface:"content",action:"get",data:{},errors:["content markets requires a UUID or content markets URL"]},i.json);return}let s=vp(r),a=t.getRegistry().claimContentMarkets();await xp(t,a,{id:o,documentSource:"sec_div",source:"FICC and Equities",...s?{path:s,url:zs(s)}:{}},i.json)}),n.command("research").argument("<input>","content research UUID or URL").option("--date <date>","publication date for UUID input (YYYY-MM-DD)").option("--lang <lang>","language segment for UUID input","en").option("--json").action(async(r,i)=>{let o=Ep(r);if(!o){we(t.write,{status:"error",surface:"content",action:"get",data:{},errors:["content research requires a UUID or content research URL"]},i.json);return}let s=vp(r);if(!s){if(!i.date){let u={status:"error",surface:"content",action:"get",data:{},errors:["--date is required when loading content research by UUID"]};i.json?we(t.write,u,!0):(Js(u),t.write(["\u2717 --date YYYY-MM-DD is required for UUID input."," The GIR HTML path requires the publication date to construct."," Alternatives:"," - Add --date: marquee content research 123e4567-... --date 2026-01-15"," - Use the full URL: marquee content research https://marquee.gs.com/content/research/en/reports/2026/01/15/123e4567-....html",' - Search + load: marquee content search "<query>" -> load @s1.crN'].join(`
110
+ `)+`
111
+ `));return}try{s=hE(o,yE(i.date),i.lang??"en")}catch(u){we(t.write,{status:"error",surface:"content",action:"get",data:{},errors:[u instanceof Error?u.message:String(u)]},i.json);return}}let a=t.getRegistry().claimContentResearch();await xp(t,a,{id:o,documentSource:"RELAY_DOCUMENT_LEGACY",path:s,url:zs(s)},i.json)})}var Dp=v(()=>{"use strict";Hs();Z();On();Me()});function EE(e){return e.startsWith("@")?e.slice(1):e}function vE(e){return m(e)&&String(e.type??"article")==="article"}function xE(e,t={}){if(/^(?:cm|cr)[1-9]\d*$/.test(e))return{namespace:e,index:0,searchRef:!1,directRef:!0};let n=t.allowSearchResultRefs?"(?:a|cm|cr)":"a",r=new RegExp(`^(.+)\\.${n}([1-9]\\d*)$`).exec(e);if(r)return{namespace:r[1],index:Number.parseInt(r[2],10)-1,searchRef:!e.endsWith(`.a${r[2]}`),directRef:!1}}function IE(e,t,n){if(t.directRef)return e;let r=typeof n.id=="string"&&n.id.length>0?n.id:void 0;if(Array.isArray(e))return t.searchRef&&r?e.find(i=>m(i)&&String(i.id??"")===r):e[t.index];if(m(e)&&Array.isArray(e.results))return t.searchRef&&r?e.results.find(i=>m(i)&&String(i.id??"")===r):e.results[t.index]}function DE(e,t){let n=Array.isArray(e.authors)?e.authors.map(String).filter(i=>i.length>0):void 0,r=typeof e.url=="string"&&e.url.length>0?e.url:t;return{id:String(e.id??""),type:"article",title:String(e.title??e.name??""),...typeof e.publicationDate=="string"?{publicationDate:e.publicationDate}:{},...n&&n.length>0?{authors:n}:{},...typeof e.source=="string"?{source:e.source}:{},...typeof e.documentSource=="string"?{documentSource:e.documentSource}:{},...typeof e.quote=="string"?{quote:e.quote}:{},...typeof e.synopsis=="string"?{synopsis:e.synopsis}:{},...typeof e.path=="string"?{path:e.path}:{},...typeof e.downloadPath=="string"?{downloadPath:e.downloadPath}:{},...r?{url:r}:{}}}function Tp(e,t,n={}){if(!e)return{ok:!1,response:{status:"error",surface:"content",action:"get",data:{},errors:["article ref is required"]}};let r=EE(e),i=t.resolveRef(r),o=xE(r,n);if(!o||!i||i.type!=="link"&&i.type!=="article")return{ok:!1,namespace:r,response:{status:"error",surface:"content",action:"get",data:{},errors:[`ref @${r} is not a content article ref`]}};let s=t.getPayload(o.namespace),a=IE(s,o,i);return vE(a)?{ok:!0,namespace:r,input:DE(o.directRef?{...i,...a}:a,typeof i.url=="string"?i.url:void 0)}:{ok:!1,namespace:r,response:{status:"error",surface:"content",action:"get",data:{},errors:[`article payload for @${r} not found`]}}}var Pp=v(()=>{"use strict";Q()});function Ks(e){e.status!=="ok"&&(process.exitCode=1)}function Un(e,t,n=!1,r){if(Ks(t),n){let{raw:i,...o}=t.data??{};e(`${JSON.stringify({...t,data:o})}
112
+ `)}else e(`${oe(t,r)}
113
+ `)}function et(e){if(!(typeof e!="string"||e.length===0))return/^https?:\/\//i.test(e)?e:`https://marquee.gs.com${e.startsWith("/")?"":"/"}${e}`}function Ys(e){if(typeof e!="string"||e.length===0)return!1;let t=e.search(/[?#]/),n=t>=0?e.slice(0,t):e;return/\.html$/i.test(n)||/\.pdf$/i.test(n)}function TE(e){return e.documentSource==="RELAY_DOCUMENT_LEGACY",et(e.url)??et(e.path)??et(e.downloadPath)}function PE(e){let t=e.documentSource;return t==="RELAY_DOCUMENT_LEGACY"?!Ys(e.path)&&!Ys(e.url)&&!Ys(e.downloadPath):typeof t=="string"&&t!=="sec_div"}function _E(e){return e instanceof Error&&e.message.length>0?e.message:String(e)}function $E(e,t){let n=e.documentSource==="RELAY_DOCUMENT_LEGACY"?"no GIR HTML article path is available":"no inline body endpoint is available",r=t===void 0?"opened in browser":`browser open failed: ${_E(t)}`;return{status:t===void 0?"ok":"error",surface:"content",action:"get",data:{result:{id:String(e.id??""),type:"article",title:String(e.title??""),...typeof e.publicationDate=="string"?{publicationDate:e.publicationDate}:{},...Array.isArray(e.authors)?{authors:e.authors.map(String)}:{},...typeof e.source=="string"?{source:e.source}:{},...typeof e.synopsis=="string"?{synopsis:e.synopsis}:{},...et(e.url??e.path)?{url:et(e.url??e.path)}:{},body:`${r} - ${n} (\`load\` -> \`open\` fallback).`}},errors:t===void 0?[]:[r]}}function _p(e,t,n){if(!t||n.status!=="ok"||!m(n.data?.result))return;let r=e.resolveRef(t);!r||r.type!=="article"||(e.setPayload(t,n.data.result),e.setRefs(t,{[t]:{...r}}))}async function $p(e,t,n=!1){let r=e.getRegistry(),i=Tp(t,r,{allowSearchResultRefs:!0});if(!i.ok){Ks(i.response),Un(e.write,i.response,n,{namespace:i.namespace});return}if(PE(i.input)){let s=TE(i.input),a;if(s){let l=e.getBrowserTransport();try{await e.syncBrowserAuthState(l,s),await l.run("open",[s])}catch(c){a=c}}else a=new Error("no URL, path, or downloadPath is available");let u=$E(i.input,a);_p(r,i.namespace,u),Un(e.write,u,n,{namespace:i.namespace,articleActions:"open|load"});return}let o=await e.getRouter().execute({surface:"content",action:"get",input:i.input});Ks(o),_p(r,i.namespace,o),Un(e.write,o,n,{namespace:i.namespace,articleActions:"open|load"})}async function Op(e,t,n){let r=await e.getRouter().execute({surface:"content",action:"search",input:n});if(r.status==="ok"&&Gt(r.data.result)){ei(e.getRegistry(),t,r.data.result),Un(e.write,r,!1,{searchNamespace:t});return}Un(e.write,r,!1)}var Mp=v(()=>{"use strict";Z();On();Me();Pp()});function OE(e){return e>1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:String(e)}function Wp(e){let t=typeof e.name=="string"?e.name:"";if(!t)return;let n=typeof e.count=="number"&&Number.isFinite(e.count)?e.count:0;return`${e.selected===!0?"\u2713 ":""}${ue(t)} (${OE(n)})`}function Lp(e,t,n){let r=typeof n.field=="string"?n.field:"";if(!r)return{ok:!1,text:`Error: @${t} is not a content facet ref`};let i=e.getPayload(ke(t)),s=(m(i)&&Array.isArray(i.facets)?i.facets:[]).filter(m).find(a=>a.field===r);return!s||!Array.isArray(s.values)?{ok:!1,text:`Error: @${t} facet payload not cached. Re-run \`marquee content search <query>\`.`}:{ok:!0,values:s.values.filter(m)}}function qp(e,t,n,r){let i=Lp(e,t,n);if(!("values"in i))return i;let o=r.toLowerCase(),s=i.values.filter(a=>typeof a.name=="string"&&a.name.toLowerCase().includes(o)).slice(0,30).map(Wp).filter(a=>!!a);return s.length===0?{ok:!0,text:`No matches for "${r}" in @${t}`}:{ok:!0,text:`- @${t} matches for "${r}":
114
+ ${s.join(", ")}`}}function Fp(e,t,n){let r=Lp(e,t,n);if(!("values"in r))return r;let i=r.values.length,o=r.values.map(Wp).filter(a=>!!a);return{ok:!0,text:[`@${t} (showing ${o.length} of ${i}):`,` ${o.join(", ")}`].join(`
115
+ `)}}var Qs=v(()=>{"use strict";_n();Z()});var Up=re((GP,Np)=>{var tt=he("constants"),ME=process.cwd,fi=null,WE=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return fi||(fi=ME.call(process)),fi};try{process.cwd()}catch{}typeof process.chdir=="function"&&(Zs=process.chdir,process.chdir=function(e){fi=null,Zs.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,Zs));var Zs;Np.exports=LE;function LE(e){tt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=o(e.chown),e.fchown=o(e.fchown),e.lchown=o(e.lchown),e.chmod=r(e.chmod),e.fchmod=r(e.fchmod),e.lchmod=r(e.lchmod),e.chownSync=s(e.chownSync),e.fchownSync=s(e.fchownSync),e.lchownSync=s(e.lchownSync),e.chmodSync=i(e.chmodSync),e.fchmodSync=i(e.fchmodSync),e.lchmodSync=i(e.lchmodSync),e.stat=a(e.stat),e.fstat=a(e.fstat),e.lstat=a(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(c,d,f){f&&process.nextTick(f)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(c,d,f,p){p&&process.nextTick(p)},e.lchownSync=function(){}),WE==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(c){function d(f,p,g){var h=Date.now(),y=0;c(f,p,function w(b){if(b&&(b.code==="EACCES"||b.code==="EPERM"||b.code==="EBUSY")&&Date.now()-h<6e4){setTimeout(function(){e.stat(p,function(R,S){R&&R.code==="ENOENT"?c(f,p,w):g(b)})},y),y<100&&(y+=10);return}g&&g(b)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,c),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(c){function d(f,p,g,h,y,w){var b;if(w&&typeof w=="function"){var R=0;b=function(S,C,x){if(S&&S.code==="EAGAIN"&&R<10)return R++,c.call(e,f,p,g,h,y,b);w.apply(this,arguments)}}return c.call(e,f,p,g,h,y,b)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,c),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(c){return function(d,f,p,g,h){for(var y=0;;)try{return c.call(e,d,f,p,g,h)}catch(w){if(w.code==="EAGAIN"&&y<10){y++;continue}throw w}}})(e.readSync);function t(c){c.lchmod=function(d,f,p){c.open(d,tt.O_WRONLY|tt.O_SYMLINK,f,function(g,h){if(g){p&&p(g);return}c.fchmod(h,f,function(y){c.close(h,function(w){p&&p(y||w)})})})},c.lchmodSync=function(d,f){var p=c.openSync(d,tt.O_WRONLY|tt.O_SYMLINK,f),g=!0,h;try{h=c.fchmodSync(p,f),g=!1}finally{if(g)try{c.closeSync(p)}catch{}else c.closeSync(p)}return h}}function n(c){tt.hasOwnProperty("O_SYMLINK")&&c.futimes?(c.lutimes=function(d,f,p,g){c.open(d,tt.O_SYMLINK,function(h,y){if(h){g&&g(h);return}c.futimes(y,f,p,function(w){c.close(y,function(b){g&&g(w||b)})})})},c.lutimesSync=function(d,f,p){var g=c.openSync(d,tt.O_SYMLINK),h,y=!0;try{h=c.futimesSync(g,f,p),y=!1}finally{if(y)try{c.closeSync(g)}catch{}else c.closeSync(g)}return h}):c.futimes&&(c.lutimes=function(d,f,p,g){g&&process.nextTick(g)},c.lutimesSync=function(){})}function r(c){return c&&function(d,f,p){return c.call(e,d,f,function(g){l(g)&&(g=null),p&&p.apply(this,arguments)})}}function i(c){return c&&function(d,f){try{return c.call(e,d,f)}catch(p){if(!l(p))throw p}}}function o(c){return c&&function(d,f,p,g){return c.call(e,d,f,p,function(h){l(h)&&(h=null),g&&g.apply(this,arguments)})}}function s(c){return c&&function(d,f,p){try{return c.call(e,d,f,p)}catch(g){if(!l(g))throw g}}}function a(c){return c&&function(d,f,p){typeof f=="function"&&(p=f,f=null);function g(h,y){y&&(y.uid<0&&(y.uid+=4294967296),y.gid<0&&(y.gid+=4294967296)),p&&p.apply(this,arguments)}return f?c.call(e,d,f,g):c.call(e,d,g)}}function u(c){return c&&function(d,f){var p=f?c.call(e,d,f):c.call(e,d);return p&&(p.uid<0&&(p.uid+=4294967296),p.gid<0&&(p.gid+=4294967296)),p}}function l(c){if(!c||c.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;return!!(d&&(c.code==="EINVAL"||c.code==="EPERM"))}}});var Gp=re((BP,Vp)=>{var jp=he("stream").Stream;Vp.exports=qE;function qE(e){return{ReadStream:t,WriteStream:n};function t(r,i){if(!(this instanceof t))return new t(r,i);jp.call(this);var o=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,i=i||{};for(var s=Object.keys(i),a=0,u=s.length;a<u;a++){var l=s[a];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){o._read()});return}e.open(this.path,this.flags,this.mode,function(c,d){if(c){o.emit("error",c),o.readable=!1;return}o.fd=d,o.emit("open",d),o._read()})}function n(r,i){if(!(this instanceof n))return new n(r,i);jp.call(this),this.path=r,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,i=i||{};for(var o=Object.keys(i),s=0,a=o.length;s<a;s++){var u=o[s];this[u]=i[u]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var Hp=re((HP,Bp)=>{"use strict";Bp.exports=NE;var FE=Object.getPrototypeOf||function(e){return e.__proto__};function NE(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:FE(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var na=re((zP,ta)=>{var ee=he("fs"),UE=Up(),jE=Gp(),VE=Hp(),pi=he("util"),de,mi;typeof Symbol=="function"&&typeof Symbol.for=="function"?(de=Symbol.for("graceful-fs.queue"),mi=Symbol.for("graceful-fs.previous")):(de="___graceful-fs.queue",mi="___graceful-fs.previous");function GE(){}function Yp(e,t){Object.defineProperty(e,de,{get:function(){return t}})}var mt=GE;pi.debuglog?mt=pi.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(mt=function(){var e=pi.format.apply(pi,arguments);e="GFS4: "+e.split(/\n/).join(`
116
+ GFS4: `),console.error(e)});ee[de]||(zp=global[de]||[],Yp(ee,zp),ee.close=(function(e){function t(n,r){return e.call(ee,n,function(i){i||Jp(),typeof r=="function"&&r.apply(this,arguments)})}return Object.defineProperty(t,mi,{value:e}),t})(ee.close),ee.closeSync=(function(e){function t(n){e.apply(ee,arguments),Jp()}return Object.defineProperty(t,mi,{value:e}),t})(ee.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){mt(ee[de]),he("assert").equal(ee[de].length,0)}));var zp;global[de]||Yp(global,ee[de]);ta.exports=Xs(VE(ee));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!ee.__patched&&(ta.exports=Xs(ee),ee.__patched=!0);function Xs(e){UE(e),e.gracefulify=Xs,e.createReadStream=C,e.createWriteStream=x;var t=e.readFile;e.readFile=n;function n(D,A,I){return typeof A=="function"&&(I=A,A=null),O(D,A,I);function O(M,N,V,G){return t(M,N,function(W){W&&(W.code==="EMFILE"||W.code==="ENFILE")?en([O,[M,N,V],W,G||Date.now(),Date.now()]):typeof V=="function"&&V.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=i;function i(D,A,I,O){return typeof I=="function"&&(O=I,I=null),M(D,A,I,O);function M(N,V,G,W,K){return r(N,V,G,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?en([M,[N,V,G,W],z,K||Date.now(),Date.now()]):typeof W=="function"&&W.apply(this,arguments)})}}var o=e.appendFile;o&&(e.appendFile=s);function s(D,A,I,O){return typeof I=="function"&&(O=I,I=null),M(D,A,I,O);function M(N,V,G,W,K){return o(N,V,G,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?en([M,[N,V,G,W],z,K||Date.now(),Date.now()]):typeof W=="function"&&W.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=u);function u(D,A,I,O){return typeof I=="function"&&(O=I,I=0),M(D,A,I,O);function M(N,V,G,W,K){return a(N,V,G,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?en([M,[N,V,G,W],z,K||Date.now(),Date.now()]):typeof W=="function"&&W.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var c=/^v[0-5]\./;function d(D,A,I){typeof A=="function"&&(I=A,A=null);var O=c.test(process.version)?function(V,G,W,K){return l(V,M(V,G,W,K))}:function(V,G,W,K){return l(V,G,M(V,G,W,K))};return O(D,A,I);function M(N,V,G,W){return function(K,z){K&&(K.code==="EMFILE"||K.code==="ENFILE")?en([O,[N,V,G],K,W||Date.now(),Date.now()]):(z&&z.sort&&z.sort(),typeof G=="function"&&G.call(this,K,z))}}}if(process.version.substr(0,4)==="v0.8"){var f=jE(e);w=f.ReadStream,R=f.WriteStream}var p=e.ReadStream;p&&(w.prototype=Object.create(p.prototype),w.prototype.open=b);var g=e.WriteStream;g&&(R.prototype=Object.create(g.prototype),R.prototype.open=S),Object.defineProperty(e,"ReadStream",{get:function(){return w},set:function(D){w=D},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return R},set:function(D){R=D},enumerable:!0,configurable:!0});var h=w;Object.defineProperty(e,"FileReadStream",{get:function(){return h},set:function(D){h=D},enumerable:!0,configurable:!0});var y=R;Object.defineProperty(e,"FileWriteStream",{get:function(){return y},set:function(D){y=D},enumerable:!0,configurable:!0});function w(D,A){return this instanceof w?(p.apply(this,arguments),this):w.apply(Object.create(w.prototype),arguments)}function b(){var D=this;j(D.path,D.flags,D.mode,function(A,I){A?(D.autoClose&&D.destroy(),D.emit("error",A)):(D.fd=I,D.emit("open",I),D.read())})}function R(D,A){return this instanceof R?(g.apply(this,arguments),this):R.apply(Object.create(R.prototype),arguments)}function S(){var D=this;j(D.path,D.flags,D.mode,function(A,I){A?(D.destroy(),D.emit("error",A)):(D.fd=I,D.emit("open",I))})}function C(D,A){return new e.ReadStream(D,A)}function x(D,A){return new e.WriteStream(D,A)}var E=e.open;e.open=j;function j(D,A,I,O){return typeof I=="function"&&(O=I,I=null),M(D,A,I,O);function M(N,V,G,W,K){return E(N,V,G,function(z,Wi){z&&(z.code==="EMFILE"||z.code==="ENFILE")?en([M,[N,V,G,W],z,K||Date.now(),Date.now()]):typeof W=="function"&&W.apply(this,arguments)})}}return e}function en(e){mt("ENQUEUE",e[0].name,e[1]),ee[de].push(e),ea()}var gi;function Jp(){for(var e=Date.now(),t=0;t<ee[de].length;++t)ee[de][t].length>2&&(ee[de][t][3]=e,ee[de][t][4]=e);ea()}function ea(){if(clearTimeout(gi),gi=void 0,ee[de].length!==0){var e=ee[de].shift(),t=e[0],n=e[1],r=e[2],i=e[3],o=e[4];if(i===void 0)mt("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-i>=6e4){mt("TIMEOUT",t.name,n);var s=n.pop();typeof s=="function"&&s.call(null,r)}else{var a=Date.now()-o,u=Math.max(o-i,1),l=Math.min(u*1.2,100);a>=l?(mt("RETRY",t.name,n),t.apply(null,n.concat([i]))):ee[de].push(e)}gi===void 0&&(gi=setTimeout(ea,0))}}});var Qp=re((JP,Kp)=>{function Se(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Kp.exports=Se;Se.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};Se.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};Se.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1;var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0};Se.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Se.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};Se.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};Se.prototype.start=Se.prototype.try;Se.prototype.errors=function(){return this._errors};Se.prototype.attempts=function(){return this._attempts};Se.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],o=i.message,s=(e[o]||0)+1;e[o]=s,s>=n&&(t=i,n=s)}return t}});var Zp=re(ht=>{var BE=Qp();ht.operation=function(e){var t=ht.timeouts(e);return new BE(t,{forever:e&&e.forever,unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};ht.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(o,s){return o-s}),r};ht.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*Math.pow(t.factor,e));return r=Math.min(r,t.maxTimeout),r};ht.wrap=function(e,t,n){if(t instanceof Array&&(n=t,t=null),!n){n=[];for(var r in e)typeof e[r]=="function"&&n.push(r)}for(var i=0;i<n.length;i++){var o=n[i],s=e[o];e[o]=function(u){var l=ht.operation(t),c=Array.prototype.slice.call(arguments,1),d=c.pop();c.push(function(f){l.retry(f)||(f&&(arguments[0]=l.mainError()),d.apply(this,arguments))}),l.attempt(function(){u.apply(e,c)})}.bind(e,s),e[o].options=t}}});var eg=re((KP,Xp)=>{Xp.exports=Zp()});var tg=re((QP,hi)=>{hi.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&hi.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&hi.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var sg=re((ZP,rn)=>{var X=global.process,yt=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};yt(X)?(ng=he("assert"),tn=tg(),rg=/^win/i.test(X.platform),jn=he("events"),typeof jn!="function"&&(jn=jn.EventEmitter),X.__signal_exit_emitter__?se=X.__signal_exit_emitter__:(se=X.__signal_exit_emitter__=new jn,se.count=0,se.emitted={}),se.infinite||(se.setMaxListeners(1/0),se.infinite=!0),rn.exports=function(e,t){if(!yt(global.process))return function(){};ng.equal(typeof e,"function","a callback must be provided for exit handler"),nn===!1&&ra();var n="exit";t&&t.alwaysLast&&(n="afterexit");var r=function(){se.removeListener(n,e),se.listeners("exit").length===0&&se.listeners("afterexit").length===0&&yi()};return se.on(n,e),r},yi=function(){!nn||!yt(global.process)||(nn=!1,tn.forEach(function(t){try{X.removeListener(t,wi[t])}catch{}}),X.emit=bi,X.reallyExit=ia,se.count-=1)},rn.exports.unload=yi,wt=function(t,n,r){se.emitted[t]||(se.emitted[t]=!0,se.emit(t,n,r))},wi={},tn.forEach(function(e){wi[e]=function(){if(yt(global.process)){var n=X.listeners(e);n.length===se.count&&(yi(),wt("exit",null,e),wt("afterexit",null,e),rg&&e==="SIGHUP"&&(e="SIGINT"),X.kill(X.pid,e))}}}),rn.exports.signals=function(){return tn},nn=!1,ra=function(){nn||!yt(global.process)||(nn=!0,se.count+=1,tn=tn.filter(function(t){try{return X.on(t,wi[t]),!0}catch{return!1}}),X.emit=og,X.reallyExit=ig)},rn.exports.load=ra,ia=X.reallyExit,ig=function(t){yt(global.process)&&(X.exitCode=t||0,wt("exit",X.exitCode,null),wt("afterexit",X.exitCode,null),ia.call(X,X.exitCode))},bi=X.emit,og=function(t,n){if(t==="exit"&&yt(global.process)){n!==void 0&&(X.exitCode=n);var r=bi.apply(this,arguments);return wt("exit",X.exitCode,null),wt("afterexit",X.exitCode,null),r}else return bi.apply(this,arguments)}):rn.exports=function(){return function(){}};var ng,tn,rg,jn,se,yi,wt,wi,nn,ra,ia,ig,bi,og});var ug=re((XP,oa)=>{"use strict";var ag=Symbol();function HE(e,t,n){let r=t[ag];if(r)return t.stat(e,(o,s)=>{if(o)return n(o);n(null,s.mtime,r)});let i=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,i,i,o=>{if(o)return n(o);t.stat(e,(s,a)=>{if(s)return n(s);let u=a.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(t,ag,{value:u}),n(null,a.mtime,u)})})}function zE(e){let t=Date.now();return e==="s"&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}oa.exports.probe=HE;oa.exports.getMtime=zE});var pg=re((e_,Gn)=>{"use strict";var JE=he("path"),ua=na(),YE=eg(),KE=sg(),dg=ug(),Ge={};function Vn(e,t){return t.lockfilePath||`${e}.lock`}function da(e,t,n){if(!t.realpath)return n(null,JE.resolve(e));t.fs.realpath(e,n)}function aa(e,t,n){let r=Vn(e,t);t.fs.mkdir(r,i=>{if(!i)return dg.probe(r,t.fs,(o,s,a)=>{if(o)return t.fs.rmdir(r,()=>{}),n(o);n(null,s,a)});if(i.code!=="EEXIST")return n(i);if(t.stale<=0)return n(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:e}));t.fs.stat(r,(o,s)=>{if(o)return o.code==="ENOENT"?aa(e,{...t,stale:0},n):n(o);if(!cg(s,t))return n(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:e}));lg(e,t,a=>{if(a)return n(a);aa(e,{...t,stale:0},n)})})})}function cg(e,t){return e.mtime.getTime()<Date.now()-t.stale}function lg(e,t,n){t.fs.rmdir(Vn(e,t),r=>{if(r&&r.code!=="ENOENT")return n(r);n()})}function Ri(e,t){let n=Ge[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let o=n.lastUpdate+t.stale<Date.now();if(r)return r.code==="ENOENT"||o?sa(e,n,Object.assign(r,{code:"ECOMPROMISED"})):(n.updateDelay=1e3,Ri(e,t));if(!(n.mtime.getTime()===i.mtime.getTime()))return sa(e,n,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let a=dg.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,a,a,u=>{let l=n.lastUpdate+t.stale<Date.now();if(!n.released){if(u)return u.code==="ENOENT"||l?sa(e,n,Object.assign(u,{code:"ECOMPROMISED"})):(n.updateDelay=1e3,Ri(e,t));n.mtime=a,n.lastUpdate=Date.now(),n.updateDelay=null,Ri(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function sa(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),Ge[e]===t&&delete Ge[e],t.options.onCompromised(n)}function QE(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:ua,onCompromised:r=>{throw r},...t},t.retries=t.retries||0,t.retries=typeof t.retries=="number"?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),da(e,t,(r,i)=>{if(r)return n(r);let o=YE.operation(t.retries);o.attempt(()=>{aa(i,t,(s,a,u)=>{if(o.retry(s))return;if(s)return n(o.mainError());let l=Ge[i]={lockfilePath:Vn(i,t),mtime:a,mtimePrecision:u,options:t,lastUpdate:Date.now()};Ri(i,t),n(null,c=>{if(l.released)return c&&c(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));fg(i,{...t,realpath:!1},c)})})})})}function fg(e,t,n){t={fs:ua,realpath:!0,...t},da(e,t,(r,i)=>{if(r)return n(r);let o=Ge[i];if(!o)return n(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));o.updateTimeout&&clearTimeout(o.updateTimeout),o.released=!0,delete Ge[i],lg(i,t,n)})}function ZE(e,t,n){t={stale:1e4,realpath:!0,fs:ua,...t},t.stale=Math.max(t.stale||0,2e3),da(e,t,(r,i)=>{if(r)return n(r);t.fs.stat(Vn(i,t),(o,s)=>o?o.code==="ENOENT"?n(null,!1):n(o):n(null,!cg(s,t)))})}function XE(){return Ge}KE(()=>{for(let e in Ge){let t=Ge[e].options;try{t.fs.rmdirSync(Vn(e,t))}catch{}}});Gn.exports.lock=QE;Gn.exports.unlock=fg;Gn.exports.check=ZE;Gn.exports.getLocks=XE});var mg=re((t_,gg)=>{"use strict";var ev=na();function tv(e){let t=["mkdir","realpath","stat","rmdir","utimes"],n={...e};return t.forEach(r=>{n[r]=(...i)=>{let o=i.pop(),s;try{s=e[`${r}Sync`](...i)}catch(a){return o(a)}o(null,s)}}),n}function nv(e){return(...t)=>new Promise((n,r)=>{t.push((i,o)=>{i?r(i):n(o)}),e(...t)})}function rv(e){return(...t)=>{let n,r;if(t.push((i,o)=>{n=i,r=o}),e(...t),n)throw n;return r}}function iv(e){if(e={...e},e.fs=tv(e.fs||ev),typeof e.retries=="number"&&e.retries>0||e.retries&&typeof e.retries.retries=="number"&&e.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return e}gg.exports={toPromise:nv,toSync:rv,toSyncOptions:iv}});var yg=re((n_,nt)=>{"use strict";var on=pg(),{toPromise:ki,toSync:Ai,toSyncOptions:ca}=mg();async function hg(e,t){let n=await ki(on.lock)(e,t);return ki(n)}function ov(e,t){let n=Ai(on.lock)(e,ca(t));return Ai(n)}function sv(e,t){return ki(on.unlock)(e,t)}function av(e,t){return Ai(on.unlock)(e,ca(t))}function uv(e,t){return ki(on.check)(e,t)}function dv(e,t){return Ai(on.check)(e,ca(t))}nt.exports=hg;nt.exports.lock=hg;nt.exports.unlock=sv;nt.exports.lockSync=ov;nt.exports.unlockSync=av;nt.exports.check=uv;nt.exports.checkSync=dv});import{existsSync as la,mkdirSync as cv,readFileSync as lv,renameSync as fv,unlinkSync as pv,writeFileSync as gv}from"node:fs";import{join as mv}from"node:path";function Hn(e){if(!e||e.type!=="dashboard")return!1;let t=e.cursor;if(!t||typeof t!="object")return!1;let n=t;return typeof n.page=="number"&&typeof n.pageSize=="number"&&typeof n.total=="number"}function yv(e,t){let n=typeof t=="number"?`p${t}`:t;return mv(e,`${n}.registry.json`)}function wv(){return{counters:{},refs:{},payloads:{}}}function sn(e){if(!la(e))return wv();try{let t=JSON.parse(lv(e,"utf8"));if(!m(t)||t.counters!==void 0&&!m(t.counters)||m(t.counters)&&Object.values(t.counters).some(n=>typeof n!="number"||!Number.isInteger(n)||n<0)||t.refs!==void 0&&!m(t.refs)||m(t.refs)&&Object.values(t.refs).some(n=>!m(n)||typeof n.type!="string")||t.payloads!==void 0&&!m(t.payloads)||t.payloadOrder!==void 0&&(!Array.isArray(t.payloadOrder)||t.payloadOrder.some(n=>typeof n!="string")))throw new Error("invalid registry state shape");return{counters:t.counters??{},refs:t.refs??{},payloads:t.payloads??{},payloadOrder:Array.isArray(t.payloadOrder)?t.payloadOrder:void 0}}catch(t){throw new T("persistence",`Registry state is corrupt: ${e} \u2014 ${t instanceof Error?t.message:String(t)}`,{path:e})}}function bv(e,t){let n=`${e}.${process.pid}.tmp`;gv(n,JSON.stringify(t),"utf8"),fv(n,e)}function kg(e,t){let n=t.startsWith("@")?t.slice(1):t;return n===e||n.startsWith(`${e}.`)?n:`${e}.${n}`}function ma(e,t){return t===e||t.startsWith(`${e}.`)}function wg(e,t){return t.startsWith(`${e}.`)}function bg(e,t){return Object.fromEntries(Object.entries(e).filter(([n])=>ma(t,n)))}function Rg(e,t,n){e.payloads[t]=n;let r=e.payloadOrder??Object.keys(e.payloads),i=r.indexOf(t);for(i!==-1&&r.splice(i,1),r.push(t);r.length>hv;){let o=r.shift();delete e.payloads[o];for(let s of Object.keys(e.refs))ma(o,s)&&delete e.refs[s]}e.payloadOrder=r}function Rv(e,t){delete e.payloads[t],e.payloadOrder&&(e.payloadOrder=e.payloadOrder.filter(n=>n!==t))}function kv(e,t,n,r){return{namespace:e,root:t,refs:n,payload:r,childRef(i){return kg(e,i)}}}function Ag(e,t){la(e)||cv(e,{recursive:!0});let n=yv(e,t);function r(){for(let a=0;a<30;a++)try{(0,Bn.lockSync)(n,{realpath:!1});return}catch{if(a===29)throw new Error("Failed to acquire registry lock");let u=Math.min(20*Math.pow(2,a),500),l=Math.floor(Math.random()*u*.5),c=Date.now()+u+l;for(;Date.now()<c;);}}function i(s){r();try{let a=sn(n),u=s(a);return bv(n,a),u}finally{(0,Bn.unlockSync)(n,{realpath:!1})}}function o(s){return i(a=>{let u=(a.counters[s]??0)+1;return a.counters[s]=u,`${s}${u}`})}return{claimSearch(){return o("s")},claimWidget(){return o("w")},claimDashboard(){return o("d")},claimContentMarkets(){return o("cm")},claimContentResearch(){return o("cr")},setRefs(s,a){i(u=>{u.refs={...u.refs,...a}})},resolveRef(s){return sn(n).refs[s]},getAllRefs(){return sn(n).refs},setPayload(s,a){i(u=>{Rg(u,s,a)})},getPayload(s){return sn(n).payloads[s]},storeArtifact(s){if(!s.namespace)throw new Error("storeArtifact requires a non-empty namespace");return i(a=>{let l={...Object.fromEntries(Object.entries(s.refs??{}).map(([c,d])=>[kg(s.namespace,c),d])),[s.namespace]:s.root};for(let c of Object.keys(a.refs))ma(s.namespace,c)&&delete a.refs[c];for(let c of Object.keys(a.payloads))wg(s.namespace,c)&&Rv(a,c);return a.refs={...a.refs,...l},Rg(a,s.namespace,s.payload),kv(s.namespace,s.root,bg(a.refs,s.namespace),a.payloads[s.namespace])})},getArtifact(s){let a=sn(n),u=a.refs[s];if(u)return{namespace:s,root:u,refs:bg(a.refs,s),payload:a.payloads[s]}},findRefs(s,a){return Object.entries(sn(n).refs).filter(([u,l])=>wg(s,u)&&(!a||a(l,u)))},updateRefCursor(s,a){return i(u=>{let l=u.refs[s];if(!l)throw new fa(s);if(!Hn(l))throw new pa(s);let c=a(l.cursor);return u.refs[s]={...l,cursor:c},c})},clean(){r();try{la(n)&&pv(n)}finally{(0,Bn.unlockSync)(n,{realpath:!1})}}}}var Bn,ga,fa,pa,hv,Si=v(()=>{"use strict";Bn=Ba(yg(),1);ge();Q();ga=e=>`error: @${e} is not a paginated list. Use \`next\` on @d{N}.`,fa=class extends Error{constructor(n){super(`ref @${n} not found`);this.refName=n;this.name="UnknownRefError"}},pa=class extends Error{constructor(n){super(ga(n));this.refName=n;this.name="NotPaginatedError"}};hv=50});function Av(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||e===null?String(e):e===void 0?"undefined":JSON.stringify(e)}function Sv(e){let t=Cv(e);if(t.length===0)return;let n=e,r=0;for(let i of t){let o=i+r,s=Sg(n,o);if(s<0)return;let a=n.slice(s+1,o).trim();if(!a)continue;let u=Ev(a);if(u<0)continue;let l=a.slice(u).replace(/;?\s*$/,"");if(!l||l.startsWith("return ")||l.startsWith("return("))continue;let c=`${a.slice(0,u)}return (${l})`,d=`${n.slice(0,s+1)} ${c} ${n.slice(o)}`;r+=d.length-n.length,n=d}return n===e?void 0:n}function Cv(e){let t=[],n=e.length-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0||e[n]!=="}")return t;for(;n>=0&&e[n]==="}";){t.unshift(n);let r=Sg(e,n);if(r<0)break;let i=r-1;for(;i>=0&&/\s/.test(e[i]);)i--;if(i>=3&&e.slice(i-3,i+1)==="else"){for(i-=4;i>=0&&/\s/.test(e[i]);)i--;if(i>=0&&e[i]==="}"){n=i;continue}}if(i>=0&&e[i]===")"){let o=1,s=i-1;for(;s>=0&&o>0;)e[s]===")"?o++:e[s]==="("&&o--,s--;let a=s;for(;a>=0&&/\s/.test(e[a]);)a--;if(a>=1&&e.slice(a-1,a+1)==="if")break}break}return t.length>=2?t:[]}function Sg(e,t){let n=0;for(let r=t;r>=0;r--){let i=e[r];if(i==='"'||i==="'"||i==="`"){for(r--;r>=0&&e[r]!==i;)e[r]==="\\"&&r>0&&r--,r--;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return r}return-1}function Ev(e){let t=e.replace(/;\s*$/,"");if(!t)return-1;let n=0,r=0;for(let o=t.length-1;o>=0;o--){let s=t[o];if(s==='"'||s==="'"||s==="`"){for(o--;o>=0&&t[o]!==s;)t[o]==="\\"&&o>0&&o--,o--;continue}if(s==="}"?n++:s==="{"?n--:s===")"?r++:s==="("&&r--,n===0&&r===0&&(s===";"||s==="}")){let a=o+1,u=t.slice(a).trim();if(u)return e.indexOf(u,a>0?a-1:0)}}let i=t.trim();return i?e.indexOf(i):-1}function ha(e){{let n=`return (${e});`;try{return new Function("data",n),n}catch{}}let t=xv(e);if(t>=0){let n=e.slice(t+1).trim().replace(/;$/,"");if(n){let r=`${e.slice(0,t+1)};
117
+ return (${n});`;try{return new Function("data",r),r}catch{}}else{let r=Sv(e);if(r)try{return new Function("data",r),r}catch{}}}{let n=vv(e);if(n.length>=2){n[n.length-1]=`return (${n[n.length-1]})`;let r=n.join(`;
118
+ `);try{return new Function("data",r),r}catch{}}}return e}function ya(e){let t=ha(e);return new Function("data",t)}function vv(e){let t=[],n=0,r=0,i=0,o=0;for(let a=0;a<e.length;a++){let u=e[a];if(u==="(")r++;else if(u===")")r--;else if(u==="[")i++;else if(u==="]")i--;else if(u==="{")n++;else if(u==="}")n--;else if(u===";"&&n===0&&r===0&&i===0){let l=e.slice(o,a).trim();l&&t.push(l),o=a+1}if(u==='"'||u==="'"||u==="`"){let l=u;for(a++;a<e.length&&e[a]!==l;)e[a]==="\\"&&a++,a++}}let s=e.slice(o).trim();return s&&t.push(s),t}function xv(e){let t=0,n=0,r=0,i=-1;for(let o=0;o<e.length;o++){let s=e[o];if(s==="("?n++:s===")"?n--:s==="["?r++:s==="]"?r--:s==="{"&&n===0&&r===0?t++:s==="}"&&n===0&&r===0&&(t--,t===0&&(i=o)),s==='"'||s==="'"||s==="`"){let a=s;for(o++;o<e.length&&e[o]!==a;)e[o]==="\\"&&o++,o++}}return i}function Iv(e,t,n){if(e===void 0)return;let r;if(n==="rows")r=m(e)&&Array.isArray(e.rows)?e.rows:[];else if(m(e)&&(e.widget!==void 0||e.params!==void 0)){let o={};e.widget!==void 0&&(o.widget=e.widget),e.params!==void 0&&(o.params=e.params),r=o}else r=e;let i=ya(t);return Av(i(r))}function Dv(e,t,n={}){let r=m(e)?e:{},i=Array.isArray(r.rows)?r.rows:[],o=m(r.rowModel)?r.rowModel:{},s=Array.isArray(r.traces)?r.traces:[],a=m(r.layout)?r.layout:{},u=Array.isArray(r.labels)?r.labels.map(String):void 0,l=ut(s,a,{seriesLabels:u}),c,d;n.head!==void 0&&n.tail!==void 0?(c=n.head,d=n.tail):n.head!==void 0?(c=n.head,d=0):n.tail!==void 0?(c=0,d=n.tail):(c=Number.MAX_SAFE_INTEGER,d=0);let f=Array.isArray(o.columns)?o.columns.map(String):[],p=typeof o.summary=="string"||f.length>0,g=i.length>0&&(p||!l)?{summary:typeof o.summary=="string"?o.summary:`table, ${i.length} rows`,columns:f.length>0?f:Object.keys(i[0]??{}),rows:i}:void 0,h=g?Tn(g,{firstN:c,lastN:d}):l?Tn(l,{firstN:c,lastN:d}):"";return(t?h.replace(/\[@data,/g,`[@${t}.data,`):h)||"No data available."}function Cg(){return{buildEvalFunctionBody:ha,buildEvalFunction:ya,evalStoredPayload:Iv,expandPayload:Dv}}var wa=v(()=>{"use strict";An();os();Z()});function Eg(e){return m(e)&&Array.isArray(e.sections)&&e.sections.length>0&&Array.isArray(e.widgets)&&typeof e.total=="number"}function vg(e,t,n){let r=e.resolveRef(t);return Hn(r)?r.cursor:{page:1,pageSize:n.pageSize??20,total:n.total}}function Tv(e){let t=e.sectionIndex;return typeof t=="number"&&Number.isInteger(t)&&t>0?t:void 0}function xg(e,t,n){if(typeof n.dashboardId=="string"&&n.dashboardId.length>0)return n.dashboardId;if(n.type==="dashboard"&&typeof n.id=="string"&&n.id.length>0)return n.id;let r=e.resolveRef(t);if(m(r)&&r.type==="dashboard"&&typeof r.id=="string"&&r.id.length>0)return r.id}function Pv(e,t,n){if(n.type==="dashboard"){let s=e.getPayload(t);return Eg(s)?ft(s,{ns:t,cursor:vg(e,t,s),store:le(e,t),dashboardId:xg(e,t,n),expandSections:"all"}):void 0}if(n.type!=="section")return;let r=typeof n.dashboardRef=="string"&&n.dashboardRef.length>0?n.dashboardRef:ke(t),i=Tv(n);if(!i)return;let o=e.getPayload(r);if(Eg(o))return ft(o,{ns:r,cursor:vg(e,r,o),store:le(e,r),dashboardId:xg(e,r,n),expandSections:[i]})}function _v(e,t,n){if(t.type!=="article"||!Gt(n))return;let r=typeof t.id=="string"?t.id:void 0;if(r){let i=n.results.find(o=>String(o.id??"")===r);if(i)return i}}function Ig(e,t){let n=Cg();e.command("expand").argument("<ref>","data ref").description("Expand rows from the current widget data").option("--head <count>","show only the earliest rows").option("--tail <count>","show only the latest rows").action(async(r,i)=>{try{let o=t.getRegistry(),{cleanRef:s,ref:a}=Xe(o,r);if(a){if(a.type==="facet"){let f=Fp(o,s,a);f.ok?P(t.write,f.text):k(t.write,f.text);return}let d=Pv(o,s,a);if(d!==void 0){P(t.write,d);return}}if(!a||a.type!=="data"){k(t.write,ws(o,s));return}let u=je(i.head);if(i.head!==void 0&&u===void 0){process.exitCode=1,P(t.write,"Error: --head must be a positive integer");return}let l=je(i.tail);if(i.tail!==void 0&&l===void 0){process.exitCode=1,P(t.write,"Error: --tail must be a positive integer");return}let c=ke(s);P(t.write,n.expandPayload(o.getPayload(c),c,{head:u,tail:l}))}catch(o){k(t.write,_("expand",o))}}),e.command("eval").argument("<ref>","stored ref").argument("<code>","JavaScript code").description("Evaluate JS against stored data for an explicit ref").action(async(r,i)=>{try{let o=t.getRegistry(),{cleanRef:s,ref:a}=Xe(o,r);if(!a){k(t.write,s.endsWith(".data")?ws(o,s):Jt(o,s));return}let u=ke(s),l=a.type==="data"?"rows":"full",c=o.getPayload(u),f=(a.type==="article"?o.getPayload(s):void 0)??_v(s,a,c)??c,p=n.evalStoredPayload(f,i,l);if(p!==void 0){P(t.write,p);return}let g=t.getBrowserTransport(),h=await g.run("eval",["(typeof globalThis !== 'undefined' && typeof globalThis.__mq !== 'undefined') || (typeof window !== 'undefined' && typeof window.__mq !== 'undefined')"]),y=n.buildEvalFunctionBody(i),w=h.trim()==="true"?`(() => { const data = globalThis.__mq ?? (typeof window !== 'undefined' ? window.__mq : undefined); ${y}; })()`:i;$(t.write,await g.run("eval",["--stdin"],{stdin:w}))}catch(o){k(t.write,Wn(o)?o.message:`eval failed: ${o instanceof Error?o.message:String(o)}`)}})}var Dg=v(()=>{"use strict";Qs();On();Si();Vt();Z();wa();wa()});function $v(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.field=="string"&&e.value!==void 0&&e.value!==null&&e.value!==""}function Ov(e){let t=e.data.result;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.id=="string"?String(t.id):void 0}async function Mv(e,t){let n=typeof e.id=="string"?e.id:"",r=typeof e.underlyingChartId=="string"?e.underlyingChartId:"",i=Array.isArray(e.configurationParameters)?e.configurationParameters.filter($v):[];if(!(!n||!r))return await t.getRouter().execute({surface:"marketview",action:"widget-configure",input:{id:n,underlyingChartId:r,parameters:i}})}async function Wv(e,t,n){let r=n.getRegistry(),i=fe(r,e);if(!i.ok){k(n.write,i.message);return}let{cleanRef:o,ref:s}=i;if(s.type==="widget"){let a,u=s.configurationId?String(s.configurationId):void 0;if(!u){let d=await Mv(s,n);if(d){if(d.status!=="ok"){k(n.write,d.errors[0]??`Error: failed to configure widget ${String(s.id??"")}`);return}let f=Ov(d);if(!f){k(n.write,`Error: failed to configure widget ${String(s.id??"")}`);return}u=f}}let l=o.split(".")[0],c=r.resolveRef(l);!u&&(c?.type==="asset"||c?.type==="dashboard")&&c.contextId?a=String(c.contextId):!u&&c?.type==="asset"&&c.id&&(a=String(c.id)),s.contextField&&c?.type==="search"&&c.assetId&&(a=String(c.assetId)),await n.renderWidgetTab(String(s.id??""),{configId:u,contextId:a,label:`widget ${String(s.id??"")}`,json:t.json,editableDashboards:!0});return}if(s.type==="dashboard"){await n.renderDashboardTab(String(s.id??""),!!t.json);return}if(s.type==="asset"){await n.renderDashboardTab(String(s.id??""),!!t.json);return}if(s.type==="article"){await n.renderContentArticle(o,!!t.json);return}k(n.write,`Error: @${o} cannot be loaded`)}function Tg(e,t){e.command("load").argument("<ref>","stored ref to load").option("--json").description("Load a widget/dashboard/asset from a stored ref").action(async(n,r)=>{await Wv(n,r,t)})}var Pg=v(()=>{"use strict";Z()});async function Lv(e,t){let n=t.getBrowserTransport(),r=fe(t.getRegistry(),e);if(!r.ok){k(t.write,r.message);return}let{cleanRef:i,ref:o}=r;if(o.type!=="link"&&o.type!=="article"){k(t.write,`Error: ref @${i} not found or not a link`);return}let s=ys(o);if(!s){k(t.write,`Error: ref @${i} not found or not a link`);return}try{await t.syncBrowserAuthState(n,s),await n.run("open",[s]),P(t.write,`Opened ${s}`)}catch(a){k(t.write,_("open",a))}}function _g(e,t){e.command("open").argument("<ref>","link ref").description("Open a stored link ref in the browser").action(async n=>{await Lv(n,t)})}var $g=v(()=>{"use strict";Z()});function ka(e){return String(e.title??"")}function ne(e){return String(e.id??"")}function Ug(e){return Array.isArray(e.children)?e.children.filter(t=>m(t)):[]}function vi(e,t){return Ug(e).filter(n=>n.entity_id===t||n.entityId===t||n.id===t||m(n.data)&&n.data.id===t)}function Ei(e,t){return vi(e,t)[0]}function qv(e,t,n){let r=Ei(e,t);if(!r)return e;let i=typeof r.id=="string"&&r.id.length>0?r.id:void 0;return{...e,children:Ug(e).map(o=>o===r?{...n,...i?{id:i}:{}}:o)}}function Be(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function an(e){let t=Be(e.configurationId);if(t)return t;if(m(e.configuration)){let n=Be(e.configuration.id);if(n)return n}if(m(e.data)){let n=Be(e.data.configurationId);if(n)return n;if(m(e.data.configuration)){let r=Be(e.data.configuration.id);if(r)return r}}return""}function ba(e){if(e){for(let t of[e.id,e.uuid,e.childId])if(typeof t=="string"&&t.length>0)return t}}function Og(e,t,n,r){let i=Mg(e.id,"dashboard id"),o=n.trim().length>0?{configurationId:n}:{};return r?(typeof r.rank=="number"&&Number.isFinite(r.rank)&&(o.rank=r.rank),{dashboardId:i,widgetId:t,configurationId:n,child:{entityId:Fv(r),type:Mg(r.type,"restore child type"),parameters:Nv(r),extras:o}}):{dashboardId:i,widgetId:t,configurationId:n,child:{entityId:t,type:"Widget",parameters:[],extras:o}}}function Fv(e){let t=Be(e.entity_id)??Be(e.entityId);if(t)return t;if(m(e.data)){let n=Be(e.data.id);if(n)return n}throw new Error("Unsupported dashboard add-widget restore child shape: missing entity id")}function Nv(e){if(e.parameters===void 0||e.parameters===null)return[];if(Array.isArray(e.parameters))return e.parameters;throw new Error("Unsupported dashboard add-widget restore child shape: parameters is not an array")}function Mg(e,t){let n=Be(e);if(n)return n;throw new Error(`Unsupported dashboard add-widget input shape: missing ${t}`)}function jg(e,t,n){let r=vi(e,t);return r.find(i=>an(i)===n)??r[0]}function Uv(e){return Array.isArray(e.dashboards)?e.dashboards.filter(t=>m(t)&&typeof t.id=="string"&&typeof t.title=="string"):[]}function jv(e,t){let n=t.trim().toLowerCase();return e.filter(r=>ka(r).trim().toLowerCase()===n)}async function Wg(e,t){let n=await e.execute({surface:"marketview",action:"dashboard-find-by-title",input:{title:t}});return n.status!=="ok"?{ok:!1,error:`Error: could not verify existing dashboards titled "${t}" (${n.errors[0]??"lookup failed"}); refusing to create a possible duplicate`}:{ok:!0,matches:Array.isArray(n.data.result)?n.data.result.filter(r=>m(r)):[]}}function Lg(e){let t=ne(e),n=ka(e);return t?`${n} (${t})`:n}function Vv(e,t){if(!t.id||!t.title)return e;let n=Array.isArray(e.dashboards)?e.dashboards:[];return n.filter(o=>m(o)).some(o=>ne(o)===t.id)?e:{...e,dashboards:[...n,{id:t.id,title:t.title}]}}function Ra(e,t){let n=m(e)?e:{},r=String(n.id??t.id??""),i=String(n.title??t.title??r),o=typeof n.link=="string"&&n.link.length>0?n.link:`https://marquee.gs.com/s/marketview/dashboards/${r}`;return{id:r,title:i,link:o}}function qg(e){return m(e)?Be(e.configurationId):void 0}async function Fg(e,t,n){let r=vi(t,n).map(i=>ba(i)).filter(i=>typeof i=="string");for(let i of r){let o=await e.execute({surface:"marketview",action:"dashboard-remove-widget",input:{dashboardId:ne(t),childId:i}});if(o.status!=="ok")return o.errors[0]??`Error: failed to roll back added widget ${n} on dashboard ${ne(t)}`}}async function zn(e,t,n){let r=ne(t),i=await e.execute({surface:"marketview",action:"dashboard-raw",input:{id:r}});if(i.status!=="ok")return{error:i.errors[0]??n??`Error: failed to fetch dashboard ${r} for update`};let o=i.data.result;return m(o)?{dashboard:o}:{error:`Error: dashboard ${r} did not return update metadata`}}async function Ng(e,t,n,r,i){let o=await zn(e,t);if(o.error||!o.dashboard)return{error:o.error??`Error: failed to fetch dashboard ${ne(t)} after updating widget configuration`};let s=ba(i);if(s?vi(o.dashboard,n).find(c=>ba(c)===s):void 0)return{error:`Error: widget ${n} replacement on dashboard ${ne(o.dashboard)} left the original child ${s} in place`};let u=jg(o.dashboard,n,r);if(!u)return{dashboard:o.dashboard,error:`Error: widget ${n} was not found on dashboard ${ne(o.dashboard)} after updating configuration`};let l=an(u);return l!==r?{dashboard:o.dashboard,error:`Error: widget ${n} configuration on dashboard ${ne(o.dashboard)} did not persist (expected ${r}, found ${l||"none"})`}:{dashboard:o.dashboard}}async function Ci(e,t,n,r,i){let o=Ei(n,r);if(o){let f=jg(n,r,i);if(f&&an(f)===i){P(e.write,`Warning: widget ${r} is already on dashboard ${ka(n)}; skipped.`);return}if(an(o)!==i){let p=await t.execute({surface:"marketview",action:"dashboard-update-widget-configuration",input:{dashboard:n,widgetId:r,configurationId:i}});if(p.status!=="ok"){k(e.write,p.errors[0]??`Error: failed to update widget configuration on dashboard ${ne(n)}`);return}let g=qg(p.data.result)??i,h=await Ng(t,n,r,g,o);if(h.error||!h.dashboard){if(!h.dashboard){k(e.write,h.error??`Error: failed to verify widget configuration on dashboard ${ne(n)}`);return}let w=an(o),R=Ei(h.dashboard,r)?await t.execute({surface:"marketview",action:"dashboard-update-widget-configuration",input:{dashboard:qv(h.dashboard,r,o),widgetId:r,configurationId:w}}):await t.execute({surface:"marketview",action:"dashboard-add-widget",input:Og(h.dashboard,r,w,o)});if(R.status!=="ok"){k(e.write,R.errors[0]??`Error: failed to restore widget configuration on dashboard ${ne(n)}`);return}k(e.write,h.error??`Error: failed to verify widget configuration on dashboard ${ne(n)}`);return}let y=Ra(p.data.result,n);P(e.write,`Updated widget ${r} configuration on dashboard ${y.title}: ${y.link}`);return}}let s=await t.execute({surface:"marketview",action:"dashboard-add-widget",input:Og(n,r,i)});if(s.status!=="ok"){k(e.write,s.errors[0]??`Error: failed to add widget to dashboard ${ne(n)}`);return}let a=`Error: failed to fetch dashboard ${ne(n)} after adding widget`,u=await zn(t,n,a);if(u.error||!u.dashboard){k(e.write,u.error??a);return}let l=Ei(u.dashboard,r),c=l?an(l):"";if(!l||c!==i){if(!l){k(e.write,`Error: widget ${r} configuration on dashboard ${ne(u.dashboard)} did not persist (expected ${i}, found none)`);return}let f=await t.execute({surface:"marketview",action:"dashboard-update-widget-configuration",input:{dashboard:u.dashboard,widgetId:r,configurationId:i}});if(f.status!=="ok"){let h=await Fg(t,u.dashboard,r);if(h){k(e.write,h);return}k(e.write,f.errors[0]??`Error: failed to update widget configuration on dashboard ${ne(u.dashboard)}`);return}let p=qg(f.data.result)??i,g=await Ng(t,u.dashboard,r,p);if(g.error||!g.dashboard){if(g.dashboard){let h=await Fg(t,g.dashboard,r);if(h){k(e.write,h);return}}k(e.write,g.error??`Error: failed to verify widget configuration on dashboard ${ne(u.dashboard)}`);return}}let d=Ra(s.data.result,n);P(e.write,`Added widget ${r} to dashboard ${d.title}: ${d.link}`)}function Vg(e,t){e.command("add").argument("<ref>","dashboard-add ref").argument("<name>","dashboard title").description("Add a widget to an existing or new dashboard").action(async(n,r)=>{let i=t.getRegistry(),o=t.getRouter(),s=fe(i,n);if(!s.ok){k(t.write,s.message);return}let{cleanRef:a,ref:u}=s;if(u.type!=="dash"){k(t.write,`Error: @${a} is not a dashboard-add ref`);return}let l=typeof u.entityId=="string"&&u.entityId.length>0?u.entityId:void 0,c=typeof u.configurationId=="string"&&u.configurationId.length>0?u.configurationId:void 0,d=Array.isArray(u.dashboards),f=Uv(u);if(!l||!c||!d){k(t.write,`Error: @${a} is missing dashboard-add metadata`);return}let p=me(r);if(/^MD[A-Z0-9]+$/i.test(p)){let w=await o.execute({surface:"marketview",action:"dashboard-raw",input:{id:p}});if(w.status!=="ok"){let R=m(w.data)?w.data.httpStatus:void 0;k(t.write,R===404?`Error: dashboard ${p} not found`:w.errors[0]??`Error: dashboard ${p} not found`);return}let b=m(w.data.result)?w.data.result:void 0;if(!b){k(t.write,`Error: dashboard ${p} not found`);return}await Ci(t,o,b,l,c);return}let g=jv(f,r);if(g.length===0){let w=await Wg(o,r);if(!w.ok){k(t.write,w.error);return}let b=w.matches;if(b.length===1){let C=await zn(o,b[0]);if(C.error||!C.dashboard){k(t.write,C.error??`Error: failed to fetch dashboard ${ne(b[0])} for update`);return}await Ci(t,o,C.dashboard,l,c);return}if(b.length>1){k(t.write,`Error: dashboard "${r}" matched multiple dashboards: ${b.map(Lg).join(", ")}`);return}let R=await o.execute({surface:"marketview",action:"dashboard-create-with-widget",input:{title:r,widgetId:l,configurationId:c}});if(R.status!=="ok"){if(R.data.httpStatus===409){let C=await Wg(o,r);if(!C.ok){k(t.write,C.error);return}let x=C.matches;if(x.length===1){let E=await zn(o,x[0]);if(E.error||!E.dashboard){k(t.write,E.error??`Error: failed to fetch dashboard ${ne(x[0])} for update`);return}await Ci(t,o,E.dashboard,l,c);return}}k(t.write,R.errors[0]??`Error: failed to create dashboard ${r}`);return}let S=Ra(R.data.result,{title:r});i.setRefs(a,{[a]:Vv(u,{id:S.id,title:S.title})}),P(t.write,`Created dashboard ${S.title} with widget ${l}: ${S.link}`);return}if(g.length>1){k(t.write,`Error: dashboard "${r}" matched multiple dashboards: ${g.map(Lg).join(", ")}`);return}let h=g[0],y=await zn(o,h);if(y.error||!y.dashboard){k(t.write,y.error??`Error: failed to fetch dashboard ${ne(h)} for update`);return}await Ci(t,o,y.dashboard,l,c)})}var Gg=v(()=>{"use strict";Z()});function Yn(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function xi(e){return`https://marquee.gs.com/s/marketview/dashboards/${e}`}function Kg(e){if(e.type!=="widget")return;let t=Yn(e.dashboardId),n=Yn(e.childId);if(!(!t||!n))return{dashboardId:t,childId:n,title:typeof e.title=="string"?e.title:""}}function Bg(e){if(e.type!=="section")return;let t=Yn(e.dashboardId),n=Yn(e.sectionId);if(!(!t||!n))return{dashboardId:t,sectionId:n}}function Gv(e){if(e.type==="dashboard")return Yn(e.id)}function Bv(e){for(let t of[e.id,e.uuid,e.childId])if(typeof t=="string"&&t.length>0)return t}function Ti(e){for(let t of[e.id,e.uuid,e.sectionId])if(typeof t=="string"&&t.length>0)return t}function Hg(e){return Array.isArray(e.children)?e.children.filter(m).map(Bv).filter(t=>t!==void 0):[]}function Jn(e,t){return Array.isArray(e.sections)?e.sections.filter(m).find(n=>Ti(n)===t):void 0}function bt(e){return e&&Array.isArray(e.children)?e.children.filter(t=>typeof t=="string"&&t.length>0):[]}function Aa(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Ii(e,t){return typeof e.title=="string"&&e.title.length>0?e.title:t}async function zv(){process.env.NODE_ENV!=="test"&&await new Promise(e=>{setTimeout(e,Hv)})}async function Sa(e,t){let n=await e.execute({surface:"marketview",action:"dashboard-raw",input:{id:t}});return n.status!=="ok"||!m(n.data.result)?{ok:!1}:{ok:!0,dashboard:n.data.result}}async function Di(e,t,n){let r={ok:!1};for(let i=0;i<zg;i+=1){if(r=await Sa(e,t),r.ok&&n(r.dashboard))return r;i<zg-1&&await zv()}return r}function Jg(e,t,n){let r=[];for(let i of t){let o=fe(e,i);if(!o.ok)return{ok:!1,message:o.message};let s=Kg(o.ref);if(!s)return{ok:!1,message:`Error: @${o.cleanRef} is not a dashboard tile ref`};if(s.dashboardId!==n)return{ok:!1,message:`Error: @${o.cleanRef} belongs to a different dashboard`};r.push(s.childId)}return{ok:!0,childIds:r}}function Jv(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Yg(e,t,n,r,i=new Set){if(!Array.isArray(e.sections))return;let o=e.sections.filter(m),s=t?o.find(a=>Ti(a)===t):void 0;return s||o.find(a=>a.title===n&&Aa(bt(a),r)&&!i.has(Qg(a)))}function Qg(e){let t=Ti(e);return t?`id:${t}`:`shape:${String(e.title??"")}\0${bt(e).join("\0")}`}function Yv(e){return Array.isArray(e.sections)?new Set(e.sections.filter(m).map(Qg)):new Set}function Zg(e,t){e.command("remove").argument("<ref>","dashboard tile ref (@d{N}.w{M})").description("Remove a widget tile from a dashboard").action(async r=>{let i=t.getRegistry(),o=t.getRouter(),s=fe(i,r);if(!s.ok){k(t.write,s.message);return}let a=Kg(s.ref);if(!a){k(t.write,`Error: @${s.cleanRef} is not a removable tile (load a dashboard with \`marketview dashboard <id>\` first)`);return}let u=await o.execute({surface:"marketview",action:"dashboard-remove-widget",input:{dashboardId:a.dashboardId,childId:a.childId}});if(u.status!=="ok"){k(t.write,u.errors[0]??`Error: failed to remove tile from dashboard ${a.dashboardId}`);return}let l=a.title?`"${a.title}" `:"",c=await Di(o,a.dashboardId,d=>Array.isArray(d.children)&&!Hg(d).includes(a.childId));if(c.ok){if(!Array.isArray(c.dashboard.children)){k(t.write,`Error: dashboard ${a.dashboardId} children could not be verified after removing tile`);return}let d=Hg(c.dashboard);if(d.includes(a.childId)){k(t.write,`Error: tile still present on dashboard ${a.dashboardId} after removal`);return}let f=d.length;P(t.write,`Removed ${l}from ${Ii(c.dashboard,a.dashboardId)} (${f} widgets remain): ${xi(a.dashboardId)}`);return}k(t.write,`Error: failed to verify tile removal on dashboard ${a.dashboardId}`)}),e.command("reorder").argument("<sectionRef>","section ref (@d{N}.s{M})").argument("<tileRefs...>","tile refs in the desired order").description("Reorder the tiles within a dashboard section").action(async(r,i)=>{let o=t.getRegistry(),s=t.getRouter(),a=fe(o,r);if(!a.ok){k(t.write,a.message);return}let u=Bg(a.ref);if(!u){k(t.write,`Error: @${a.cleanRef} is not a dashboard section ref`);return}let l=Jg(o,i,u.dashboardId);if(!l.ok){k(t.write,l.message);return}let c=await Sa(s,u.dashboardId);if(!c.ok){k(t.write,`Error: failed to fetch dashboard ${u.dashboardId} for reorder`);return}let d=bt(Jn(c.dashboard,u.sectionId));if(d.length===0){k(t.write,`Error: section ${u.sectionId} was not found on dashboard ${u.dashboardId}`);return}if(!Jv(d,l.childIds)){k(t.write,`Error: reorder must list exactly the ${d.length} tiles already in the section (got ${l.childIds.length})`);return}let f=await s.execute({surface:"marketview",action:"dashboard-set-section",input:{dashboardId:u.dashboardId,sectionId:u.sectionId,childIds:l.childIds}});if(f.status!=="ok"){k(t.write,f.errors[0]??`Error: failed to reorder section on dashboard ${u.dashboardId}`);return}let p=await Di(s,u.dashboardId,g=>bt(Jn(g,u.sectionId)).join(",")===l.childIds.join(","));if(p.ok){let g=bt(Jn(p.dashboard,u.sectionId));if(g.join(",")!==l.childIds.join(",")){k(t.write,`Error: section order on dashboard ${u.dashboardId} did not persist`);return}P(t.write,`Reordered ${g.length} tiles in ${Ii(p.dashboard,u.dashboardId)}: ${xi(u.dashboardId)}`);return}k(t.write,`Error: failed to verify section reorder on dashboard ${u.dashboardId}`)});let n=e.command("section").description("Manage dashboard sections");n.command("add").argument("<ref>","dashboard ref (@d{N})").argument("<title>","section title").argument("[tileRefs...]","tile refs to place in the new section").description("Create a section on a dashboard").action(async(r,i,o=[])=>{let s=t.getRegistry(),a=t.getRouter(),u=fe(s,r);if(!u.ok){k(t.write,u.message);return}let l=Gv(u.ref);if(!l){k(t.write,`Error: @${u.cleanRef} is not a dashboard ref`);return}if(o.length===0){k(t.write,"Error: section add requires at least one dashboard tile ref");return}let c=Jg(s,o,l);if(!c.ok){k(t.write,c.message);return}let d=await Sa(a,l);if(!d.ok){k(t.write,`Error: failed to fetch dashboard ${l} before creating section "${i}"`);return}let f=Yv(d.dashboard),p=await a.execute({surface:"marketview",action:"dashboard-create-section",input:{dashboardId:l,title:i,childIds:c.childIds}});if(p.status!=="ok"){k(t.write,p.errors[0]??`Error: failed to create section on dashboard ${l}`);return}let g=m(p.data.result)?Ti(p.data.result):void 0,h=await Di(a,l,b=>{let R=Yg(b,g,i,c.childIds,f);return R!==void 0&&Aa(bt(R),c.childIds)});if(h.ok){let b=h.dashboard.sections;if(!Array.isArray(b)){k(t.write,`Error: dashboard ${l} sections could not be verified after creating section "${i}"`);return}let R=Yg(h.dashboard,g,i,c.childIds,f);if(!R){k(t.write,`Error: created section "${i}" was not found on dashboard ${l} after creation`);return}let S=bt(R);if(!Aa(S,c.childIds)){k(t.write,`Error: created section "${i}" on dashboard ${l} has ${S.length} tiles, expected ${c.childIds.length}`);return}}if(!h.ok){k(t.write,`Error: failed to verify section creation on dashboard ${l}`);return}let y=c.childIds.length>0?` with ${c.childIds.length} tiles`:"",w=Ii(h.dashboard,l);P(t.write,`Created section "${i}"${y} on ${w}: ${xi(l)}`)}),n.command("rm").argument("<ref>","section ref (@d{N}.s{M})").description("Delete a section from a dashboard").action(async r=>{let i=t.getRegistry(),o=t.getRouter(),s=fe(i,r);if(!s.ok){k(t.write,s.message);return}let a=Bg(s.ref);if(!a){k(t.write,`Error: @${s.cleanRef} is not a dashboard section ref`);return}let u=await o.execute({surface:"marketview",action:"dashboard-delete-section",input:{dashboardId:a.dashboardId,sectionId:a.sectionId}});if(u.status!=="ok"){k(t.write,u.errors[0]??`Error: failed to delete section on dashboard ${a.dashboardId}`);return}let l=await Di(o,a.dashboardId,d=>Array.isArray(d.sections)&&!Jn(d,a.sectionId));if(!l.ok){k(t.write,`Error: failed to verify section deletion on dashboard ${a.dashboardId}`);return}if(!Array.isArray(l.dashboard.sections)){k(t.write,`Error: dashboard ${a.dashboardId} sections could not be verified after deleting section ${a.sectionId}`);return}if(Jn(l.dashboard,a.sectionId)){k(t.write,`Error: section ${a.sectionId} still present on dashboard ${a.dashboardId} after deletion`);return}let c=Ii(l.dashboard,a.dashboardId);P(t.write,`Deleted section from ${c}: ${xi(a.dashboardId)}`)})}var zg,Hv,Xg=v(()=>{"use strict";Z();zg=10,Hv=1e3});import{randomUUID as Kv}from"node:crypto";function Ea(e){return e.__paginationRollbackOwner}function Qv(e){return e.__paginationRollbackCursor}function va(e){let t=e.__paginationStaleRollbackOwners;return new Set(Array.isArray(t)?t.filter(n=>typeof n=="string"):[])}function Kn(e){let{__paginationRollbackOwner:t,__paginationRollbackCursor:n,__paginationStaleRollbackOwners:r,...i}=e;return i}function Zv(e,t){let n=va(e);return n.add(t),{...e,__paginationStaleRollbackOwners:[...n]}}function Xv(e,t){let n=e,r=new Set;for(;;){let i=Ea(n);if(!i||!t.has(i))return n;let o=Qv(n);if(!o||r.has(i))return Kn(n);r.add(i),n=o}}function ex(e,t){return e.page===t.page&&e.pageSize===t.pageSize&&e.total===t.total}function em(e,t,n,r,i){return ft(r,{ns:t,...typeof e.id=="string"&&e.id.length>0?{dashboardId:e.id}:{},cursor:n,store:le(i,t)})}function tx(e){return e.includes(" ... end of list.")?e:`${e}
119
+ ... end of list.`}function nx(e){return e.errors[0]??`error: ${e.surface}.${e.action} failed`}async function Ca(e,t,n){let{write:r,registry:i}=n,o=zt(e),s=i.resolveRef(o),a=Ze(s)?s:void 0;if(!a){P(r,Jt(i,o,{prefix:"error"})),process.exitCode=1;return}if(a.type!=="dashboard"){P(r,ga(o)),process.exitCode=1;return}if(!Hn(a)){P(r,`error: ref @${o} has no cursor. Re-run \`marquee marketview dashboard <ID>\` to establish pagination.`),process.exitCode=1;return}let u=a.cursor,l=Pn(u.total,u.pageSize,u.page);if(t==="prev"&&u.page<=1){P(r,"Already on first page.");return}if(t==="next"&&u.page>=l.lastPage){let b=i.getPayload(o);if(!b){P(r,`error: ref @${o} payload not cached. Re-run \`marquee marketview dashboard <ID>\`.`),process.exitCode=1;return}r(`${tx(em(a,o,u,b,i))}
120
+ `);return}let c=typeof t=="number"?Math.min(Math.max(1,t),l.lastPage):t==="next"?Math.min(u.page+1,l.lastPage):Math.max(u.page-1,1),d=i.getPayload(o);if(!d){P(r,`error: ref @${o} payload not cached. Re-run \`marquee marketview dashboard <ID>\`.`),process.exitCode=1;return}let p={...u},g=Kv(),h;try{h=i.updateRefCursor(o,b=>(p={...b},{...Kn(b),page:c,__paginationRollbackOwner:g,__paginationRollbackCursor:p}))}catch(b){P(r,b instanceof Error?b.message:String(b)),process.exitCode=1;return}let y=Kn(h),w=await Qf(d,y,n.router);if(w){i.updateRefCursor(o,b=>{let R=Ea(b);if(R!==g)return R?Zv(b,g):b;let S=va(b);return va(p).forEach(C=>S.add(C)),ex(b,y)?Xv(p,S):Kn(b)}),P(r,nx(w)),process.exitCode=1;return}i.updateRefCursor(o,b=>Ea(b)===g?Kn(b):b),i.setPayload(o,d),r(`${em(a,o,y,d,i)}
121
+ `)}function tm(e,t){e.command("next").argument("<ref>","paginated dashboard ref (@d{N})").description("Advance a paginated list to the next page").action(async n=>{await Ca(n,"next",{write:t.write,registry:t.getRegistry(),router:t.getRouter()})}),e.command("prev").argument("<ref>","paginated dashboard ref (@d{N})").description("Go back to the previous page of a paginated list").action(async n=>{await Ca(n,"prev",{write:t.write,registry:t.getRegistry(),router:t.getRouter()})}),e.command("page").argument("<ref>","paginated dashboard ref (@d{N})").argument("<number>","page number to jump to").description("Jump to a specific page of a paginated list").action(async(n,r)=>{let i=parseInt(r,10);if(!Number.isFinite(i)||i<1){t.write(`error: page number must be a positive integer
122
+ `),process.exitCode=1;return}await Ca(n,i,{write:t.write,registry:t.getRegistry(),router:t.getRouter()})})}var nm=v(()=>{"use strict";Si();as();Vt();Z();ui()});function rm(e){return e instanceof Pi}function Zn(e){if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e)){let t=e.map(n=>Zn(n));return t.every(n=>n!==void 0)?t:void 0}if(m(e)){let t=Object.entries(e).map(([n,r])=>[n,Zn(r)]);if(t.every(([,n])=>n!==void 0))return Object.fromEntries(t)}}function Qn(e,t){let n=m(e.optionRawValues)?e.optionRawValues:void 0;if(n&&Object.prototype.hasOwnProperty.call(n,t))return Ee(Zn(n[t]))}function rx(e,t){let n=[...Array.isArray(e.options)?e.options.map(String):[],...Array.isArray(e.allOptions)?e.allOptions.map(String):[]];if(n.length!==0)return new Set(n).has(t)?t:void 0}function xa(e){return e==="Asset"||e==="Enum"||e==="EnumList"||e==="AssetList"||e==="Portfolio"}function im(e){let t=String(e.paramType??""),n=Zn(e.value),r=Zn(e.rawValue);if(t==="Date"&&n!==void 0){let i=Qn(e,String(n));if(i!==void 0)return i}if(t==="Date"&&r!==void 0)return Ee(r);if((t==="EnumList"||t==="AssetList")&&Array.isArray(n)){let i=Array.isArray(r)?r:void 0;return n.map((o,s)=>{if(typeof o!="string")return o;let a=Qn(e,o);return a!==void 0?a:i&&Object.prototype.hasOwnProperty.call(i,s)?Ee(i[s]):o})}if(n!==void 0&&xa(t)){let i=Qn(e,String(n));if(i!==void 0)return i}if(r!==void 0&&xa(t))return Ee(r);if(t==="Asset"&&typeof n=="string"&&n.startsWith("MA")||t==="Portfolio"&&typeof n=="string"&&n.startsWith("MP"))return n;if(!xa(t))return n}function ix(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function om(e,t){if(e==="EnumList"||e==="AssetList")return ix(t);if(e==="Integer"){let n=Number(t);if(Number.isFinite(n))return n}return t}function ox(e){let t=m(e.data)&&typeof e.data.error=="string"?e.data.error:void 0;return e.errors[0]??t??`Error: ${e.surface}.${e.action} failed`}function sx(e){return[m(e.data)&&typeof e.data.error=="string"?e.data.error:void 0,...e.errors].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r==="no asset found"||r==="asset not found"||r==="not found")}function _i(e){throw new Pi(ox(e))}async function sm(e,t){if(t.startsWith("MA"))return t;let n=await e.execute({surface:"asset",action:"resolve",input:{query:t}});if(n.status!=="ok"){if(sx(n))return t;_i(n)}if(!m(n.data.result))return t;let r=n.data.result.id;return typeof r=="string"&&r.startsWith("MA")?r:t}function ax(e){return Array.isArray(e.cgGroupIds)?e.cgGroupIds.map(String).filter(Boolean):[]}function am(e){let t=m(e.data.result)?e.data.result:e.data;return(m(t)&&Array.isArray(t.matches)?t.matches:[]).map(r=>{if(!m(r))return;let i=typeof r.id=="string"?r.id:"",o=typeof r.display=="string"?r.display:"";return i&&o?{id:i,display:o}:void 0}).filter(r=>r!==void 0)}async function ux(e,t,n){let r=ax(t);if(r.length===0)return;let i=await e.execute({surface:"marketview",action:"filter-constituents",input:{groupIds:r.join(","),query:n.trim(),limit:30}});i.status!=="ok"&&_i(i);let o=n.trim().toLowerCase(),s=am(i).filter(a=>a.id===n||a.display.toLowerCase()===o);return s.length===1?s[0].id:void 0}function dx(e){return Array.isArray(e.rawOptions)?e.rawOptions.map(String).filter(Boolean):[]}async function cx(e,t,n){let r=dx(t);if(r.length===0)return;let i=await e.execute({surface:"marketview",action:"asset-options",input:{ids:r,query:n.trim(),limit:30}});i.status!=="ok"&&_i(i);let o=n.trim().toLowerCase(),s=am(i).filter(a=>a.id===n||a.display.toLowerCase()===o);return s.length===1?s[0].id:void 0}async function Ia(e,t,n){let r=String(t.paramType??"");if(Array.isArray(n)){let o=[];for(let s of n){if(typeof s!="string")return;let a=Qn(t,s);if(a!==void 0){o.push(a);continue}if(r==="AssetList"&&s.startsWith("MA")){o.push(s);continue}if(r==="EnumList"){o.push(s);continue}return}return o}if(typeof n=="number")return n;if(typeof n!="string")return;let i=Qn(t,n);if(i!==void 0)return i;if(r==="Asset"){let s=rx(t,n)??n,a=await sm(e,s);if(a!==s||s.startsWith("MA"))return a;let u=await cx(e,t,n);return u!==void 0?u:ux(e,t,n)}if(r==="Portfolio")return n.startsWith("MP")?n:void 0;if(!(r==="Enum"||r==="EnumList"||r==="AssetList"))return n}function lx(e){return m(e)&&typeof e.label=="string"&&e.rawValue!==void 0}function fx(e){return m(e)&&typeof e.field=="string"&&(e.type===void 0||typeof e.type=="string")&&(e.options===void 0||Array.isArray(e.options)&&e.options.every(t=>lx(t)))}async function um(e,t,n,r){let i={id:t,includeData:!1};n&&(i.context=n);let o=await e.execute({surface:"marketview",action:"widget-load",input:i});o.status!=="ok"&&_i(o);let s=o.data.result,u=(Array.isArray(s)?s:m(s)&&Array.isArray(s.params)?s.params:[]).filter(c=>fx(c));async function l(c,d){if(typeof d!="string")return d;if(typeof c?.rawDefault=="string"&&c.default!==void 0&&String(c.default)===d)return c.rawDefault;if(!c?.options||c.options.length===0)return d;let f=c.options.find(h=>h.rawValue===d||h.label===d);if(f)return f.rawValue;let p=d.toLowerCase(),g=c.options.find(h=>h.label.toLowerCase()===p);return g?g.rawValue:c?.type==="Asset"?sm(e,d):d}return Promise.all(r.map(async c=>{let d=u.find(f=>f.field===c.field);return d?Array.isArray(c.value)?{...c,value:await Promise.all(c.value.map(f=>l(d,f)))}:{...c,value:await l(d,c.value)}:c}))}var Pi,dm=v(()=>{"use strict";Z();pn();pn();Pi=class extends Error{name="ParamResolutionError"}});function un(e){let t=zt(e),n=t.lastIndexOf(".");return n>0?t.slice(0,n):t}function px(e){return m(e.optionRawValues)&&Object.keys(e.optionRawValues).length>0||Array.isArray(e.options)&&e.options.length>0||Array.isArray(e.allOptions)&&e.allOptions.length>0||Array.isArray(e.rawOptions)&&e.rawOptions.length>0||Array.isArray(e.cgGroupIds)&&e.cgGroupIds.length>0}function Pa(e,t){let n=un(t),r=Object.entries(e.getAllRefs()).filter(([i,o])=>i.startsWith(`${n}.`)&&Ze(o)&&o.type==="param").map(([i])=>`@${i}`).sort();return r.length===0?`Error: ref @${t} not found`:`Error: ref @${t} not found. Available params for @${n}: ${r.join(", ")}`}function Ta(e,t){if(t.includes(e))return e;let n=e.toLowerCase(),r=t.filter(i=>i.toLowerCase()===n);return r.length===1?r[0]:e}function gx(e,t){return typeof e=="string"?Ta(e,t):Array.isArray(e)?e.map(n=>Ta(n,t)):e}function Da(e,t){return rm(t)?(k(e.write,t.message),!0):!1}function _a(e,t){let n=e.resolveRef(t);return m(n)&&n.type==="search"&&n.surface==="content"?n:void 0}function mx(e,t){let n=e.getPayload(t);return m(n)&&Array.isArray(n.facets)?n.facets.filter(m):[]}function $i(e){return Array.isArray(e.appliedFilters)?e.appliedFilters.filter(m):[]}function Oi(e){return Array.isArray(e.appliedFacets)?e.appliedFacets.filter(m):[]}function hx(e){return typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?e.limit:10}function Rt(e){return{query:String(e.query??""),limit:hx(e),sort:e.sort==="relevance"?"relevance":"time",page:typeof e.page=="number"&&Number.isFinite(e.page)?e.page:1,...typeof e.from=="string"&&e.from.length>0?{from:e.from}:{},...typeof e.to=="string"&&e.to.length>0?{to:e.to}:{},...$i(e).length>0?{select:$i(e)}:{},...Oi(e).length>0?{appliedFacets:Oi(e)}:{}}}function yx(e){let t={...e,sort:"time",page:1};return delete t.appliedFilters,delete t.appliedFacets,delete t.from,delete t.to,t}function lm(e,t,n,r){let i=mx(e,t).find(l=>l.field===n),o=Array.isArray(i?.values)?i.values.filter(m):[],s=r.trim().toLowerCase(),a=o.find(l=>typeof l.name=="string"&&l.name.trim().toLowerCase()===s);if(!a)return{ok:!1,error:`Error: "${r}" is not a valid option for @${t}.${n}. Try \`marquee filter @${t}.${n} "${r}"\`.`};let u=typeof a.guid=="string"?a.guid:"";return u?{ok:!0,selection:{field:n,guid:u,name:r}}:{ok:!1,error:`Error: @${t}.${n} cached value "${r}" has no GUID. Re-run \`marquee content search <query>\`.`}}function wx(e,t,n,r,i){let o=[],s=[];for(let u of $i(e)){if(u.field!==r||typeof u.value!="string"){o.push(u);continue}let l=lm(t,n,r,u.value);l.ok?s.push(l.selection):o.push(u)}let a=new Map;for(let u of[...s,...Oi(e),i]){let l=`${String(u.field??"")}\0${String(u.guid??"")}`;l!=="\0"&&a.set(l,u)}return{appliedFilters:o,appliedFacets:[...a.values()]}}async function bx(e,t,n,r){let i=ke(e),o=_a(r.getRegistry(),i);if(!o||typeof o.query!="string"){k(r.write,`Error: @${e} content search state not cached. Re-run \`marquee content search <query>\`.`);return}let s=typeof t.field=="string"?t.field:"",a=lm(r.getRegistry(),i,s,n);if(!a.ok){k(r.write,a.error);return}let u=wx(o,r.getRegistry(),i,s,a.selection),l=Rt({...o,page:1,appliedFilters:u.appliedFilters,appliedFacets:u.appliedFacets});await r.renderContentSearch(i,l)}async function Rx(e,t,n,r,i,o){let s=String(t.paramType??"");if(!r.has(s)){k(o.write,i(e,s));return}let a=ke(e),u=_a(o.getRegistry(),a);if(!u||typeof u.query!="string"){k(o.write,`Error: @${e} content search state not cached. Re-run \`marquee content search <query>\`.`);return}let l=typeof t.control=="string"?t.control:"";if(l==="sort"){let c=Array.isArray(t.options)?t.options.map(String):[],d=Ta(n,c);if(!c.includes(d)){k(o.write,`Error: "${n}" is not a valid option for @${e}. Available: ${c.join(", ")}`);return}await o.renderContentSearch(a,Rt({...u,sort:d,page:1}));return}if(l==="from"||l==="to"){await o.renderContentSearch(a,Rt({...u,[l]:n,page:1}));return}k(o.write,`Error: @${e} is not a content search control ref`)}async function kx(e,t,n){let r=n.getRegistry(),{cleanRef:i,ref:o}=Xe(r,e);if(!o){k(n.write,Pa(r,i));return}let s=o.type==="search"&&o.surface==="content"?i:ke(i),a=_a(r,s);if(!a||typeof a.query!="string"){k(n.write,`Error: @${i} content search state not cached. Re-run \`marquee content search <query>\`.`);return}if(o.type==="search"&&o.surface==="content"){await n.renderContentSearch(s,Rt(yx(a)));return}if(o.type==="facet"){let u=typeof o.field=="string"?o.field:"",l=t?.trim().toLowerCase(),c=Oi(a).filter(p=>p.field!==u?!0:l?String(p.name??"").trim().toLowerCase()!==l:!1),d=$i(a).filter(p=>p.field!==u?!0:l?String(p.value??"").trim().toLowerCase()!==l:!1),f={...a,page:1,appliedFacets:c,appliedFilters:d};c.length===0&&delete f.appliedFacets,d.length===0&&delete f.appliedFilters,await n.renderContentSearch(s,Rt(f));return}if(o.type==="search-control"){let u=typeof o.control=="string"?o.control:"",l={...a,page:1};if(u==="from"||u==="to"){delete l[u],await n.renderContentSearch(s,Rt(l));return}if(u==="sort"){l.sort="time",await n.renderContentSearch(s,Rt(l));return}}k(n.write,`Error: @${i} cannot be unselected`)}async function fm(e,t,n,r){if(typeof r.chartId=="string"&&r.chartId.length>0)return r.chartId;let i=un(n),o=t.resolveRef(i);if(m(o)&&typeof o.chartId=="string"&&o.chartId.length>0)return o.chartId;if(!i.includes("."))return;let s=typeof r.widgetId=="string"?r.widgetId:void 0;if(!s)return;let a={id:s};typeof r.configurationId=="string"&&r.configurationId.length>0&&(a.context=r.configurationId);let u=await e.execute({surface:"marketview",action:"widget-load",input:a});if(u.status!=="ok")return;let l=m(u.data.result)?u.data.result:{},c=typeof l.chartId=="string"&&l.chartId.length>0?l.chartId:void 0;if(!c)return;let d={[n]:{...r,chartId:c}};return Ze(o)&&(d[i]={...o,chartId:c}),t.setRefs(i,d),c}async function cm(e,t,n,r,i){let o=i.getRouter(),s=i.getRegistry(),{cleanRef:a,ref:u}=Xe(s,e);if(!u){k(i.write,Pa(s,a));return}if(u.type==="facet"){if(!n.has("Enum")){k(i.write,`Error: @${a} is a content facet. Use 'select' instead.`);return}await bx(a,u,t,i);return}if(u.type==="search-control"){await Rx(a,u,t,n,r,i);return}if(u.type!=="param"){k(i.write,`Error: @${a} is not a parameter ref`);return}let l=String(u.paramType??"");if(!n.has(l)){k(i.write,r(a,l));return}let c=om(l,t),d=c,f=String(u.widgetId??""),p=new Set(["Asset","String","Date","Integer"]),g=Array.isArray(u.options)?u.options.map(String):[];g.length>0&&!p.has(l)&&(c=gx(c,g),d=c);let h=Array.isArray(c)?c:[String(c)];if(g.length>0&&!p.has(l)&&h.some(A=>!g.includes(A))){k(i.write,`Error: "${t}" is not a valid option for @${a}. Available: ${g.join(", ")}`);return}if(l==="Asset"&&px(u)){try{d=await Ia(o,u,c)}catch(A){if(Da(i,A))return;throw A}if(d===void 0){k(i.write,`Error: "${t}" is not a valid asset for @${a}. Try \`marquee filter @${a} "${t}"\` to search available options.`);return}}let y=u.configurationId?String(u.configurationId):void 0,w=String(u.field??""),b=un(a);await fm(o,s,a,u);let R=[];for(let[,A]of s.findRefs(b,I=>I.type==="param"&&String(I.widgetId??"")===f&&String(I.field??"")!==w))R.push({field:String(A.field??""),value:A.value,ref:A});R.push({field:w,value:d,ref:u,target:!0});let S=[],C=[];for(let A of R){let I;try{I=A.target?await Ia(o,A.ref,A.value):im(A.ref)}catch(M){if(Da(i,M))return;throw M}let O={field:A.field,value:I===void 0?A.value:I,...A.target&&l==="Asset"?{displayValue:c}:{}};S.push(O),I===void 0&&C.push(O)}let x;try{x=C.length>0?await um(o,f,y,C):[]}catch(A){if(Da(i,A))return;throw A}let E=new Map(x.map(A=>[A.field,A])),D=S.map(A=>E.get(A.field)??A).map(A=>({...A,...A.field===w&&l==="Asset"?{displayValue:c}:{}}));await i.renderWidgetTab(String(u.widgetId??""),{configId:y,paramOverrides:D,assetLabel:l==="Asset"&&!t.startsWith("MA")?t:void 0,label:`widget ${f}`,mutationFallbackRef:`${un(a)}.link`,editableDashboards:!0})}async function Ax(e,t){let n=t.getRouter(),r=t.getRegistry(),{cleanRef:i,ref:o}=Xe(r,e);if(!o||o.type!=="param"){k(t.write,o?`Error: ref @${i} not found or not a parameter`:Pa(r,i));return}if(String(o.paramType??"")!=="Boolean"){k(t.write,`Error: @${i} is ${String(o.paramType??"unknown")}. Use 'fill' or 'select' instead.`);return}let s=o.value===!0||o.value==="true",a=String(o.widgetId??""),u=String(o.field??""),l=un(i);await fm(n,r,i,o);let c=[];for(let[,d]of r.findRefs(l,f=>f.type==="param"&&String(f.widgetId??"")===a&&String(f.field??"")!==u))c.push({field:String(d.field??""),value:d.rawValue??d.value??""});c.push({field:u,value:!s}),await t.renderWidgetTab(a,{configId:o.configurationId?String(o.configurationId):void 0,paramOverrides:c,label:`widget ${a}`,mutationFallbackRef:`${un(i)}.link`,editableDashboards:!0})}function pm(e,t){e.command("select").argument("<ref>","parameter ref").argument("<value>","option value").description("Select an enum-like parameter").action(async(n,r)=>{await cm(n,r,new Set(["Enum","EnumList","AssetList"]),(i,o)=>`Error: @${i} is ${o}, not Enum/EnumList. Use 'fill' instead.`,t)}),e.command("fill").passThroughOptions().argument("<ref>","parameter ref").argument("<value>","field value").description("Fill an asset/string/date parameter").action(async(n,r)=>{await cm(n,r,new Set(["Asset","String","Date","Integer","Portfolio"]),(i,o)=>`Error: @${i} is ${o}. Use 'select' for Enum or 'check' for Boolean.`,t)}),e.command("check").argument("<ref>","boolean parameter ref").description("Toggle a boolean parameter").action(async n=>{await Ax(n,t)}),e.command("unselect").argument("<ref>","content search ref").argument("[value]","optional selected value to clear").description("Clear a selected ref value").action(async(n,r)=>{await kx(n,r,t)})}var gm=v(()=>{"use strict";Z();dm()});function Sx(e){e.status==="error"&&(process.exitCode=1)}function mm(e,t){Sx(t),e(`${oe(t)}
123
+ `)}function $a(e,t){let n=e.refIndex;return typeof n=="number"&&Number.isInteger(n)&&n>0?n:t}function bm(e,t){let n=Array.isArray(e.allOptions)?e.allOptions.map(String):[],r=Array.isArray(e.options)?e.options.map(String):[],i=n.length>0?n:r,o=t.trim().toLowerCase();return i.filter(s=>s.toLowerCase().includes(o))}function hm(e){return e.map(t=>{if(!m(t))return;let n=String(t.display??"");if(n)return{id:String(t.id??""),display:n}}).filter(t=>t!==void 0)}function ym(e){let t=new Map;for(let n of e)t.set(n.display,(t.get(n.display)??0)+1);return e.map(n=>n.id&&(t.get(n.display)??0)>1?`${n.display} (${n.id})`:n.display)}function Rm(e){return m(e)&&typeof e.id=="string"&&typeof e.title=="string"}function Ex(e){return Array.isArray(e)?e.filter(Rm):[]}function vx(e){return m(e)&&Array.isArray(e.widgets)&&typeof e.total=="number"}function wm(e,t){for(let n=0;n<t;n++)if(!Rm(e.widgets[n]))return n;return t}function xx(e,t,n){let r=typeof e.pageSize=="number"&&e.pageSize>0?e.pageSize:50,i=new Set((Array.isArray(e.loadedPages)?e.loadedPages:[]).filter(a=>Number.isInteger(a)&&a>0)),o=Math.floor(t/r)+1,s=Math.floor(Math.max(t,t+Math.max(n-1,0))/r)+1;for(let a=o;a<=s;a++)i.add(a);e.loadedPages=[...i].sort((a,u)=>a-u)}async function Ix(e,t){if(!e.contextId||!qn(e.contextType))return;let n=typeof e.total=="number"&&Number.isFinite(e.total)?e.total:e.widgets.length,r=wm(e,n);for(;r<n;){let i=Math.min(Cx,n-r),o=await t.getRouter().execute({surface:"marketview",action:"asset",input:{assetId:e.contextId,limit:i,offset:r,includeFilters:!1}});if(o.status!=="ok")return o;let s=m(o.data.result)?o.data.result:{},a=Ex(s.widgets);if(a.forEach((u,l)=>{e.widgets[r+l]=u}),xx(e,r,a.length),a.length===0)break;r=wm(e,n)}}function Dx(e){return e.errors[0]??`error: ${e.surface}.${e.action} failed`}async function Tx(e,t,n,r){let i=r.getRegistry(),o=i.getPayload(e);if(t==="asset"&&vx(o)){let p=await Ix(o,r);if(p){P(r.write,Dx(p)),process.exitCode=1;return}i.setPayload(e,o)}let s=m(o)&&Array.isArray(o.widgets)?o.widgets:[];if(s.length===0){P(r.write,`No widget matches for "${n}" in @${e}`);return}let a=n.toLowerCase(),u=s.map((p,g)=>({widget:p,index:g})).filter(({widget:p})=>{if(!m(p))return!1;let g=typeof p.title=="string"?p.title:"",h=typeof p.id=="string"?p.id:"";return g.toLowerCase().includes(a)||h.toLowerCase().includes(a)}).sort((p,g)=>{let h=m(p.widget)?$a(p.widget,p.index+1):p.index+1,y=m(g.widget)?$a(g.widget,g.index+1):g.index+1;return h-y||p.index-g.index});if(u.length===0){P(r.write,`No widget matches for "${n}" in @${e}`);return}let l=u.slice(0,30),c={},d=[`- @${e} widget matches for "${n}":`];for(let{widget:p,index:g}of l){if(!m(p)||typeof p.title!="string"||typeof p.id!="string")continue;let h=`${e}.w${$a(p,g+1)}`,y=typeof p.configurationId=="string"?p.configurationId:"";c[h]={type:"widget",id:p.id,configurationId:y},c[`${h}.link`]={type:"link",url:`https://marquee.gs.com/s/marketview/widget/${p.id}?config=${y}`};let w=p.titleResolved===!0;t==="asset"&&!w?d.push(` - widget @${h} [load] (cached title matched "${p.title}"; load for asset-context title)`):d.push(` - widget "${p.title}" [@${h}, load]`)}let f=u.length-l.length;f>0&&d.push(` ... ${f} more`),i.setRefs(e,c),P(r.write,d.join(`
124
+ `))}function Px(e,t){let n=Array.isArray(e.allOptions)?e.allOptions.map(String):[];if(n.length===0)return;let r=t.trim().toLowerCase(),i=n.filter(o=>o.toLowerCase().includes(r)).slice(0,30);return i.length>0?i:void 0}async function _x(e,t,n,r){let i=Array.isArray(t.cgGroupIds)?t.cgGroupIds.map(String):[],o=Array.isArray(t.rawOptions)?t.rawOptions.map(String):[],s=[],a=Px(t,n);if(a)s=a;else if(i.length>0)try{let u=await r.getRouter().execute({surface:"marketview",action:"filter-constituents",input:{groupIds:i.join(","),query:n.trim(),limit:30}});if(u.status!=="ok"){mm(r.write,u);return}let l=m(u.data.result)?u.data.result:u.data,c=m(l)&&Array.isArray(l.matches)?l.matches:[];s=ym(hm(c))}catch(u){P(r.write,_("filter",u));return}else if(o.length>0)try{let u=await r.getRouter().execute({surface:"marketview",action:"asset-options",input:{ids:o,query:n.trim(),limit:30}});if(u.status!=="ok"){mm(r.write,u);return}let l=m(u.data.result)?u.data.result:u.data,c=m(l)&&Array.isArray(l.matches)?l.matches:[];s=ym(hm(c))}catch(u){P(r.write,_("filter",u));return}else s=bm(t,n).slice(0,30);s.length===0?P(r.write,`No matches for "${n}" in @${e}`):P(r.write,`- @${e} matches for "${n}":
125
+ ${s.join(", ")}`)}function $x(e,t,n,r){let i=bm(t,n).slice(0,30);i.length===0?P(r.write,`No matches for "${n}" in @${e}`):P(r.write,`- @${e} matches for "${n}":
126
+ ${i.join(", ")}`)}async function Ox(e,t,n){let r=n.getRegistry(),i=fe(r,e);if(!i.ok){k(n.write,i.message);return}let{cleanRef:o,ref:s}=i;if(s.type==="asset"||s.type==="dashboard"){let u=r.getPayload(o),l=s.type==="dashboard"&&m(u)&&qn(u.contextType)?"asset":s.type;await Tx(o,l,t,n);return}if(s.type==="facet"){let u=qp(r,o,s,t);u.ok?P(n.write,u.text):k(n.write,u.text);return}if(s.type!=="param"){k(n.write,`Error: @${o} is not a parameter ref`);return}let a=String(s.paramType??"");if(a==="Asset"||a==="AssetList"){await _x(o,s,t,n);return}if(a==="Enum"||a==="EnumList"||a==="Portfolio"){$x(o,s,t,n);return}k(n.write,`Error: @${o} is ${a}. Only Asset/AssetList/Enum/EnumList/Portfolio params can be filtered.`)}function km(e,t){e.command("filter").argument("<ref>","parameter ref").argument("<query>","search text").description("Search available options for a parameter").action(async(n,r)=>{await Ox(n,r,t)})}var Cx,Am=v(()=>{"use strict";Me();Qs();Z();ui();Cx=250});function Mx(){return process.stdin.isTTY?Promise.reject(new Error("--stdin requires piped input")):new Promise((e,t)=>{let n="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>{n+=r}),process.stdin.on("end",()=>e(n)),process.stdin.on("error",t),process.stdin.isPaused()&&process.stdin.resume()})}function Wx(e,t){return e===void 0&&t.error("missing required argument 'code'"),[e]}function Lx(e){try{let t=new URL(e.trim());return t.hostname==="marquee.gs.com"&&/^\/s\/marketview\/widget\//.test(t.pathname)}catch{return!1}}function qx(e){try{return new URL(e.trim()).hostname==="marquee.gs.com"}catch{return!1}}function Oa(e,t,n,r){P(e,`${t}: unavailable: ${_(n,r)}`)}function Fx(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n&&!n.startsWith("-")&&qx(n))return n}}function Nx(e){try{let t=new URL(e.trim());return t.hostname==="idfs.gs.com"&&/^\/signin/.test(t.pathname)}catch{return!1}}function Ux(e){let t=e.toLowerCase();return t.includes("search marquee")&&(t.includes("frequently used")||t.includes("quick access"))}function jx(e){let t=e.toLowerCase();return t.includes("widget details and comparisons")||t.includes("about this widget")||t.includes("more widgets from this author")||t.includes("continue exploring this widget")}async function Vx(e,t,n){let r=Ux(t)&&!jx(t),i="";try{i=(await e.run("get",["url"])).trim()}catch{return}if(Nx(i)){process.exitCode=1,P(n,`Error: browser auth mismatch: browser is on the GS SSO sign-in page (${i}). REST auth may still be authenticated; run \`marquee auth login --headed\` to refresh browser auth.`);return}r&&Lx(i)&&(process.exitCode=1,P(n,`Error: browser destination mismatch: current URL is a MarketView widget route but the DOM is the Marquee home shell (${i}). Marquee did not render the requested widget.`))}function Sm(e,t){let{write:n}=t,r=e.command("browser");r.command("open").argument("[target]","Marquee ID or URL").option("--headed","Open in a visible browser window").description("Open in browser").action(async(d,f)=>{let p=t.getBrowserTransport();if(!d){try{f.headed?$(n,await p.run("open",[],{headed:!0})):$(n,await p.run("open",[])),P(n,"Opened browser.")}catch(y){k(n,_("open",y))}return}let{url:g,error:h}=t.resolveBrowserOpenTarget(d);if(!g){k(n,h??`Error: cannot open ${d}`);return}try{await t.syncBrowserAuthState(p,g),f.headed?$(n,await p.run("open",[g],{headed:!0})):$(n,await p.run("open",[g])),P(n,`Opened: ${g}`)}catch(y){k(n,_("open",y))}}),r.command("close").option("--all","close every browser session").description("Shut down browser session").action(async d=>{let f=t.getBrowserTransport();try{d.all?await f.run("close",["--all"]):await f.close(),P(n,"Browser session closed.")}catch(p){k(n,_("close",p))}}),r.command("click").argument("<ref>","element ref or selector").option("--new-tab","open in new tab").description("Click an element").action(async(d,f)=>{let p=t.getBrowserTransport();try{let g=[d];f.newTab&&g.push("--new-tab"),$(n,await p.run("click",g))}catch(g){k(n,_("click",g))}}),r.command("fill").argument("<ref>","element ref or selector").argument("<value>","text to fill").description("Clear and type text").action(async(d,f)=>{let p=t.getBrowserTransport();try{$(n,await p.run("fill",[d,f]))}catch(g){k(n,_("fill",g))}}),r.command("type").argument("<ref>","element ref or selector").argument("<value>","text to type").description("Type without clearing").action(async(d,f)=>{let p=t.getBrowserTransport();try{$(n,await p.run("type",[d,f]))}catch(g){k(n,_("type",g))}}),r.command("select").argument("<ref>","element ref or selector").argument("<options...>","option values to select").description("Select dropdown option").action(async(d,f)=>{let p=t.getBrowserTransport();try{$(n,await p.run("select",[d,...f]))}catch(g){k(n,_("select",g))}}),r.command("check").argument("<ref>","element ref or selector").description("Toggle checkbox").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("check",[d]))}catch(p){k(n,_("check",p))}}),r.command("uncheck").argument("<ref>","element ref or selector").description("Uncheck checkbox").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("uncheck",[d]))}catch(p){k(n,_("uncheck",p))}}),r.command("press").argument("<key>","key to press (Enter, Tab, etc.)").description("Press a key").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("press",[d]))}catch(p){k(n,_("press",p))}});let i=r.command("keyboard").description("Raw keyboard input without a selector");for(let d of["type","inserttext"])i.command(d).argument("<text>","text to send to the focused element").description(d==="type"?"Type text with real key events":"Insert text without key events").action(async f=>{let p=t.getBrowserTransport();try{$(n,await p.run("keyboard",[d,f]))}catch(g){k(n,_(`keyboard ${d}`,g))}});r.command("scroll").argument("[direction]","scroll direction (up, down, left, right)").argument("[amount]","scroll amount in pixels").option("-s, --selector <sel>","scroll within a specific container").description("Scroll page or container").action(async(d,f,p)=>{let g=t.getBrowserTransport();try{let h=[];d&&h.push(d),f&&h.push(f),p.selector&&h.push("--selector",p.selector),$(n,await g.run("scroll",h))}catch(h){k(n,_("scroll",h))}}),r.command("snapshot").option("--all","full accessibility tree (default: interactive only)").option("-i, --interactive","only interactive elements").option("-u, --urls","include href URLs for links").option("-c, --compact","remove empty structural elements").option("-d, --depth <n>","limit tree depth").option("--cursor","include cursor-interactive elements").option("--scope <selector>","scope to CSS selector").option("-s, --selector <selector>","scope to CSS selector").description("Show interactive element refs").action(async d=>{let f=t.getBrowserTransport();try{let p=[];(!d.all||d.interactive)&&p.push("-i"),d.urls&&p.push("--urls"),d.compact&&p.push("--compact"),d.depth&&p.push("--depth",d.depth),d.cursor&&p.push("-C"),d.scope&&p.push("-s",d.scope),d.selector&&p.push("--selector",d.selector);let g=await f.run("snapshot",p);await Vx(f,g,n),$(n,g)}catch(p){k(n,_("snapshot",p))}}),r.command("screenshot").argument("[args...]","selector and/or output file path").option("-f, --full","full page screenshot").option("--annotate","annotate with numbered element labels").option("--screenshot-dir <path>","default output directory").option("--screenshot-quality <n>","JPEG quality 0-100").option("--screenshot-format <fmt>","image format: png or jpeg").description("Take a screenshot").action(async(d=[],f)=>{let p=t.getBrowserTransport();try{let g=[...d];f.full&&g.push("--full"),f.annotate&&g.push("--annotate"),f.screenshotDir&&g.push("--screenshot-dir",f.screenshotDir),f.screenshotQuality&&g.push("--screenshot-quality",f.screenshotQuality),f.screenshotFormat&&g.push("--screenshot-format",f.screenshotFormat),$(n,await p.run("screenshot",g))}catch(g){k(n,_("screenshot",g))}}),r.command("read").argument("[url]","URL to read (omit to read the active tab DOM)").option("--raw","return raw text without preferring markdown").option("--require-md","require a markdown response").option("--llms <mode>","read the nearest llms file (index|full)").option("--outline","compact heading outline of a single page").option("--filter <text>","keep only content matching text").option("--timeout <ms>","request timeout in milliseconds").description("Fetch page as agent-readable text").action(async(d,f)=>{let p=t.getBrowserTransport();try{let g=[];d&&g.push(d),f.raw&&g.push("--raw"),f.requireMd&&g.push("--require-md"),f.llms&&g.push("--llms",f.llms),f.outline&&g.push("--outline"),f.filter&&g.push("--filter",f.filter),f.timeout&&g.push("--timeout",f.timeout),$(n,await p.run("read",g))}catch(g){k(n,_("read",g))}});let o=r.command("get").description("Get page information");o.command("text").argument("<ref>","element ref or selector").description("Get element text").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("get",["text",d]))}catch(p){k(n,_("get text",p))}}),o.command("url").description("Get current URL").action(async()=>{let d=t.getBrowserTransport();try{$(n,await d.run("get",["url"]))}catch(f){k(n,_("get url",f))}}),o.command("title").description("Get page title").action(async()=>{let d=t.getBrowserTransport();try{$(n,await d.run("get",["title"]))}catch(f){k(n,_("get title",f))}}),o.command("cdp-url").description("Get Chrome DevTools Protocol WebSocket URL").action(async()=>{let d=t.getBrowserTransport();try{$(n,await d.run("get",["cdp-url"]))}catch(f){k(n,_("get cdp-url",f))}}),r.command("eval").argument("[code]","JavaScript code to evaluate").option("-b, --base64","decode script from base64").option("--stdin","read code from stdin").description("Evaluate raw JS in browser").action(async(d,f,p)=>{let g=t.getBrowserTransport();if(f.stdin){try{let y=["--stdin"];f.base64&&y.push("--base64");let w=await g.run("eval",y,{stdin:await Mx()});$(n,w)}catch(y){if(y.message==="--stdin requires piped input"){k(n,`Error: ${y.message}`);return}k(n,_("eval",y))}return}let h=Wx(d,p);f.base64&&h.unshift("--base64");try{let y=await g.run("eval",h);$(n,y)}catch(y){k(n,_("eval",y))}}),r.command("wait").argument("[target]","element ref, selector, or milliseconds").option("--timeout <ms>","timeout in milliseconds").option("--load <strategy>","wait for network (e.g. networkidle)").option("--url <pattern>","wait for URL pattern").option("--fn <js>","wait for JS condition").option("--text <text>","wait for text to appear").option("--download [path]","wait for a download to complete").option("--state <state>","wait for selector state").description("Wait for element, network, URL, or condition").action(async(d,f)=>{let p=t.getBrowserTransport();try{let g=[];f.load?g.push("--load",f.load):f.url?g.push("--url",f.url):f.fn?g.push("--fn",f.fn):f.text?g.push("--text",f.text):f.download?(g.push("--download"),typeof f.download=="string"&&g.push(f.download)):d&&g.push(d),f.state&&g.push("--state",f.state),f.timeout&&g.push("--timeout",f.timeout),$(n,await p.run("wait",g))}catch(g){k(n,_("wait",g))}});let s=r.command("find").description("Find element by semantic locator");for(let d of["text","label","placeholder","alt","title","testid","first","last"])s.command(d).argument("<value>",`${d} to search for`).argument("[action]","action to perform (click, fill, etc.)").argument("[text...]","text for fill/type actions").option("--exact","require exact text match").description(`Find by ${d}`).action(async(f,p,g=[],h)=>{let y=t.getBrowserTransport();try{let w=[d,f,...p?[p]:[],...g];h.exact&&w.push("--exact"),$(n,await y.run("find",w))}catch(w){k(n,_("find",w))}});s.command("nth").argument("<index>","zero-based match index").argument("<selector>","selector to search for").argument("[action]","action to perform").argument("[text...]","text for fill/type actions").option("--exact","require exact text match").description("Find nth matching element").action(async(d,f,p,g=[],h)=>{let y=t.getBrowserTransport();try{let w=["nth",d,f,...p?[p]:[],...g];h.exact&&w.push("--exact"),$(n,await y.run("find",w))}catch(w){k(n,_("find",w))}}),s.command("role").argument("<role>","ARIA role").argument("[action]","action to perform").argument("[text...]","text for fill/type actions").option("--name <name>","accessible name").option("--exact","require exact text match").description("Find by ARIA role").action(async(d,f,p=[],g)=>{let h=t.getBrowserTransport();try{let y=["role",d,...f?[f]:[],...p];g.name&&y.push("--name",g.name),g.exact&&y.push("--exact"),$(n,await h.run("find",y))}catch(y){k(n,_("find",y))}}),r.command("tab").argument("[operation]","operation or tab ref").argument("[args...]","operation args").allowUnknownOption(!0).description("Manage browser tabs").action(async(d,f=[])=>{let p=t.getBrowserTransport();try{if(d==="new"){let g=Fx(f);g&&await t.syncBrowserAuthState(p,g)}$(n,await p.run("tab",d?[d,...f]:[]))}catch(g){k(n,_("tab",g))}});let a=r.command("network").description("Network interception and monitoring");a.command("requests").option("--clear","clear request log").option("--filter <pattern>","filter by URL pattern").option("--type <types>","filter by resource type (xhr,fetch,document)").option("--method <method>","filter by HTTP method").option("--status <code>","filter by status code").option("--json","output as JSON").description("List captured network requests").action(async d=>{let f=t.getBrowserTransport();try{let p=[];d.clear&&p.push("--clear"),d.filter&&p.push("--filter",d.filter),d.type&&p.push("--type",d.type),d.method&&p.push("--method",d.method),d.status&&p.push("--status",d.status),d.json&&p.push("--json"),$(n,await f.run("network",["requests",...p]))}catch(p){k(n,_("network requests",p))}}),a.command("request").argument("<requestId>","request ID to inspect").description("View full request/response detail").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("network",["request",d]))}catch(p){k(n,_("network request",p))}});let u=a.command("har").description("Record and export HAR files");u.command("start").description("Start HAR recording").action(async()=>{let d=t.getBrowserTransport();try{$(n,await d.run("network",["har","start"]))}catch(f){k(n,_("network har start",f))}}),u.command("stop").argument("[path]","output file path").description("Stop HAR recording and export").action(async d=>{let f=t.getBrowserTransport();try{let p=["har","stop"];d&&p.push(d),$(n,await f.run("network",p))}catch(p){k(n,_("network har stop",p))}}),a.command("route").argument("<url>","URL pattern to intercept").option("--abort","abort matching requests").option("--body <json>","respond with custom body").option("--resource-type <csv>","filter by resource type").description("Intercept requests matching URL pattern").action(async(d,f)=>{let p=t.getBrowserTransport();try{let g=[d];f.abort&&g.push("--abort"),f.body&&g.push("--body",f.body),f.resourceType&&g.push("--resource-type",f.resourceType),$(n,await p.run("network",["route",...g]))}catch(g){k(n,_("network route",g))}}),a.command("unroute").argument("[url]","URL pattern to remove (all if omitted)").description("Remove network route").action(async d=>{let f=t.getBrowserTransport();try{let p=d?[d]:[];$(n,await f.run("network",["unroute",...p]))}catch(p){k(n,_("network unroute",p))}}),o.command("html").argument("<ref>","element ref or selector").description("Get inner HTML of element").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("get",["html",d]))}catch(p){k(n,_("get html",p))}}),o.command("value").argument("<ref>","element ref or selector").description("Get value of input element").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("get",["value",d]))}catch(p){k(n,_("get value",p))}}),o.command("attr").argument("<ref>","element ref or selector").argument("<name>","attribute name").description("Get attribute value").action(async(d,f)=>{let p=t.getBrowserTransport();try{$(n,await p.run("get",["attr",d,f]))}catch(g){k(n,_("get attr",g))}}),o.command("count").argument("<ref>","element ref or selector").description("Count matching elements").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("get",["count",d]))}catch(p){k(n,_("get count",p))}}),o.command("box").argument("<ref>","element ref or selector").description("Get bounding box").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("get",["box",d]))}catch(p){k(n,_("get box",p))}}),o.command("styles").argument("<ref>","element ref or selector").description("Get computed styles").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("get",["styles",d]))}catch(p){k(n,_("get styles",p))}});let l=r.command("is").description("Check element state");l.command("visible").argument("<ref>","element ref or selector").description("Check if element is visible").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("is",["visible",d]))}catch(p){Oa(n,"browser is visible","is visible",p)}}),l.command("enabled").argument("<ref>","element ref or selector").description("Check if element is enabled").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("is",["enabled",d]))}catch(p){Oa(n,"browser is enabled","is enabled",p)}}),l.command("checked").argument("<ref>","element ref or selector").description("Check if checkbox/radio is checked").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("is",["checked",d]))}catch(p){Oa(n,"browser is checked","is checked",p)}}),r.command("back").description("Go back").action(async()=>{let d=t.getBrowserTransport();try{$(n,await d.run("back",[]))}catch(f){k(n,_("back",f))}}),r.command("forward").description("Go forward").action(async()=>{let d=t.getBrowserTransport();try{$(n,await d.run("forward",[]))}catch(f){k(n,_("forward",f))}}),r.command("reload").description("Reload page").action(async()=>{let d=t.getBrowserTransport();try{$(n,await d.run("reload",[]))}catch(f){k(n,_("reload",f))}}),r.command("hover").argument("<ref>","element ref or selector").description("Hover over element").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("hover",[d]))}catch(p){k(n,_("hover",p))}}),r.command("focus").argument("<ref>","element ref or selector").description("Focus element").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("focus",[d]))}catch(p){k(n,_("focus",p))}}),r.command("dblclick").argument("<ref>","element ref or selector").description("Double-click element").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("dblclick",[d]))}catch(p){k(n,_("dblclick",p))}}),r.command("drag").argument("<source>","source element ref or selector").argument("<target>","target element ref or selector").description("Drag and drop").action(async(d,f)=>{let p=t.getBrowserTransport();try{$(n,await p.run("drag",[d,f]))}catch(g){k(n,_("drag",g))}}),r.command("scrollintoview").argument("<ref>","element ref or selector").description("Scroll element into view").action(async d=>{let f=t.getBrowserTransport();try{$(n,await f.run("scrollintoview",[d]))}catch(p){k(n,_("scrollintoview",p))}});let c=r.command("diff").description("Compare page states");c.command("snapshot").option("-b, --baseline <file>","compare against saved file").option("-s, --selector <sel>","scope snapshot to selector or ref").option("-c, --compact","use compact snapshot format").option("-d, --depth <n>","limit snapshot tree depth").description("Compare DOM to last snapshot").action(async d=>{let f=t.getBrowserTransport();try{let p=["snapshot"];d.baseline&&p.push("--baseline",d.baseline),d.selector&&p.push("--selector",d.selector),d.compact&&p.push("--compact"),d.depth&&p.push("--depth",d.depth),$(n,await f.run("diff",p))}catch(p){k(n,_("diff",p))}}),c.command("screenshot").requiredOption("-b, --baseline <file>","baseline image to compare against").option("-o, --output <file>","path for the diff image").option("-t, --threshold <value>","color distance threshold").option("-s, --selector <sel>","scope screenshot to element").option("--full","full page screenshot").description("Compare screenshot to a baseline image").action(async d=>{let f=t.getBrowserTransport();try{let p=["screenshot","--baseline",d.baseline];d.output&&p.push("--output",d.output),d.threshold&&p.push("--threshold",d.threshold),d.selector&&p.push("--selector",d.selector),d.full&&p.push("--full"),$(n,await f.run("diff",p))}catch(p){k(n,_("diff",p))}}),c.command("url").argument("<url1>","first URL").argument("<url2>","second URL").option("--screenshot","also compare screenshots").option("--full","full page screenshots").option("--wait-until <strategy>","navigation wait strategy").option("-s, --selector <sel>","scope snapshots to selector or ref").option("-c, --compact","use compact snapshot format").option("-d, --depth <n>","limit snapshot tree depth").description("Compare two pages").action(async(d,f,p)=>{let g=t.getBrowserTransport();try{let h=["url",d,f];p.screenshot&&h.push("--screenshot"),p.full&&h.push("--full"),p.waitUntil&&h.push("--wait-until",p.waitUntil),p.selector&&h.push("--selector",p.selector),p.compact&&h.push("--compact"),p.depth&&h.push("--depth",p.depth),$(n,await g.run("diff",h))}catch(h){k(n,_("diff",h))}})}var Cm=v(()=>{"use strict";Z()});import{homedir as Gx}from"node:os";import{join as Ma}from"node:path";async function Em(e){if(e.getAuthStatus){let n=await e.getAuthStatus();n==="authenticated"?P(e.write,"Authenticated"):n==="relink-required"?P(e.write,"Goldman link expired. Re-link Goldman to continue."):n==="research-expired"?P(e.write,"Research session expired. Run: marquee auth login"):n==="research-unavailable"?P(e.write,"Research session unavailable. Check network and retry."):n==="auth-unavailable"?P(e.write,"Auth status unavailable. Check cookie jar and network, then retry."):P(e.write,"Not authenticated. Run: marquee auth login");return}let t=await e.isAuthenticated();P(e.write,t?"Authenticated":"Not authenticated. Run: marquee auth login")}function vm(e,t){e.command("status").description("Check authentication status").action(async()=>{await Em(t)})}function xm(e,t){let{write:n}=t,r=e.command("auth").description("Manage authentication credentials");r.command("status").description("Check authentication status").action(async()=>{await Em(t)}),r.command("save").option("--url <url>","SSO login URL","https://marquee.gs.com/s/").option("--username <user>","username").option("--password-stdin","read password from stdin").description("Store SSO credentials").action(async i=>{let o=t.getTransport();try{let s=["save","marquee","--url",i.url];i.username&&s.push("--username",i.username),i.passwordStdin&&s.push("--password-stdin"),$(n,await o.run("auth",s))}catch(s){k(n,`Error: ${_("auth save",s)}`)}}),r.command("login").option("--password-stdin","read password from stdin").description("SSO login (automated with saved credentials, manual browser fallback)").action(async i=>{try{let o=t.createAuthClient();await o.assertAgentBrowserAvailable();let s;i.passwordStdin&&(s=await new Promise((l,c)=>{let d="";process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{d+=f}),process.stdin.on("end",()=>l(d.trim())),process.stdin.on("error",c),process.stdin.isPaused()&&process.stdin.resume()}));let a;try{let{createDecipheriv:l}=await import("node:crypto"),{readFileSync:c}=await import("node:fs"),d=Ma(Gx(),".agent-browser"),f=process.env.AGENT_BROWSER_ENCRYPTION_KEY?.trim(),p=Buffer.from(f&&f.length>0?f:c(Ma(d,".encryption-key"),"utf8").trim(),"hex"),g=JSON.parse(c(Ma(d,"auth","marquee.json"),"utf8"));if(g.encrypted&&g.iv&&g.authTag&&g.data){let h=l("aes-256-gcm",p,Buffer.from(g.iv,"base64"));h.setAuthTag(Buffer.from(g.authTag,"base64"));let y=h.update(Buffer.from(g.data,"base64"));y=Buffer.concat([y,h.final()]);let w=JSON.parse(y.toString("utf8"));a=w.username,s||(s=w.password)}}catch{}let u=[t.browserStatePath];t.poolStatePath&&u.push(t.poolStatePath),a&&s?(P(n,"Opening browser for SSO login..."),await o.login({headed:!0,sso:{user:a,pass:s},extraStatePaths:u})):(P(n,"No saved credentials. Opening browser for manual login..."),await o.login({headed:!0,extraStatePaths:u})),t.pool&&await t.pool.warm(),P(n,"Login successful. Session saved.")}catch(o){let s=o instanceof Error?o.message:String(o),a=s.includes("CDP error")||s.includes("daemon already running")||s.includes("Session with given id not found");k(n,a?"Login failed: browser session error. Try again.":Wn(o)?o.message:`Login failed: ${s}`)}}),r.command("list").description("List saved profiles").action(async()=>{let i=t.getTransport();try{$(n,await i.run("auth",["list"]))}catch(o){k(n,`Error: ${_("auth list",o)}`)}}),r.command("show").argument("<profile>","profile name").description("Inspect a profile").action(async i=>{let o=t.getTransport();try{$(n,await o.run("auth",["show",i]))}catch(s){k(n,`Error: ${_("auth show",s)}`)}}),r.command("delete").argument("<profile>","profile name").description("Remove credentials").action(async i=>{let o=t.getTransport();try{$(n,await o.run("auth",["delete",i]))}catch(s){k(n,`Error: ${_("auth delete",s)}`)}})}var Im=v(()=>{"use strict";Z()});function Dm(e){return e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.name?e.name:"Unknown"}function Bx(e){let t=Dm(e),n=[e.title,e.pmd?"Partner":""].filter(Boolean),r=n.length?`${t} \u2014 ${n.join(", ")}`:t,i=[e.divisionName,e.departmentName].filter(Boolean).join(" / "),o=[e.city,e.country,e.region].filter(Boolean).join(", "),s=[e.company,o].filter(Boolean).join(" \xB7 ");return[r,i,s].filter(Boolean).join(`
127
+ `)}function Hx(e){return JSON.stringify({name:Dm(e),title:e.title??null,partner:e.pmd??!1,division:e.divisionName??null,department:e.departmentName??null,company:e.company??null,city:e.city??null,country:e.country??null,region:e.region??null},null,2)}function Tm(e,t){e.command("whoami").option("--json","Output as JSON").description("Show current user identity").action(async n=>{let r,i=Math.round(performance.now());try{r=await t.getHttpTransport().request("/v1/users/self")}catch(s){if(s instanceof T&&s.code==="auth_expired"){P(t.write,s.details?.brokerCode==="relink_required"?s.message:"Not authenticated. Run: marquee auth login");return}throw s}let o=Math.round(performance.now())-i;process.env.MARQUEE_TRACE_LOG&&process.stderr.write(`__MQ_TRACE__${JSON.stringify([{method:"GET",path:"/v1/users/self",queryKeys:[],startMs:i,durationMs:o,status:"ok"}])}
128
+ `),n.json?P(t.write,Hx(r)):P(t.write,Bx(r))})}var Pm=v(()=>{"use strict";Z();xn()});function Yx(e){try{return new URL(e).hostname==="marquee.gs.com"}catch{return!1}}function Kx(e,t){let n=e.startsWith(".")?e.slice(1):e;return t===n||t.endsWith(`.${n}`)}function Qx(e,t){return e.expires===void 0||e.expires<0||e.expires>t}function Zx(e){let t=["set",e.name,e.value,"--url",zx];return e.domain&&t.push("--domain",e.domain),e.path&&t.push("--path",e.path),e.httpOnly&&t.push("--httpOnly"),e.secure&&t.push("--secure"),e.sameSite&&t.push("--sameSite",e.sameSite),e.expires!==void 0&&t.push("--expires",String(Math.floor(e.expires))),t}function _m(e){let t=e.syncIntervalMs??Jx,n=0;function r(){if(e.useCookieJar&&!e.useCookieJar())return;let u=dt(e.cookieJarPath);if(Mr(u,"marquee.gs.com"))return u}function i(u){let l=r();if(!l)return;let c=Math.floor(Date.now()/1e3);return l.cookies.filter(d=>Qx(d,c)&&Kx(d.domain,u))}async function o(u,l,c){for(let d of l)await u.run("cookies",Zx(d),{skipAuthCheck:!0,headed:c})}async function s(u){let l=Date.now();if(l-n<t)return;let c=i("marquee.gs.com");if(!c)return;await o(u,c);let d=await u.run("tab",["list","--json"],{skipAuthCheck:!0}),f=JSON.parse(d)?.data?.tabs??[];for(let p of f)p.url?.startsWith("https://idfs.gs.com")&&await u.run("tab",["close",p.tabId],{skipAuthCheck:!0});n=l}async function a(u,l){if(!Yx(l))return;let c=new URL(l).hostname,d=i(c);d&&(await o(u,d,!0),n=Date.now())}return{maybeSyncBrowserCookies:s,syncBrowserAuthState:a}}var zx,Jx,$m=v(()=>{"use strict";En();zx="https://marquee.gs.com",Jx=300*1e3});import{createHash as Xx}from"node:crypto";import{homedir as Mi}from"node:os";import{join as Xn}from"node:path";function r0(e){let{replayDir:t,recordDir:n,recordNaming:r,manifestPath:i}=e;if(t&&n)return In({mode:"record",dir:n,naming:r,manifestPath:i,realFetch:In({mode:"replay",dir:t})});if(t)return In({mode:"replay",dir:t});if(n)return In({mode:"record",dir:n,naming:r,manifestPath:i})}function i0(e=process.env,t=process.pid){if(e.MARQUEE_HTTP_RECORD)return e.MARQUEE_HTTP_RECORD;if(e.MARQUEE_RECORD_LIVE&&!e.MARQUEE_HTTP_REPLAY)return Xn(e.MARQUEE_RECORD_LIVE,`cli-${t}`)}function Wa(e){return Xx("sha256").update(e).digest("hex").slice(0,12)}function o0(e=process.env,t=process.cwd(),n=process.ppid){let r=e.MARQUEE_OWNER_SESSION_ID?.trim();if(r)return`owner-${Wa(r)}`;let i=e.MARQUEE_SESSION_PID_SOURCE==="shim",o=e.INIT_CWD&&e.INIT_CWD.trim().length>0?e.INIT_CWD:t;return i&&o.trim().length>0?`cwd-${Wa(o)}`:e.npm_execpath&&e.npm_lifecycle_event==="npx"&&o.trim().length>0?`cwd-${Wa(o)}`:`p${n}`}function s0(e=process.env){let t=e.MARQUEE_REF_STORE_DIR?.trim();return t&&t.length>0?t:t0}function La(){return process.env.NODE_ENV==="test"||process.env.VITEST==="true"||process.env.VITEST_WORKER_ID!==void 0}function a0(e,t){let n=Array.from(e??process.argv);return t==="user"?n:t==="electron"?n.slice(1):n.slice(2)}function u0(e,t){return e.commands.find(n=>n.name()===t||n.aliases().includes(t))}function d0(e){let t=e.parseAsync.bind(e);e.parseAsync=(async(n,r)=>{let i=a0(n,r?.from);if(!i.some(s=>s==="--help"||s==="-h"))return t(n,r);let o=e;for(let s of i){if(s==="--"||s==="--help"||s==="-h")break;if(s.startsWith("-"))continue;let a=u0(o,s);if(a){o=a;continue}o.commands.length>0&&o.error(`error: unknown command '${s}'`,{code:"commander.unknownCommand"});break}return t(n,r)})}function c0(e,t){let n=e.cookieJarPath??Ua;return e.transport?new Dn({jarPath:n,sleep:async()=>{},spawnFn:async(r,i)=>{let o=Yo(i[0])?i.slice(1):i,s=o[0]==="--session"?o.slice(2):o,a=s[0]==="--headed";a&&(s=s.slice(1));let u=s[0],l=s.slice(1);return u==="eval"?{stdout:(l[0]??"").includes("/v1/users/self")?"authed":"true",stderr:""}:u==="cookies"&&l[0]==="get"?{stdout:JSON.stringify({success:!0,data:{cookies:[{name:"test",value:"1",domain:"marquee.gs.com",path:"/",expires:-1,httpOnly:!1,secure:!0,sameSite:"Lax"}]}}),stderr:""}:{stdout:await t().run(u??"",l,{skipAuthCheck:!0,headed:a}),stderr:""}}}):new Dn({jarPath:n})}async function l0(e,t,n){return await Om(e,t,n)==="authenticated"}async function Om(e,t,n){if(e.transport)try{return await t().isAuthenticated()?"authenticated":"unauthenticated"}catch{return"auth-unavailable"}if(Mm())try{return await n().request("/v1/users/self"),"authenticated"}catch(r){return p0(r)?"relink-required":qa(r)?"unauthenticated":"auth-unavailable"}try{let r=dt(e.cookieJarPath??Ua),i=new URL("/v1/users/self","https://marquee.gs.com");if(!Wr(r,i))return"unauthenticated";await n().request("/v1/users/self")}catch(r){return qa(r)?"unauthenticated":"auth-unavailable"}try{let r=await n().request("/research/session-exchange");return f0(r)?"authenticated":"research-unavailable"}catch(r){return qa(r)?"research-expired":"research-unavailable"}}function f0(e){return typeof e=="string"?e.trim().length>0:typeof e!="object"||e===null||Array.isArray(e)?!1:["token","accessToken","access_token"].some(t=>{let n=e[t];return typeof n=="string"&&n.trim().length>0})}function qa(e){return e instanceof T&&(e.code==="auth_expired"||e.details?.status===401||e.details?.status===403)}function p0(e){return e instanceof T&&e.details?.brokerCode==="relink_required"}function Na(e,t={}){let n=t.poolStatePath??e0,r=!t.transport&&!La()?xl({stateFile:n}):void 0,i=t.pool??r;r&&r.installExitHandlers();let o=new Sp,s,a,u,l,c;o.name("marquee"),o.exitOverride(),o.enablePositionalOptions();function d(){return t.transport?t.transport:(s||(s=jr({session:Fa,pool:r??void 0})),s)}let f=_m({cookieJarPath:g(),useCookieJar:()=>!(La()&&!t.cookieJarPath)});function p(){if(t.browserTransport)return t.browserTransport;if(t.transport)return t.transport;if(!a){let S=jr({session:Fa});a={...S,async run(C,x=[],E={}){return C!=="state"&&C!=="close"&&await f.maybeSyncBrowserCookies(S),S.run(C,x,E)}}}return a}function g(){return t.cookieJarPath??Ua}function h(){return t.browserStatePath??n0}function y(){if(!u){let S=Mm();if(S)return u=new $r(S),u;let C=dt(g());if(!Mr(C,"marquee.gs.com"))throw new T("auth_expired","Not authenticated. Run: marquee auth login");let x=process.env.MARQUEE_HTTP_REPLAY,E=i0(),j=process.env.MARQUEE_HTTP_RECORD_NAMING==="readable"?"readable":"hash";u=new Fr({jar:C,jarPath:g(),fetchFn:r0({replayDir:x,recordDir:E,recordNaming:j,manifestPath:process.env.MARQUEE_HTTP_RECORD_MANIFEST}),saveFn:x?()=>{}:void 0})}return u}function w(){if(t.router)return t.router;if(!l){if(La())return l=Nr(),l;l=gl({request:(S,C)=>y().request(S,C)},async(S,C)=>qo(S,C,t.adaptersDir),No)}return l}function b(){return c||(c=Ag(t.refStoreDir??s0(),o0(process.env))),c}let R={write:e,getRouter:w,getRegistry:b,getTransport:d,getBrowserTransport:p,getHttpTransport:y,createAuthClient:()=>c0(t,d),isAuthenticated:()=>l0(t,d,y),getAuthStatus:()=>Om(t,d,y),syncBrowserAuthState:f.syncBrowserAuthState,resolveBrowserOpenTarget:S=>hf(b(),S),renderWidgetTab:(S,C={})=>Of(S,C,{write:e,router:w(),registry:b()}),renderDashboardTab:(S,C=!1)=>Xf(S,C,{write:e,router:w(),registry:b()}),renderContentArticle:(S,C)=>$p(R,S,C),renderContentSearch:(S,C)=>Op(R,S,C),browserStatePath:h(),poolStatePath:i?n:void 0,pool:i?{warm:()=>i.warm()}:void 0};return sp(o,R),up(o,R),Ip(o,R),Tg(o,R),Vg(o,R),Zg(o,R),_g(o,R),Ig(o,R),tm(o,R),pm(o,R),km(o,R),vm(o,R),Tm(o,R),Sm(o,R),xm(o,R),d0(o),{program:o}}function Mm(e=process.env){let t=e.MARQUEE_BROKER_URL?.trim(),n=e.MARQUEEBOT_ACCOUNT_ID?.trim(),r=e.MARQUEE_OWNER_SESSION_ID?.trim(),i=e.MARQUEE_BROKER_INVOCATION_TOKEN?.trim(),o=[t,n,i].filter(Boolean).length;if(o!==0){if(o!==3||!r)throw new T("config","Incomplete credential broker configuration: set MARQUEE_BROKER_URL, MARQUEEBOT_ACCOUNT_ID, MARQUEE_OWNER_SESSION_ID, and MARQUEE_BROKER_INVOCATION_TOKEN");return{brokerUrl:t,accountId:n,sessionId:r,invocationToken:i}}}function Wm(e=o=>process.stdout.write(o),t,n,r,i={}){return{program:Na(e,{router:t,transport:n,refStoreDir:r,...i}).program,async runForTest(s){let a="";return await Na(l=>{a+=l},{router:t??Nr(),transport:n??jr({session:Fa}),refStoreDir:r,...i}).program.parseAsync(s,{from:"user"}),JSON.parse(a)}}}async function Lm(e,t,n){let r="";return await Na(o=>{r+=o},{router:t,refStoreDir:n}).program.parseAsync(e,{from:"user"}),JSON.parse(r)}var Fa,e0,t0,Ua,n0,ja=v(()=>{"use strict";Gc();xn();xn();En();Nl();Jl();Cs();ep();Is();Is();dp();Dp();Mp();Dg();Pg();$g();Gg();Xg();nm();gm();Am();Cm();Im();Pm();$m();Si();Z();Hs();Z();Fa="marquee",e0=Xn(Mi(),".agent-browser","pool","state.json"),t0=Xn(Mi(),".marquee","sessions"),Ua=process.env.MARQUEE_COOKIE_JAR??Xn(Mi(),".marquee","cookies.json"),n0=process.env.MARQUEE_BROWSER_STATE??Xn(Mi(),".marquee","browser-state.json")});var qm={};Y(qm,{createProgram:()=>Wm,formatColumns:()=>Qr,resolveMarqueeUrl:()=>ti,runCli:()=>Lm,toText:()=>oe});var Fm=v(()=>{"use strict";ja();ja();ss();Me()});ge();function Jm(e){return e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]}function Ym(e){try{return new URL(e),!0}catch{return!1}}function Km(e){return e.startsWith("/content/research/")}function Qm(e){let t,n=!1,r=!1;for(let i=0;i<e.length;i++){let o=e[i];if(o==="-h"||o==="--help")return{json:n,hasDate:r,fastPathSafe:!1};if(o==="--json"){n=!0;continue}if(o==="--date"){r=!0,i++;continue}if(o.startsWith("--date=")){r=!0;continue}if(o==="--lang"){i++;continue}if(!o.startsWith("--lang=")){if(o.startsWith("-"))return{json:n,hasDate:r,fastPathSafe:!1};if(t!==void 0)return{json:n,hasDate:r,fastPathSafe:!1};t=o}}return{input:t,json:n,hasDate:r,fastPathSafe:!0}}function Ha(e){if(e[0]!=="content"||e[1]!=="research")return{handled:!1};let t=Qm(e.slice(2));return!t.fastPathSafe||t.hasDate||!t.input||!Jm(t.input)||Ym(t.input)||Km(t.input)?{handled:!1}:t.json?{handled:!0,exitCode:1,stdout:`${JSON.stringify({status:"error",surface:"content",action:"get",data:{},errors:["--date is required when loading content research by UUID"]})}
129
+ `}:{handled:!0,exitCode:1,stdout:["\u2717 --date YYYY-MM-DD is required for UUID input."," The GIR HTML path requires the publication date to construct."," Alternatives:"," - Add --date: marquee content research 123e4567-... --date 2026-01-15"," - Use the full URL: marquee content research https://marquee.gs.com/content/research/en/reports/2026/01/15/123e4567-....html",' - Search + load: marquee content search "<query>" -> load @s1.crN'].join(`
130
+ `)+`
131
+ `}}function za(e){let t=e?.code;if(t==="commander.helpDisplayed"||t==="commander.version")return{exitCode:0,exitImmediately:0};let n;if(e instanceof T){let r=e.details?.body,i=r?` \u2014 ${r.length>200?r.slice(0,200):r}`:"";n=`${e.message}${i}
132
+ `}else e instanceof Error&&(n=`Error: ${e.message}
133
+ `);return{...n?{stderr:n}:{},exitCode:e?.exitCode??1}}function Nm(e){return new Promise(t=>{e.write("",()=>t())})}function g0(){let e=Ha(process.argv.slice(2));return e.handled?(process.stdout.write(e.stdout??""),process.exitCode=e.exitCode,!0):!1}try{if(!g0()){let{createProgram:e}=await Promise.resolve().then(()=>(Fm(),qm));await e().program.parseAsync(process.argv)}}catch(e){let t=za(e);t.exitImmediately!==void 0&&process.exit(t.exitImmediately),t.stderr&&process.stderr.write(t.stderr),process.exitCode=t.exitCode}process.env.MARQUEE_TRACE_LOG&&process.stderr.write(`__MQ_TRACE__[]
134
+ `);await Nm(process.stdout);await Nm(process.stderr);process.exit(process.exitCode??0);