UNPKG

dt-app

Version:

The Dynatrace App Toolkit is a tool you can use from your command line to create, develop, and deploy apps on your Dynatrace environment.

163 lines (133 loc) 225 kB
#!/usr/bin/env node "use strict";var Wu=Object.create;var ua=Object.defineProperty;var Vu=Object.getOwnPropertyDescriptor;var Hu=Object.getOwnPropertyNames;var Gu=Object.getPrototypeOf,zu=Object.prototype.hasOwnProperty;var Ju=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Hu(t))!zu.call(e,r)&&r!==n&&ua(e,r,{get:()=>t[r],enumerable:!(o=Vu(t,r))||o.enumerable});return e};var T=(e,t,n)=>(n=e!=null?Wu(Gu(e)):{},Ju(t||!e||!e.__esModule?ua(n,"default",{value:e,enumerable:!0}):n,e));var Nu=require("dotenv"),Dn=require("path"),Io=require("fs"),ma=require("os");var re=require("chalk"),Yt=require("lodash");var de=require("fs"),ga=require("fs/promises"),Mo=require("path"),Ku=new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}_log.txt/),fa=e=>(e>9?"":"0")+e,qu=e=>`${e.getFullYear()}-${fa(e.getMonth()+1)}-${fa(e.getDate())}_log.txt`,Yu=e=>{try{let t=e.split("-");return new Date(Number(t[0]),Number(t[1]),Number(t[2].split("_")[0]))}catch{return}},wi=class{async setup(t){return Promise.resolve()}write(t){}getLogFile(){return""}},vi=class{logFolder;logFile;stream;async setup(t){this.logFolder=(0,Mo.join)(t,".dt-app/logs"),(0,de.existsSync)(this.logFolder)||(0,de.mkdirSync)(this.logFolder,{recursive:!0}),await this.rotate()}async rotate(){if(this.logFile=(0,Mo.join)(this.logFolder,qu(new Date)),!(0,de.existsSync)(this.logFile)){let t=(0,de.readdirSync)(this.logFolder).map(n=>n.trim()).filter(n=>Ku.test(n));if(t.length>=10){let n=t.map(o=>({path:o,date:Yu(o)})).filter(o=>o.date).sort((o,r)=>o.date.getTime()-r.date.getTime())[0].path;(0,ga.unlink)((0,Mo.join)(this.logFolder,n))}(0,de.closeSync)((0,de.openSync)(this.logFile,"w"))}await new Promise(t=>{this.stream=(0,de.createWriteStream)(this.logFile,{encoding:"utf-8",flags:"a"}),this.stream.on("open",()=>t())})}write(t){this.stream&&this.stream.write(t)}getLogFile(){return this.logFile}};async function ha(e){return vt=new vi,vt.setup(e)}var vt=new wi;var va=require("os");var Ci=T(require("ora"));var bi=[],qt=!1;function Zu(e){return new Promise((t,n)=>{bi.push(async()=>{try{let o=await e();t(o)}catch(o){n(o)}}),Xu()})}async function Xu(){if(!qt){for(qt=!0;bi.length>0;)await bi.shift()();qt=!1}}async function No(e){return Zu(e)}var _n=process.env.DT_APP_DEACTIVATE_SPINNER!=="true",Mn={interval:80},Je=[],bt="idle",Un=(0,Ci.default)({spinner:{frames:[""],interval:Mn.interval},isSilent:!_n}),Qu=()=>` ${Je.map(e=>e.getFrame()).join(` `)}`;function ef(){Un.text=Qu()}var Nn;function tf(){_n&&bt!=="running"&&!qt&&(Nn===void 0&&(Nn=setInterval(ef,Mn.interval)),Un.start(),bt="running")}function ya(){bt==="running"&&(bt="paused",Un.stop())}function wa(){bt==="paused"&&!qt&&(bt="running",Un.start())}function Ti(){bt="idle",Un.stop(),Je.forEach(e=>e.abort()),Nn!==void 0&&(clearInterval(Nn),Nn=void 0)}var _o=class{spinner;constructor(t){this.spinner=(0,Ci.default)({...t,isSilent:!_n})}get text(){return this.spinner.text}set text(t){this.spinner.text=t}cleanup(){let t=Je.indexOf(this);t>-1&&(this.spinner.isSpinning&&this.spinner.stop(),Je.splice(t,1)),Je.length===0&&Ti()}getFrame(){return this.spinner.frame()}start(t){return t&&(this.text=t),Je.includes(this)||Je.push(this),tf(),this}_stop(t,n="abort"){switch(this.text=t??this.text,ya(),n){case"success":this.spinner.succeed(this.text);break;case"info":this.spinner.info(this.text);break;case"fail":this.spinner.fail(this.text);break;case"warn":this.spinner.warn(this.text);break;case"abort":this.spinner.stop();break;default:this.spinner.stopAndPersist(n)}return this.cleanup(),wa(),this}stop(t,n={}){return this._stop(t,n)}abort(){return this._stop(void 0,"abort")}info(t){return this._stop(t,"info")}succeed(t){return this._stop(t,"success")}fail(t){return this._stop(t,"fail")}warn(t){return this._stop(t,"warn")}},ke={create:(e={})=>new _o({...e,interval:Mn.interval}),start:(e,t={})=>new _o({...t,interval:Mn.interval}).start(e),pause:ya,resume:wa,reset:Ti,successAll:e=>Je.forEach(t=>t.succeed(e)),failAll:e=>Je.forEach(t=>t.fail(e)),disable:()=>{_n=!1,Ti()},enable:()=>{_n=!0},getInterval:()=>Mn.interval,_getMockedSpinner:function(e){let t={abort:(...n)=>t,fail:(...n)=>t,info:(...n)=>t,start:(...n)=>t,stop:(...n)=>t,succeed:(...n)=>t,text:e??"",warn:(...n)=>t};return t}};var ba=`Using 0.0.0.0 as host will expose the dev server to your internal network! Use 0.0.0.0 as host only when you want to access the dev server from another machine. Remove "host: '0.0.0.0'" if this behavior is not explicitly wanted.`;var Ei=class{boxSize=80;warningBoxSize=90;disabled=!1;spinner={create:()=>ke.create(),disable:ke.disable,start:t=>ke.start(t),pause:ke.pause,resume:ke.resume,abort:ke.reset};disable(){this.disabled=!0,ke.disable()}log(t){this._log(`${this._padString(t,1)}`,"INFO")}debug(t,n){global.VERBOSE_MODE&&n.startsWith(global.VERBOSE_MODE.replace("%",""))&&(this.spinner.pause(),console.log(`${(0,re.yellow)("DEBUG")}${this._padString(`[${n}] ${t}`,1)}`),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ke.getInterval())),this._printToFile(`[${n}] ${t}`,"DEBUG")}info(t,n){this._log(n===void 0||n?this._padString(t,0):t,"INFO")}success(t){this._log((0,re.green)(this._padString(t,0)),"INFO")}error(t){this._log((0,re.red)(this._padString(t,0)),"ERROR")}warn(t){let n=` ${(0,re.yellow)("Warning "+(0,Yt.repeat)("─",this.warningBoxSize-8))} ${(0,re.yellow)(this._padString(t))} ${(0,re.yellow)((0,Yt.repeat)("─",this.warningBoxSize))} `;this._log(n,"WARNING")}logBox(t){if(this.disabled)return;let n=` ${(0,re.magenta)((0,Yt.repeat)("─",this.boxSize))} ${(0,re.magenta)(this._padString(t))} ${(0,re.magenta)((0,Yt.repeat)("─",this.boxSize))} `;this._log(n,"INFO")}clean(){this.spinner.abort()}async initLogFile(t){this.disabled||await ha(t)}debounceTimeout;_log(t,n){this.disabled||(this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.spinner.pause(),n==="ERROR"?console.log(t):No(()=>Promise.resolve(console.log(t))),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ke.getInterval()),this._printToFile(t,n))}_printToFile(t,n){vt.write(`${of().toISOString()} ${n} ${nf(t)} `)}_padString(t,n=2){return`${t}`.split(/[\n\r]/).map(o=>`${(0,Yt.repeat)(" ",n)}${o}`).join(va.EOL)}};function nf(e){let t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return e.replace(new RegExp(t,"g"),"")}function of(){let e=new Date,t=e.getTimezoneOffset()*6e4;return e.setTime(e.getTime()-t),e}var p=new Ei;var Zt=require("fs");var $n=require("path");var Ta=require("chalk"),Bn=(o=>(o.GENERIC_CLI_ERROR="DEC:D9",o.CONNECTION_ERROR="DEC:DA",o.INVALID_APP_STRUCTURE="DEC:E3",o))(Bn||{}),E=(m=>(m[m.POSIX_SIGNAL_BASE=128]="POSIX_SIGNAL_BASE",m[m.UNCAUGHT=256]="UNCAUGHT",m[m.INTERNAL=257]="INTERNAL",m[m.USER=258]="USER",m[m.AUTH=259]="AUTH",m[m.TIMEOUT=260]="TIMEOUT",m[m.COMPILATION=261]="COMPILATION",m[m.NETWORKING=263]="NETWORKING",m[m.VALIDATION=264]="VALIDATION",m[m.BUILD=265]="BUILD",m[m.APP_GATEWAY_COMMUNICATION=266]="APP_GATEWAY_COMMUNICATION",m))(E||{}),rf=`Authentication failed! Please make sure that: * The provided client ID and the secret are correct. * The provided client ID has needed scopes. Deploy scopes: * app-engine:apps:run * app-engine:apps:install * app-engine:apps:delete Uninstall scopes: * app-engine:apps:delete Telemetry scopes: * app-engine:apps:run Development server needs all the scopes specified in the app.config. For more details on how you can configure authentication, see https://dt-url.net/qw024j8 `;function Uo(e){let t=[e,rf];return new Error(t.filter(Boolean).join(` `),{cause:259})}function Ca(e){return e?e.replace(/\(|\)/g,"").split(" ").filter(Boolean).map(t=>t.includes($n.sep)?`${t.split($n.sep).pop()}`:t).join(" "):"No stacktrace is available for this error"}function st(e){return e?e.replace(/\(|\)/g,"").split(" ").filter(Boolean).map((t,n)=>n===0&&t.toLocaleLowerCase()==="error:"?"":t).map(t=>t.includes("http")||t.includes("://")?"":t).map(t=>t.includes($n.sep)?`${t.replace(/["']/g,"").split($n.sep).pop()}`:t).join(" ").substring(0,200).trim():""}function w(e){return e instanceof Error?e:new Error(String(e))}function $o(e,t){throw new Error(`ERROR [${(0,Ta.green)(t)}]: ${e.message}`)}function M(e){if(!(0,Zt.existsSync)(e)&&!(0,Zt.lstatSync)(e,{throwIfNoEntry:!1})?.isFile())throw new Error(`[read-json.ts] File does not exist: ${e}`,{cause:257});let t=(0,Zt.readFileSync)(e,"utf-8");return JSON.parse(t)}var Xt=require("fs"),jn=require("os"),Ea=require("path"),Ai=(0,Ea.join)((0,jn.homedir)(),".dt-app","history"),Tt,xa="◬";function Aa(){Sa();let e=process.argv.slice(1);if(!(e.length<1)){e[0].endsWith(".js")&&(e=e.slice(1));try{(0,Xt.appendFileSync)(Ai,`${e.join(" ")}${xa}${jn.EOL}`)}catch{}}}function Sa(){Tt||(Tt=(0,Xt.existsSync)(Ai)?(0,Xt.readFileSync)(Ai,"utf-8").split(jn.EOL):[],Tt.length>0&&Tt[Tt.length-1]===""&&Tt.pop())}function sf(){return Sa(),Tt??[]}function Oa(){let e=sf();if(e.length===0)return{command:"(none)"};let t=e[e.length-1],[n]=t.split(xa);return{command:n}}var Pa=require("child_process"),Ra=require("semver");function Fa(e){let{engines:t}=e;if(t){for(let[n,o]of Object.entries(t))if(n==="node"||n==="npm"){let r=(0,Pa.execSync)(`${n} --version`).toString();if(!(0,Ra.satisfies)(r,o))throw new Error(`Your ${n} version does not satisfy the version requirements of ${o}, installed: ${r}`,{cause:258})}}}function ka(){let e=process.argv.indexOf("--verbose");if(e<0)return;let t=process.argv[e+1],n=!t||t.startsWith("-")?"%":t;global.VERBOSE_MODE=n}var Bo=process.env.CODESPACE_NAME&&process.env.CODESPACE_NAME.trim()!==""?process.env.CODESPACE_NAME:void 0;function Da(e){if(!Bo)return;let t=process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN;return`${Bo}-${e}.${t}`}var Ln=process.env.GITPOD_WORKSPACE_URL&&process.env.GITPOD_WORKSPACE_URL.trim()!==""?process.env.GITPOD_WORKSPACE_URL:void 0;function Ia(e){if(!Ln)return;let t=new URL(Ln).hostname;return`${e}-${t}`}var Si=process.env.DT_APP_DEV_ENVIRONMENT_URL&&process.env.DT_APP_DEV_ENVIRONMENT_URL.trim()!==""?process.env.DT_APP_DEV_ENVIRONMENT_URL:void 0,fe=Ln||Bo||Si;function Ct(e){if(fe)return Si?Si.replace(/^https?:\/\//,""):Ln?Ia(e):Da(e)}function jo(e){let t=Ct(e);return t?`wss://${t.replace(/^https?:\/\//,"")}`:""}function Lo(){console.log(`${global.DT_APP_VERSION}`)}function Ma(...e){let t=process.version.replace("v","").split(".").shift(),n=Number(t);return e.includes(n)?!0:(p.warn(`To prevent potential issues, please use dt-app with the officially supported Node.js version ${e[0]}.`),!1)}var it=require("commander");var Ps=require("path"),Tn=require("commander");var Pt=require("@dynatrace/openkit-js"),Za=require("lodash"),Ot=require("fs"),Jo=require("fs/promises"),Xa=T(require("http")),Qa=T(require("https")),at=require("os"),Fi=require("path"),Hn=require("url");var Na=require("child_process"),pf=require("commander");function ee(e,t){let o={cwd:t||process.cwd(),maxBuffer:10485760};return new Promise((r,i)=>{(0,Na.exec)(e,o,(s,a,c)=>{s!==null?i(s):typeof c!="string"?i(c):r(a)})})}var Et=require("undici");async function A(e,t){return(0,Et.fetch)(e,t)}var Wn="/platform/app-engine/registry/v1",lf="APP-REGISTRY";function _a(e,t,n,o,r){let i=JSON.stringify(t,null,2),a=`${e} HTTP ${n} ${o} ${t?.message??""}`+` ${df(t,r)}`;return p.debug(`${a}${i}`,lf),new Error(a,{cause:266})}function df(e,t){return e?.details?.constraintViolations?e.details.constraintViolations.reduce((n,o)=>{let r=mf(o,t);return`${n} ${r}`},""):""}function mf(e,t){let{errorCode:n,errorCodeProperties:o,message:r}=e,i=r;if(n&&t){let s=o?.dependency,a=t.find(c=>c.name===s)?.packageJsonDep;if(n==="DependencyUnknown"&&(i=`Unknown endpoint ${s} being used in your dependency ${a}. Please check that dependency.`),n==="DependencyVersionIncompatible"){let c=o?.availableVersion,l=o?.incompatibleVersion;i=`The endpoint ${s} found in your dependency ${a} is using an incompatible version. Please check that dependency and upgrade or downgrade accordingly.${l||c?` `:""} ${l?`Incompatible version found in your dependencies: ${l} `:""}${c?`Available version for the endpoint: ${c}`:""}`}}return i}function Wo(e){let t=["Error while connecting to the app registry",e];return new Error(t.filter(Boolean).join(` `),{cause:266})}async function Vo(e,t,n){try{let o=new URL(e);o.pathname=`${Wn}/apps/${n}`,o.searchParams.append("add-fields","manifest,resourceStatus.subResourceStatuses"),o.searchParams.append("latest-app-version","true");let r={headers:{authorization:`Bearer ${t}`}},i=await A(o.toString(),r);return await uf(i)===0?void 0:await i.json()}catch(o){throw Wo(w(o).message)}}async function uf(e){if(e.ok&&e.headers.get("content-type")?.includes("text/html"))return 1;if(!e.ok){if(e.status===403)throw Uo(e.statusText+` `);if(e.status===404)return 0;{let t=await e.json(),n=t&&typeof t=="object"&&"error"in t&&typeof t.error=="object"&&t.error&&"message"in t.error?t.error.message:"";throw new Error(`Failed fetching app: ${e.status} ${e.statusText} ${n}`,{cause:263})}}if(e.headers.get("content-type")?.includes("text/html"))throw new Error("Fetching the app returned an unexpected response. Please re-check your environment url.",{cause:263})}async function Ho(e,t){try{let n=new URL(e),o={headers:{authorization:`Bearer ${t}`,"content-type":"application/octet-stream"}};n.pathname="/platform/metadata/v1/user";let r=await A(n.toString(),o);return!r.ok||r.headers.get("content-type")?.includes("text/html")?void 0:await r.json()}catch(n){throw Wo(w(n).message)}}async function Ua(e,t,n,o){try{let r=new URL(e);r.pathname=`${Wn}/apps`;let i=await A(r.toString(),{method:"POST",body:t,headers:{authorization:`Bearer ${n}`,"content-type":"application/zip"}});if(!i.ok){let s=await i.json();return _a("Failed to install the app",s.error,i.status,i.statusText,o)}}catch(r){return Wo(w(r).message)}}async function $a(e,t,n){try{let o=new URL(e);o.pathname=`${Wn}/apps/${t}`;let r=await A(o.toString(),{method:"DELETE",headers:{authorization:`Bearer ${n}`}});if(!r.ok){let i=await r.json();return _a("Failed to uninstall the app",i.error,r.status,r.statusText)}}catch(o){return Wo(w(o).message)}}async function Ba(e,t){let n=await A(`${e}/platform/app-engine/registry/v1/app.default.csp.json`,{headers:{authorization:`Bearer ${t}`}});return n.status>=200&&n.status<=299?(await n.json()).policyDirectives:(p.warn(`The default csp policy from the platform couldn't be applied. App-registry failed with: ${n.status} ${n.statusText}`),{})}function Qt(e){let t=new URL(e),[n,...o]=t.hostname.split(".");if(!o||o.length<1)throw new Error(`Invalid environment URL: "${e}"`,{cause:258});return{tenant:n,hostname:o.join(".")}}async function ff(e,t,n,o){let r=await Ba(e,n),i=[3e3,3001,3002,3003,3004,3005],s=i.flatMap(f=>fe?[`https://${Ct(f)}`]:[`http://localhost:${f}`,`https://localhost:${f}`]),a=i.flatMap(f=>fe?[jo(f)]:[`ws://localhost:${f}`,`wss://localhost:${f}`]),c={"script-src":["'unsafe-eval'",...s,...t.map(f=>`'sha256-${f}'`)],"connect-src":[...s,...a],"frame-ancestors":s},{tenant:l,hostname:d}=Qt(e),m=f=>f.replaceAll("{tenantId}",l).replaceAll("{hostname}",d),u={},g=[...Object.keys(r),...Object.keys(c)];for(let f of g){let y=new Set;for(let b of r[f]??[])y.add(m(b));for(let b of c[f]??[])y.add(m(b));u[f]=Array.from(y)}return u["frame-src"]=["*"],u["frame-ancestors"]=["*"],o&&Object.entries(o).forEach(([f,y])=>{u[f]?u[f].push(...y.map(b=>b.value)):u[f]=y.map(b=>b.value)}),gf(u)}function gf(e){return Object.entries(e).map(([t,n])=>`${t} ${n.join(" ")}`).join("; ")}var ja=new Map;async function La(e,t,n,o){let r=`${e}-${t.join(",")}-${o}`,i=ja.get(r);if(i)return i;let s=await ff(e,t,n,o);return ja.set(r,s),s}var ki=require("jsonwebtoken");var Wa=require("path"),Va=require("os"),At=require("fs"),Vn=require("fs/promises");var xt=(0,Wa.join)((0,Va.homedir)(),".dt-app",".session"),hf=19;function Ha(e){return e instanceof Error?{error:{name:e.name,message:e.message,stack:e.stack,cause:e.cause}}:e}function Oi(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ga(n)]))}function Ga(e){return e==null?e:Array.isArray(e)?e.map(t=>Ga(t)):typeof e=="object"?Oi(e):typeof e=="string"?st(e):e}function za(){return Math.floor(Math.random()*Math.pow(10,18))}function yf(e){return e!==""&&e.length<=hf&&Number.isInteger(Number(e))}function Ja(){try{if(!(0,At.existsSync)(xt))return;let e=(0,At.statSync)(xt).birthtime;wf(e)&&(0,At.unlinkSync)(xt)}catch{p?.debug("Could not identify user uniquely",C)}}function wf(e){return(new Date().getTime()-e.getTime())/(1e3*3600)>=24}async function Ka(e){try{if((0,At.existsSync)(xt)){let n=(await(0,Vn.readFile)(xt)).toString();yf(n)?e=Number(n):await(0,Vn.writeFile)(xt,e.toString())}else await(0,Vn.writeFile)(xt,e.toString())}catch(t){console.error("Error initializing session file:",t)}return e}async function qa(e){let t=M(e),n=t?.app_token?.access_token||t?.toolkit_token?.access_token;if(n)return Ho(t.app_token?.environment_url||t.toolkit_token?.environment_url||"",n)}function $(e){return e.reduce((t,n,o,r)=>{if(n.startsWith("--")){let i=n.slice(2),s=r[o+1];s&&!s.startsWith("--")?t[i]=st(s):t[i]=!0}return t},{})}function Ya(e){return e.includes("dev")?"dev":e.includes("hardening")?"hardening":"prod"}function Pi(e){if(!e)return"";let t;if(typeof e=="string")t=e;else{if(!e.userId)return"";t=e.emailAddress}if(!t)return"";let n=`@${t.split("@")[1]}`;return n==="@heimdall.dynatrace.com"?"heimdall":n==="@dynatrace.com"||n==="@ruxitlabs.com"?"internal":"external"}var Ri=(0,Fi.join)((0,at.homedir)(),".dt-app",".uuid"),C="TELEMETRY",H,vf=36,Gn,zn,zo,Di=!1,St;function bf(){return parseInt(process.env.DT_APP_DISABLE_TELEMETRY)===1}function Tf(e,t){p?.debug("Creating a new HTTP and HTTPS interceptor for tracing",C),[Xa.default,Qa.default].forEach(o=>{let r=o.request;o.request=function(){let i;try{arguments[0]instanceof Hn.URL?i=arguments[0]:typeof arguments[0]=="string"?i=new Hn.URL(arguments[0]):i=new Hn.URL(`${arguments[0].protocol}//${arguments[0].hostname}${arguments[0].path}`)}catch{return r.apply(null,arguments)}for(let l of t)if(l.startsWith(i.origin))return r.apply(null,arguments);p?.debug(`Tracing request ${i.toString()}`,C);let s=e.traceWebRequest(i.toString()),a=0;(arguments[0]instanceof Hn.URL||typeof arguments[0]=="string")&&(a=1),arguments[a]=arguments[a]??{},arguments[a].headers||(arguments[a].headers={}),arguments[a].headers[Pt.webRequestTagHeader]=s.getTag(),s.start();let c=r.apply(null,arguments);return c.once("response",l=>{s.stop(l.statusCode)}),c}})}async function B(e){if(bf()){p?.debug("Telemetry disabled",C);return}p?.debug("Initializing telemetry",C);let t=process.env.DT_APP_TELEMETRY_DEV_ENDPOINT==="1"?JSON.parse((0,Ot.readFileSync)((0,Fi.join)(__dirname,"cli","../../../src/utils/reporting/telemetry.dev.json"),"utf8")):{beaconEndpoint:"https://bf96767wvv.bf.dynatrace.com/mbeacon",applicationId:"4b1eddd3-a461-4e9b-9596-6d61a8a2e876"};if(p?.debug(`Using telemetry endpoint ${t.beaconEndpoint}`,C),Ja(),zn=await Ka(za()),Gn=new Pt.OpenKitBuilder(t.beaconEndpoint,t.applicationId,zn).withApplicationVersion(global.DT_APP_VERSION).withOperatingSystem((0,at.platform)()).withLogLevel(global.VERBOSE_MODE?Pt.LogLevel.Info:Pt.LogLevel.Error).build(),await new Promise(o=>{Gn.waitForInit(r=>{r&&(H=Gn.createSession(),Di=!0,Tf(H,[t.beaconEndpoint])),o(r)},3e4)})){p?.debug("Successfully initialized OpenKit",C),p?.debug(`Telemetry enabled: Session ID "${zn}"`,C),St={appId:e?.app?.id,appVersion:e?.app?.version,environmentUrl:e?.environmentUrl};try{let o="";if((0,Ot.existsSync)(Ri)){let i=(await(0,Jo.readFile)(Ri)).toString();if(i.length===vf&&(zo=i,H.identifyUser(i),p?.debug("Identification successful",C)),e?.oauth2File&&(0,Ot.existsSync)(e?.oauth2File)){let s=M(e.oauth2File),a=s?.app_token?.access_token||s?.toolkit_token?.access_token;if(a){let{email:c}=(0,ki.decode)(a);o=c}}}else if(e?.oauth2File&&(0,Ot.existsSync)(e.oauth2File)){let r=await qa(e.oauth2File);r?.userId&&(zo=r.userId,o=r.emailAddress,H.identifyUser(r.userId),(0,Jo.writeFile)(Ri,r.userId),p.debug("Created uuid file to identify user uniquely",C))}St={...St,userType:Pi(o)}}catch{p?.debug("Could not identify user uniquely",C)}}else p?.debug("Failed to initialize OpenKit, disabling telemetry",C)}async function j(e){if(!H)return;let t=H.enterAction(e);process.version.charAt(0)==="v"?t.reportValue("nodejs_version",process.version.substring(1)):t.reportValue("nodejs_version",process.version),t.reportValue("cli_version",global.DT_APP_VERSION),t.reportValue("operating_system",(0,at.platform)()),t.reportValue("operating_system_version",(0,at.version)());let n=await ee("npm --version");t.reportValue("npm_version",n.replace(` `,""));let o=await ee("git version");return t.reportValue("git_version",o.replace("git version ","")),t}async function Y(e,t,n){if(e)try{if(n==="deploy"||n==="publish"){let i=!!t.selfMonitoringAgent;e.reportValue("selfmon_enabled",`${i}`)}if(t.oauth2File&&(0,Ot.existsSync)(t.oauth2File)){let i=M(t.oauth2File),s=i?.app_token?.access_token||i?.toolkit_token?.access_token;if(s){let{email:a}=(0,ki.decode)(s);e.reportValue("userType",Pi(a))}}if(e.reportValue("app_id",t.appId),e.reportValue("app_version",t.appVersion),!t.environmentUrl.startsWith("http"))return;let{tenant:r}=Qt(t.environmentUrl);e.reportValue("tenant_id",r),t.environmentUrl.includes("dev")?e.reportValue("session_type","dev"):t.environmentUrl.includes("hardening")?e.reportValue("session_type","hardening"):e.reportValue("session_type","prod")}catch{p?.debug("Could not report additional action information",C)}}async function L(e,t){if(e)try{Object.entries(t)?.forEach(n=>{e.reportValue(`command_arg_${(0,Za.snakeCase)(n[0])}`,st(JSON.stringify(n[1])))})}catch{p?.debug("Could not report command args",C)}}function S(e,t){if(!Di||!H||!zn)return;let n=Oi(Ha(e.payload||{})),o=t?.environmentUrl||St?.environmentUrl||"",r=t?.app?.id||St.appId||"",i=t?.app?.version||St.appVersion||"",s=process.version.charAt(0)==="v"?process.version.substring(1):process.version,a=o?{tenantId:Qt(o).tenant,sessionType:Ya(o)}:{tenantId:"",sessionType:""},c={...zo&&{userId:zo},userType:St.userType||""},l={sessionId:zn.toString(),"event.type":`dt-app.${e["event.category"]}.${e.name}`,"event.category":e["event.category"],"event.provider":"dt-app",operatingSystemVersion:(0,at.version)(),nodejsVersion:s,appId:r,appVersion:i,cliVersion:global.DT_APP_VERSION,...a,...c,...n};H.sendBizEvent(l["event.type"],l)}var Go=e=>{let n=e.length;for(let o=e.length-1;o>=0;o--){let r=e.charCodeAt(o);r>127&&r<=2047?n++:r>2047&&r<=65535&&(n+=2),r>=56320&&r<=57343&&o--}return n>=14336};async function ec(e,t){if(!H)return;let n=H.enterAction(e),{icons:o,packages:r,...i}=t;if(o){let s={appId:i.appId,appVersion:i.appVersion,appCommand:i.appCommand,icons:o};Go(JSON.stringify(s))||H.sendBizEvent("designSystemIconsMetrics",s)}if(r){let s={appId:i.appId,appVersion:i.appVersion,appCommand:i.appCommand,packages:r};Go(JSON.stringify(s))||H.sendBizEvent("dynatracePackageVersions",s)}if(i)if(!Go(JSON.stringify(i)))H.sendBizEvent("designSystemComponentMetrics",i);else{for(i.incomplete=!0;Go(JSON.stringify(i));)delete i.components[Object.keys(i.components).pop()];H.sendBizEvent("designSystemComponentMetrics",i)}return n}async function k(){if(Gn)return p?.debug("Closing OpenKit connection",C),new Promise(e=>{Gn.shutdown(()=>{p?.debug("Successfully closed OpenKit connection",C),e()}),Di=!1})}function ie(e,t){return require.resolve(e,{paths:[t]})}var U=require("path"),wr=require("fs");var nc=require("path");var ct=require("path"),Rt=require("fs"),en=`The intended action name is not allowed. Names can only contain: - ASCII letters & numbers - underscore (_) - dot (.) - and hyphen (-) but they can only start with either underscore (_) or letters and cannot end with hyphen (-) or dot (.) `;function tn(e){return(0,ct.basename)(e,(0,ct.extname)(e))}function tc(e){(0,Rt.existsSync)(e)&&(0,Rt.rmSync)(e,{recursive:!0})}function De(e){(0,Rt.existsSync)(e)||(0,Rt.mkdirSync)(e)}function Te({name:e,suffix:t,allowNested:n=!0}){let{name:o,dir:r,base:i}=(0,ct.parse)(e),a=`${n?o:i}.${t}`;return n?(0,ct.join)(r,a):a}function nn(e,t){let n=e.split("/").filter(Boolean),o="../".repeat(n.length);return t.compilerOptions.typeRoots=t.compilerOptions.typeRoots.map(r=>o+r),t}function on(e){return/^[A-Za-z_][A-Za-z0-9_.-]*[^-.]$/.test(e)}function Ft(e,t){let n=(0,nc.join)(e,".dt-app",t);return De(n),n}var Ko=require("path");function F(){if(__filename.endsWith("bin.js"))return(0,Ko.resolve)(__dirname);if(__filename.endsWith("index.js"))return(0,Ko.resolve)(__dirname,"src");if(__filename.endsWith(".ts"))return(0,Ko.resolve)(__dirname,"..");throw new Error("Could not retrieve lib source folder!",{cause:257})}var Jn=()=>({name:"skip-css",setup(e){e.onResolve({filter:/\.css$/},({path:t})=>({path:t,external:!0,namespace:"skip-css"}))}});var vc=require("fs"),lt=T(require("fast-glob")),Me=require("path");function v(e,t){let o=(Array.isArray(e)?e:e.split(/[\/\\]/g)).map(r=>r?r.replace(/\\/g,"/"):"").join("/").replace(/\/\.\//g,"/").replace(/(?<!:)\/{2,}/g,"/").replace(/^.\//,"");return t?.keepFullPath?o:o.replace(/^([a-zA-Z]):/,"")}var Ce=require("path");function Kn(e,t){let n=Ce.posix.normalize(Ce.posix.join(t.split(Ce.win32.sep).join(Ce.posix.sep),"/")),o=new RegExp(`^.*?${n}`,"g"),r=Ce.posix.parse(e.split(Ce.win32.sep).join(Ce.posix.sep).replace(o,""));return new URL("http://localhost"+Ce.posix.normalize(Ce.posix.join("/",r.dir,r.name.replace(/\.function$/,"")))).pathname}var Yo=T(require("fs"));var Zo=require("path");var oc=T(require("path"));function rn(){return oc.default.resolve(F(),"utils","snippets")}var rc=T(require("fastify")),Ii=require("fs"),ic=T(require("ws"));function sc(e){let t={};e.https&&(t={https:{cert:(0,Ii.readFileSync)(e.https.cert),key:(0,Ii.readFileSync)(e.https.key)}});let n=(0,rc.default)({...t,bodyLimit:50*1048576});return n.removeAllContentTypeParsers(),n.addContentTypeParser("*",{parseAs:"buffer"},(o,r,i)=>{i(null,r)}),n}function ac({server:e}){return new ic.default.Server({server:e})}function cc(e){let t=e.https?"wss":"ws",n=e.host==="127.0.0.1"?"localhost":e.host;return`${t}://${n}:${e.port}`}function pc(){let e=(0,Zo.resolve)(rn(),"defaultIndex.snippet.html");return Yo.default.readFileSync(e).toString("utf-8")}function sn(e,t){let{transformSync:n}=require(ie("esbuild",t)),o=(0,Zo.resolve)(rn(),"sdkWebShim.snippet.ts"),r=Yo.default.readFileSync(o,"utf-8"),i={loader:"ts",define:{"process.env.INJECT":JSON.stringify(e)}};return n(r,i).code}function lc(e){let t=(0,Zo.resolve)(rn(),"selfmon_config.snippet.js");return Yo.default.readFileSync(t,"utf-8").replace("{{PLATFORM_PREFIX}}",e)}var qo;async function Xo(e){return qo||(qo=await(await A(e)).text(),qo)}function an(e){let t=jo(e.server.port),n=cc(e.server);return`window.socketUrl = '${t===""?n:t}';`}var dc=T(require("chalk"));var Cf=/(?<=(?:\||")cuc=).*?(?=\||")/g,Mi;function mc(e){let t;Mi?t=Mi:(t=Cf.exec(e),Mi=t);try{return t[0]}catch{throw new Error(`The self monitoring agent could not be retrieved, please check if ${dc.default.cyan`options.app.selfMonitoringAgent`} is configured to the correct url.`,{cause:263})}}async function uc(e){try{if(!e.includes("http"))return 3;let t=await A(e),n=t.status,r=t.headers.get("content-type")?.includes("javascript"),s=(await t.text()).includes("cuc=");return n===404||!r||!s?2:(await Xo(e),0)}catch{return 1}}var me=T(require("chalk"));var Ie={green:"#73be28",purple:"#6f2da8",blue:"#1496ff",limeGreen:"#b4dc00"};function _(e,t){t&&console.log(`${e} `),console.log(me.default.hex(Ie.green).bold(`${e} `))}function P(e){if(e){console.log(`════════ `);return}console.log(me.default.hex(Ie.blue).bold("══")+me.default.hex(Ie.limeGreen).bold("══")+me.default.hex(Ie.green).bold("══")+me.default.hex(Ie.purple).bold("══")+` `)}function x(e,t="white",n){if(n){process.stdout.write(e);return}process.stdout.write(se(e,t))}function cn(e,t="white",n){if(n){console.log(e);return}console.log(se(e,t))}function se(e,t="white"){return{white:me.default.white,blue:me.default.hex(Ie.blue),green:me.default.hex(Ie.green),purple:me.default.hex(Ie.purple),limeGreen:me.default.hex(Ie.limeGreen),gray:me.default.dim}[t](e)}function pn(e){let n=process.stdout.columns<=100?process.stdout.columns:100;if(e){console.log("─".repeat(n)+` `);return}console.log(me.default.hex(Ie.blue)("─".repeat(n))+` `)}function D(){console.log(` `)}function pt(e,t=""){let n=(o,r="")=>{let c="";return o.items?.forEach((l,d)=>{let m=d===o.items.length-1,u=m?"└─ ":"├─ ",g=m?" ":"│ ";c+=`${r}${u}${l.name} `,l.items?.length&&(c+=n(l,r+g))}),c};console.log(n(e,t))}function Qo(){console.log("")}function qn(e,t,n,o=!0){let r={};e.forEach(s=>{let c=s.split("/")[0];r[c]||(r[c]=[]),r[c].push(s)});let i={items:[]};return Object.keys(r).forEach(s=>{let a={name:s,items:[]};r[s].forEach(c=>{let l=c.split("/");if(l.shift(),l.length!==0)if(l.length===1){let d=l[0];a.items.push(d.endsWith("widget.tsx")?fc(d,t,n,o):gc(d,t,n))}else{let d=a;for(let u=0;u<l.length-1;u++){let g=l[u],f=d.items.find(y=>y.name===g&&Array.isArray(y.items));f||(f={name:g,items:[]},d.items.push(f)),d=f}let m=l[l.length-1];d.items.push(m.endsWith("widget.tsx")?fc(m,t,n,o):gc(m,t,n))}}),i.items.push(a)}),i}function fc(e,t,n,o){let r=[{name:`Local: ${t[e+"_local"]}`}];return o&&r.push({name:`Environment: ${t[e+"_environment"]}`}),{name:n[e],items:r}}function gc(e,t,n){return{name:`${n[e]}: ${t[e]}`}}var Ni=T(require("chalk")),Ee=require("path"),Yn=require("fs/promises");function Ke(e){return e.startsWith("../")?e:e.startsWith("./")?e.slice(1):e.startsWith("/")?e:"/"+e}var yc=T(require("fast-glob")),wc=require("fs"),hc={created:Ni.default.green`CREATED:`,updated:"UPDATED:",deleted:Ni.default.red`DELETED:`,copied:"COPIED:"};function kt(e){let t={},n={fileExists:o,throwIfFileDoesNotExist:r,getFile:i,getFilePathsByRegex:s,getFileMap:a,getFileName:c,setFile:l,setFiles:d,mapEsbuildOutputFiles:m,deleteFile:u,writeFileToDisc:g,writeFileMapToDisc:f,addAssetFiles:y,resetFileMap:b};return e&&d(e),n;function o(h){let O=Ke(h);return!!t[O]}function r(h){let O=Ke(h);if(!o(h))throw S({"event.category":"crash",name:"fileManager.setFile",payload:{error:`Failed to set file ${h} with fileManager.`}}),new Error(`File ${O} does not exist in fileMap!`)}function i(h){return h=Ke(v(h)),r(h),t[h]}function s(h){return Object.keys(t).filter(O=>O.match(h))}function a(){return t}function c(h){return h=Ke(v(h)),r(h),(0,Ee.basename)(h)}function l(h,O){h=Ke(v(h)),t[h]={content:O}}function d(h){for(let O in h)l(O,h[O].content)}function m(h,O,I="dist"){let Ge=v([O,"dist"]);return(h||[]).forEach(Fe=>{let ze=v(Fe.path),In=v([I,ze.replace(Ge,"")]),yi=Ke(In);t[yi]={content:Buffer.from(Fe.contents)}}),n}function u(h){h=Ke(v(h)),delete t[h]}async function g(h){h=Ke(v(h)),r(h),await(0,Yn.writeFile)((0,Ee.join)(h),t[h].content)}async function f(h){await Promise.all(Object.entries(t).map(async([O,{content:I,mode:Ge}])=>{let Fe=(Buffer.byteLength(I,"utf8")/Math.pow(2,10)).toFixed(2),ze=(0,Ee.join)(h,O);return p.debug(`${Ge!==void 0?hc[Ge]:hc.created} ${ze} ${`(${Fe} KB)`}`,"FILES"),await(0,Yn.mkdir)((0,Ee.dirname)(ze),{recursive:!0}),(0,Yn.writeFile)(ze,I)}))}async function y(h){for(let O of h.assetConfigs){let I=(0,Ee.isAbsolute)(O.input)?O.input:(0,Ee.join)(h.root,O.input),Ge=await(0,yc.default)(O.glob,{cwd:I,dot:!0,ignore:O.ignore});for(let Fe of Ge){let ze=v([h.distDir,O.output,Fe]);l(ze,(0,wc.readFileSync)((0,Ee.join)(I,Fe)))}}}function b(){t={}}}var W=kt();var qe="documents",tr="document-types";async function nr(e,t,n,o){let r=await Xo(t),i=o.startsWith("dynatrace.");if(!i){let s;try{s=mc(r)}catch(d){let m=d instanceof Error?d.message:String(d);p.error(m);return}let a=lc(s),c="./assets/agentConfig.js",l=v([n,c]);W.setFile(l,Buffer.from(a)),e.injectScript(c)}e.injectScript(t),i&&e.addInjectionMarker()}function te(e){if(!(0,vc.existsSync)((0,Me.join)(e.cwd,e.sourceRoot,"api")))return[];let t=e.includeJs?"{ts,js}":"ts";return(0,lt.sync)(v([e.sourceRoot,"api",`**/*.function.${t}`]),{cwd:e.cwd,ignore:["**/*.test.ts","**/*.spec.ts"]})}function bc(e){let t=te({cwd:e.cwd,sourceRoot:e.sourceRoot});if(!t.length)return;x("Available app functions served from '/api':","green"),D();let n={};t.forEach(i=>{n[i.split("/")[i.split("/").length-1]]=se(e.url+v(["/api",Kn(i,"api").replace(".resumable","")]),"gray")});let o=or(t,e.cwd),r=qn(t,n,o);pt(r)}async function Tc(e){let t=await(0,lt.default)(`${e.actionsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]}),n=await(0,lt.default)(`${e.actionsDir}/*.action.ts`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(n.length===0&&t.length===0)return;x("Available workflow actions:","green"),D();let o=or([...n,...t],e.cwd),r=Ef(e,n,t),i=qn([...n,...t],r,o);pt(i)}function Ef(e,t,n){let o={};return t.forEach(r=>{let i=er(r),s=(0,Me.basename)(r,".action.ts");o[i]=se(`${e.url}/api/${s.replace(".resumable","")}`,"gray")}),n.forEach(r=>{let i=er(r),s=(0,Me.basename)(r,".widget.tsx"),a=`${e.url}/widgets/actions/${s}`;o[`${i}_local`]=se(a,"gray"),o[`${i}_environment`]=se(xf(e.environmentUrl,a,e.locationAppIds),"gray")}),o}function er(e){let t=e.split("/");return t[t.length-1]}function xf(e,t,n){return`${e}/ui/apps/dynatrace.automations/dev-helper?src=${t}&locationAppIds=${n}`}async function dt(e,t){return(await(0,lt.default)(t,{cwd:e,ignore:["**/*.{test,spec}.ts","node_modules"]})).map(o=>(0,Me.join)(e,o))}async function Cc(e){let t=await(0,lt.default)(`${e.widgetSettingsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(t.length===0)return;x("Available settings widgets:","green"),D();let n={};t.forEach(i=>{let s=er(i),a=(0,Me.basename)(s,".widget.tsx"),c=`${e.url}/widgets/settings/${a}`;n[`${s}_local`]=se(c,"gray")});let o=or(t,e.cwd),r=qn(t,n,o,!1);pt(r)}async function Ec(e){let t=await(0,lt.default)(`${e.documentsDir}/*.*`,{cwd:e.cwd,onlyFiles:!0});if(!t.length)return;x("Available documents:","green"),D();let n={};t.forEach(i=>{let s=er(i),a=`${e.appId}.${(0,Me.basename)(i).split(".")[0]}`;n[s]=se(a,"gray")});let o=or(t,e.cwd),r=qn(t,n,o);pt(r)}function or(e,t){let n={};return e.forEach(o=>{let r=(0,Me.basename)(o);n[r]=Af((0,Me.join)(t,o),r)}),n}function Af(e,t){return process.platform==="win32"&&(e="/"+e.replace(/\\/g,"/").replace(/^\/+/,"")),`\x1B]8;;file://${e.replace(/\\/g,"/")}\x1B\\${t}\x1B]8;;\x1B\\`}var ir=require("lodash"),$i=require("micromatch"),Sc=require("fs"),mt=require("path");var xc=require("path");var _i;function ge(e){return _i||(_i=require(ie("typescript",e))),_i}function Ye(e,t){return{category:t,text:e.text,filePath:e.location?.file?(0,xc.resolve)(e.location.file):void 0,line:e.location?.line??1,column:(e.location?.column??0)+1}}function Ui(e,t){let n=ge(t),o=`TS${e.code}`,r=n.flattenDiagnosticMessageText(e.messageText,` `),i=e.category===n.DiagnosticCategory.Error?"Error":"Warning";if(e.file){let{line:s,character:a}=n.getLineAndCharacterOfPosition(e.file,e.start);return{code:o,category:i,text:r,filePath:e.file.fileName,column:a+1,line:s+1}}return{code:o,category:i,text:r,filePath:void 0,line:1,column:1}}var rr={noEmit:!0,skipLibCheck:!0};function Ac(e){let{ScriptTarget:t}=ge(e);return{ui:{target:t.ES2021,...rr},functions:{target:t.ESNext,...rr},actions:{target:t.ESNext,...rr},widgets:{target:t.ESNext,...rr}}}var sr=e=>({actions:`${e}/*.action.ts`,widgets:`${e}/*.widget.tsx`});function xe(e){let{createCompilerHost:t,createProgram:n}=ge(e.srcRoot),{tsConfigContents:o,tsConfigFileDiagnostics:r}=Sf(e.srcRoot,e.tsConfigFullPath);if(o.projectReferences&&o.projectReferences.length>0&&o.fileNames.length===0)return Of(e);let s={...o.options,...Ac(e.srcRoot)[e.buildType],incremental:!1},a=t(o.options),c=[],l=(0,$i.not)(e.entrypoints,o.raw.exclude).map(g=>(0,mt.isAbsolute)(g)?g:(0,mt.join)(e.srcRoot,g));if(o.options.composite)c=[...new Set([...l,...o.fileNames])];else{let g=o.fileNames.filter(y=>y.endsWith(".d.ts")),f=(0,$i.not)(g,o.raw.exclude).map(y=>(0,mt.isAbsolute)(y)?y:(0,mt.join)(e.srcRoot,y));c=[...new Set([...l,...f])]}let d=n({rootNames:c,options:s,host:a,configFileParsingDiagnostics:r,projectReferences:o.projectReferences}),m=d.emit();return[...d.getSyntacticDiagnostics(),...d.getSemanticDiagnostics(),...d.getConfigFileParsingDiagnostics(),...d.getGlobalDiagnostics(),...d.getDeclarationDiagnostics(),...m.diagnostics].map(g=>Ui(g,e.appRoot))}function Sf(e,t){let{sys:n,readConfigFile:o,parseJsonConfigFileContent:r}=ge(e),i=o(t,c=>(0,Sc.readFileSync)(c).toString()),s=[];i.error&&(0,ir.has)(i.error.file,"parseDiagnostics")&&(s=(0,ir.get)(i.error?.file,"parseDiagnostics"));let a=r(i.config,n,(0,mt.dirname)(t));return s.push(...a.errors),{tsConfigContents:a,tsConfigFileDiagnostics:s}}function Of(e){let{sys:t,createSolutionBuilderHost:n,createSolutionBuilder:o}=ge(e.srcRoot),r=[],i=n(t,void 0,a=>{r.push(a)},a=>{r.push(a)});return o(i,[e.tsConfigFullPath],{dry:!1,force:!1,verbose:!1}).build(),r.map(a=>Ui(a,e.appRoot))}function ar(e){return e.filter(t=>t.category==="Error"||!t.filePath||!t.filePath.includes("node_modules"))}function dn(e,t){return t?ar(e):e.filter(n=>n.category==="Error")}var Oc=require("@babel/code-frame"),he=require("chalk"),Pc=require("fs"),Rc=T(require("ansi-to-html"));var Pf=new Rc.default({});function ye(e){for(let t of e)p.info(Rf(t))}var Rf=e=>{let t=e.filePath?`${(0,he.cyan)(e.filePath)}:${(0,he.yellow)(e.line)}:${(0,he.yellow)(e.column)}`:"<no file>",n=e.category==="Error"?(0,he.red)("Error:"):(0,he.yellow)("Warning:"),o=e.code?(0,he.gray)(` ${e.code}`):"",r=`> ${t} - ${n}${o} ${e.text}`,i=(0,he.bold)(`${Fc(e)}`);return`${r} ${i}`},cr=e=>{try{return`<div class="dt-app-codesnippet" style="background-color:#15171B">${Pf.toHtml(Fc(e))}</div>`}catch(t){console.error(t)}return""},Fc=e=>{try{if(!e.filePath)return"";let t=(0,Pc.readFileSync)(e.filePath,"utf-8"),n=t==="",o={start:{line:e.line,column:n?1:e.column}};return(0,Oc.codeFrameColumns)(n?" ":t,o,{forceColor:!0})}catch(t){console.error(t)}return""};var kc=require("fs"),Ff="//# sourceMappingURL=data:application/json;base64,ewogICJtYXBwaW5ncyI6ICJBQUFBQSIsCiAgInNvdXJjZXMiOiBbIiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiIl0sCiAgIm5hbWVzIjogWyIiXSwKICAidmVyc2lvbiI6IDMsCiAgImZpbGUiOiAiIgp9",Ne=()=>({name:"excludeVendorFromSourceMap",setup(e){e.onLoad({filter:/node_modules/},t=>{if(t.path.endsWith(".js"))return{contents:`${(0,kc.readFileSync)(t.path,"utf8")} ${Ff}`,loader:"default"}})}});var Dc=e=>` import Widget from "${e.replace(".tsx","").replaceAll("\\","/")}"; import { _WidgetWrapper as WidgetWrapper } from '@dynatrace-sdk/automation-action-utils'; import { AppRoot } from '@dynatrace/strato-components-preview'; import React from 'react'; import { createRoot } from 'react-dom/client'; const WrappedWidget: React.FunctionComponent = WidgetWrapper(Widget); createRoot(document.getElementById('root')!).render( <AppRoot> <WrappedWidget /> </AppRoot> ); `,Ic=e=>` import { runner } from '@dynatrace-sdk/automation-action-utils/actions'; import action from '${e.replace(".ts","").replaceAll("\\","/")}'; export default async function (payload: unknown = undefined) { return runner(null, payload, action); } `;var It=require("path");var Mc={sourcemap:!1,includeVendorSourceMaps:!1},kf={sourcemap:!0,includeVendorSourceMaps:!0};function Xe(e){if(e.sourcemaps===void 0)return e.dev?kf:Mc;switch(e.sourcemaps){case!0:return{sourcemap:!0,includeVendorSourceMaps:!1};case!1:return{sourcemap:!1,includeVendorSourceMaps:!1};case"all":return{sourcemap:!0,includeVendorSourceMaps:!0};default:return Mc}}var Zn=require("path");var mn=require("path");var Bi=require("path"),pr=require("fs");function lr(e){return e.map(Df).filter(t=>!t.filePath?.includes("node_modules/"))}var Nc=e=>Ye(e,"Error"),Df=e=>Ye(e,"Warning");async function _c(e,t){let o=te({cwd:e.root,sourceRoot:e.build.sourceRoot}).length>0,r=(0,pr.existsSync)((0,Bi.join)(e.root,t));if(o&&!r)throw new Error(`Failed to build functions A tsconfig.json must exist, if function source files are present in the api directory. Please create a tsconfig.json file in the api directory, or delete the directory. ${(0,pr.readFileSync)((0,Bi.join)(F(),"function/template/tsconfig.json"),"utf-8")}: `,{cause:265});if(!o&&r)throw new Error(`Failed to build functions A tsconfig.json exists, but no functions were found in the api directory. Please create a function in the api directory, or delete the directory. You can create functions with the generate command: $ npm run generate:function `,{cause:265})}function _e(){return{sourcemap:!0,color:!0,loader:{".node":"empty"},bundle:!0,logLevel:"silent",charset:"utf8",write:!1}}async function Uc(e,t,n){let o=require(ie("esbuild",t.cwd));if(!o.context)throw new Error(`esbuild context function not found. This is likely happening because you may have dependencies in your project that are installing an older version of esbuild. Please fix your dependencies and try again. ${o.version?`Your current esbuild version being used is ${o.version}.`:""}`,{cause:258});let{context:r}=o,i=t.sourcemapOptions?.sourcemap??!1;i&&!t.sourcemapOptions?.includeVendorSourceMaps&&(t.plugins=[...t.plugins??[],Ne()]);let s=await r({..._e(),entryPoints:t.entryPoints.map(c=>(0,mn.isAbsolute)(c)?c:(0,mn.join)(t.cwd,c)),outbase:t.outbase,target:t.target,minify:t.minify??!1,sourcemap:i,platform:t.platform||"browser",plugins:t.plugins||[],external:t.external||[],sourceRoot:t.sourceRoot,tsconfig:(0,mn.isAbsolute)(t.tsconfig)?t.tsconfig:(0,mn.join)(t.cwd,t.tsconfig),outdir:e,format:t.format,globalName:t.globalName,metafile:t.metafile,write:!1,define:t.define});n?.addEventListener("abort",()=>s.cancel());let a=s.rebuild();try{return await a}finally{s.dispose()}}async function ji(e,t){let n=Date.now();try{let o=(0,Zn.join)(e.cwd,"dist"),r=await Uc(o,e,t),i=Date.now(),s=r.warnings.map(l=>Ye(l,"Warning")).filter(l=>!l.filePath?.includes("node_modules/")),a=e.outDir??"dist";return{fileMap:r.outputFiles.reduce((l,d)=>{let m=`${Zn.sep}${(0,Zn.join)(a,d.path.replace(o,""))}`;return{...l,[m]:{content:Buffer.from(d.contents)}}},{}),diagnostics:s,duration:i-n,metafile:r.metafile}}catch(o){let r=Date.now();if(If(o)){let s=[...o.errors.map(a=>Ye(a,"Error")),...o.warnings.map(a=>Ye(a,"Warning")).filter(a=>!a.filePath?.includes("node_modules/"))];return{fileMap:{},diagnostics:s,duration:r-n}}throw o instanceof Error?o:new Error(String(o),{cause:261})}}function If(e){return typeof e=="object"&&typeof e?.errors<"u"}var $c=require("path"),Bc=require("worker_threads");var un={actions:void 0,functions:void 0,ui:void 0,widgets:void 0};async function jc(){let e=["actions","functions","ui","widgets"];await Promise.all(e.map(t=>{let n=un[t];return n?(un[t]=void 0,n.terminate()):Promise.resolve()})),p.debug("All TypeScript workers terminated","TYPESCRIPT")}function Qe(e){if(un[e.buildType])return;let t=n=>{switch(n.type){case"initialized":p.debug(` ${n.payload} typescript worker thread has been initialized!`,"TYPESCRIPT");break;case"type-error":p.info(n.payload);break;case"send-biz-event":S({"event.category":"error",name:"ts-worker-error",payload:n.payload});break;case"entrypoints-changed":p.debug(`New amount of entrypoints for ${n.payload.buildType}: ${n.payload.entrypoints.length}`,`ENTRYPOINTS_WATCHER-${n.payload.event}`)}};un[e.buildType]=new Bc.Worker((0,$c.join)(F(),"ts-worker.js"),{workerData:e}),un[e.buildType].once("error",n=>{p.error(`TypeScript worker thread error: ${n}`),process.exit(1)}),un[e.buildType].on("message",n=>{t(n)})}var dr=["assert","assert/strict","buffer","console","crypto","events","http","https","path","path/posix","path/win32","perf_hooks","querystring","stream","stream/consumers","stream/promises","stream/web","string_decoder","timers","timers/promises","url","util","util/types","zlib","fs","fs/promises","process","node:fs","node:fs/promises","node:process","diagnostics_channel","node:assert","node:assert/strict","node:buffer","node:console","node:crypto","node:diagnostics_channel","node:events","node:http","node:https","node:path","node:path/posix","node:path/win32","node:perf_hooks","node:querystring","node:stream","node:stream/consumers","node:stream/promises","node:stream/web","node:string_decoder","node:timers","node:timers/promises","node:url","node:util","node:util/types","node:zlib"];function Lc(e){return(0,It.join)(e).split(It.sep).filter(n=>n).length>1}var Xn=require("node:path"),mr=require("fs"),Wc=require("inquirer");function ae(e){let{filePath:t}=Vc(e);return(0,mr.existsSync)(t)}function Vc({allowNested:e=!0,...t}){let n=t.suffix?Te({name:t.name,suffix:t.suffix,allowNested:e}):t.name,o="";return t.folder?o=(0,Xn.join)(t.cwd,t.folder,n):o=(0,Xn.join)(t.cwd,n),t.suffix||(n=(0,Xn.basename)(o)),{fileName:n,filePath:o}}async function Qn(e,t,n){if(ae(e))return!0;p.spinner.pause();let{fileName:r,filePath:i}=Vc(e),s;process.argv.includes("--non-interactive")?s=!0:s=await No(async()=>{let{createFile:c}=await(0,Wc.prompt)([{name:"createFile",type:"confirm",message:`${i} is missing${n?", and it is required":""}. Do you want to generate the file?`}]);return c}),p.spinner.resume();let a=JSON.stringify(t,null,2);if(!s&&n)throw new Error(`Failed to continue Please create a ${r} file in the ${i} directory. Example ${i}: ${a} `,{cause:E[n]});return s?((0,mr.writeFileSync)(i,a),p.log(`${i} created!`),!0):!1}var qi=require("chalk"),gn=require("http2"),ro=require("path");var Hc=require("url");async function ur({clientID:e,clientSecret:t,accountURN:n},o,r){if(!e||!t)throw new Error('"clientID" and "clientSecret" are required to fetch an automation token..',{cause:259});let i=new Hc.URLSearchParams;i.append("grant_type","client_credentials"),r&&i.append("scope",r.map(s=>s.name).join(" ")),i.append("client_id",e),i.append("client_secret",t),n&&i.append("resource",n);try{let s=await A(`${new URL(o).origin}/sso/oauth2/token`,{method:"POST",body:Buffer.from(i.toString()),headers:{"content-type":"application/x-www-form-urlencoded"}}),a=await s.json();if(s.ok)return a;throw Uo(JSON.stringify(a)??"Could not get token from authentication provider")}catch(s){let a=s,c=a.cause&&typeof a.cause!="number"?a.cause:a;throw p.debug(`Failed to get automation token! Backend responded with: ${c.message}`,"AUTH"),new Error(`${c.message}`,{cause:259})}}var zc=require("url");var Li=new Map;async function Gc(e){if(Li.has(e)){let r=Li.get(e);return p.debug(`Found resolved URL in cache: ${r.toString()}`,"HTTP(S)"),r}p.debug(`Execute GET request without allowing redirection to '${e}'`,"HTTP(S)");let t=await A(e,{redirect:"follow"}),n,o=t.headers.get("location");return o?n=new URL(o):n=new URL(t.url),p.debug(`Resolved URL is ${n.toString()}`,"HTTP(S)"),Li.set(e,n),n}async function Jc(e){try{let t=new zc.URL(e);t.pathname="platform/oauth2/authorization/dynatrace-sso",p.debug(`Retrieving SSO-URL for environment '${e}'`,"AUTH");let n=(await Gc(t.toString())).origin;return p.debug(`Using SSO-URL '${n}'`,"AUTH"),n}catch(t){let n=w(t);p.debug(`SSO-URL for '${e}' could not be processed.`,"AUTH"),p.debug(`Error: ${n.message}`,"AUTH"),$o(new Error(`SSO-URL for '${e}' could not be processed. ${n.message} If you need further assistance visit the connectivity troubleshooting guide here: https://dt-url.net/c4jp0s12`,{cause:258}),"DEC:DA")}}var gp=require("path"),hp=require("fs");var tp=T(require("fastify")),np=T(require("open")),op=require("mime-types"),rp=require("querystring");var eo=require("crypto"),fr=[{name:"app-engine:apps:run",comment:"cli-scope"}];function Kc(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Mf(e){return(0,eo.createHash)("sha256").update(e).digest()}var Wi=Kc((0,eo.randomBytes)(46)),qc=Kc(Mf(Wi)),Yc=(0,eo.randomBytes)(20).toString("hex");async function Zc(e,t,n,o){let r=new URL(e);r.pathname="/sso/oauth2/token",r.searchParams.append("grant_type","authorization_code"),r.searchParams.append("code",n),r.searchParams.append("client_id",t),r.searchParams.append("redirect_uri",o.toString()),r.searchParams.append("code_verifier",Wi);let i=await A(r.toString(),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"}});if(!i.ok)throw new Error(i.statusText,{cause:259});return await i.json()}async function Xc(e,t){if(fe){let n=`https://${Ct(e)}/auth/login`;return`${t}/platform-reserved/app-registry/v1/cde-auth?cde-uri=${encodeURIComponent(n)}`}return`http://localhost:${e}/auth/login`}var Hi=T(require("fs")),Vi;function Nf(){try{return Hi.default.statSync("/.dockerenv"),!0}catch{return!1}}function _f(){try{return Hi.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Qc(){return Vi===void 0&&(Vi=Nf()||_f()),Vi}var ip=require("@dynatrace/devkit");var ep=`<html> <head> <meta charset="utf-8" /> <title>dt-app - Dynatrace</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <style> @font-face { font-family: 'DynatraceFlow'; font-style: normal; font-weight: 400; font-display: swap; src: url(https://dt-cdn.net/fonts/DTFlow-Regular-v002.woff2) format('woff2'); } @font-face { font-family: 'DynatraceFlow'; font-style: normal; font-weight: 500; font-display: swap; src: url(https://dt-cdn.net/fonts/DTFlow-Medium-v002.woff2) format('woff2'); } @font-face { font-family: 'DynatraceFlow'; font-style: normal; font-weight: 600; font-display: swap; src: url(https://dt-cdn.net/fonts/DTFlow-Semibold-v002.woff2) format('woff2'); } :root { --bg-color: rgb(243, 243, 247); --line-color: #d2d3e1; --text-color: rgb(43, 42, 88); --text-link-color: rgb(69, 76, 201); --text-accent-color: rgb(244, 244, 251); --primary-color: rgb(71, 78, 207); --font-family: DynatraceFlow, Roboto, Helvetica, sans-serif; } @media (prefers-color-scheme: dark) { :root { --bg-color: rgb(25, 25,