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.
245 lines (212 loc) • 230 kB
JavaScript
#!/usr/bin/env node
"use strict";var tf=Object.create;var da=Object.defineProperty;var nf=Object.getOwnPropertyDescriptor;var rf=Object.getOwnPropertyNames;var of=Object.getPrototypeOf,sf=Object.prototype.hasOwnProperty;var af=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rf(t))!sf.call(e,o)&&o!==n&&da(e,o,{get:()=>t[o],enumerable:!(r=nf(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?tf(of(e)):{},af(t||!e||!e.__esModule?da(n,"default",{value:e,enumerable:!0}):n,e));var Ym=require("dotenv"),$n=require("path"),$r=require("fs"),la=require("os");var At=require("@dynatrace/openkit-js"),Ba=require("lodash"),Ct=require("fs"),Yr=require("fs/promises"),La=T(require("http")),Wa=T(require("https")),ot=require("os"),Mi=require("path"),zn=require("url");var te=require("chalk"),zt=require("lodash");var ce=require("fs"),ma=require("fs/promises"),Ur=require("path"),cf=new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}_log.txt/),ua=e=>(e>9?"":"0")+e,pf=e=>`${e.getFullYear()}-${ua(e.getMonth()+1)}-${ua(e.getDate())}_log.txt`,lf=e=>{try{let t=e.split("-");return new Date(Number(t[0]),Number(t[1]),Number(t[2].split("_")[0]))}catch{return}},xi=class{async setup(t){return Promise.resolve()}write(t){}getLogFile(){return""}},Ci=class{logFolder;logFile;stream;async setup(t){this.logFolder=(0,Ur.join)(t,".dt-app/logs"),(0,ce.existsSync)(this.logFolder)||(0,ce.mkdirSync)(this.logFolder,{recursive:!0}),await this.rotate()}async rotate(){if(this.logFile=(0,Ur.join)(this.logFolder,pf(new Date)),!(0,ce.existsSync)(this.logFile)){let t=(0,ce.readdirSync)(this.logFolder).map(n=>n.trim()).filter(n=>cf.test(n));if(t.length>=10){let n=t.map(r=>({path:r,date:lf(r)})).filter(r=>r.date).sort((r,o)=>r.date.getTime()-o.date.getTime())[0].path;(0,ma.unlink)((0,Ur.join)(this.logFolder,n))}(0,ce.closeSync)((0,ce.openSync)(this.logFile,"w"))}await new Promise(t=>{this.stream=(0,ce.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 fa(e){return wt=new Ci,wt.setup(e)}var wt=new xi;var ya=require("os");var Oi=T(require("ora"));var Ai=[],Gt=!1;function df(e){return new Promise((t,n)=>{Ai.push(async()=>{try{let r=await e();t(r)}catch(r){n(r)}}),uf()})}async function uf(){if(!Gt){for(Gt=!0;Ai.length>0;)await Ai.shift()();Gt=!1}}async function jr(e){return df(e)}var Bn=process.env.DT_APP_DEACTIVATE_SPINNER!=="true",Un={interval:80},Ge=[],bt="idle",Ln=(0,Oi.default)({spinner:{frames:[""],interval:Un.interval},isSilent:!Bn}),mf=()=>`
${Ge.map(e=>e.getFrame()).join(`
`)}`;function ff(){Ln.text=mf()}var jn;function gf(){Bn&&bt!=="running"&&!Gt&&(jn===void 0&&(jn=setInterval(ff,Un.interval)),Ln.start(),bt="running")}function ga(){bt==="running"&&(bt="paused",Ln.stop())}function ha(){bt==="paused"&&!Gt&&(bt="running",Ln.start())}function Pi(){bt="idle",Ln.stop(),Ge.forEach(e=>e.abort()),jn!==void 0&&(clearInterval(jn),jn=void 0)}var Br=class{spinner;constructor(t){this.spinner=(0,Oi.default)({...t,isSilent:!Bn})}get text(){return this.spinner.text}set text(t){this.spinner.text=t}cleanup(){let t=Ge.indexOf(this);t>-1&&(this.spinner.isSpinning&&this.spinner.stop(),Ge.splice(t,1)),Ge.length===0&&Pi()}getFrame(){return this.spinner.frame()}start(t){return t&&(this.text=t),Ge.includes(this)||Ge.push(this),gf(),this}_stop(t,n="abort"){switch(this.text=t??this.text,ga(),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(),ha(),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 Br({...e,interval:Un.interval}),start:(e,t={})=>new Br({...t,interval:Un.interval}).start(e),pause:ga,resume:ha,reset:Pi,successAll:e=>Ge.forEach(t=>t.succeed(e)),failAll:e=>Ge.forEach(t=>t.fail(e)),disable:()=>{Bn=!1,Pi()},enable:()=>{Bn=!0},getInterval:()=>Un.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 wa=`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 Si=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,te.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,te.green)(this._padString(t,0)),"INFO")}error(t){this._log((0,te.red)(this._padString(t,0)),"ERROR")}warn(t){let n=`
${(0,te.yellow)("Warning "+(0,zt.repeat)("─",this.warningBoxSize-8))}
${(0,te.yellow)(this._padString(t))}
${(0,te.yellow)((0,zt.repeat)("─",this.warningBoxSize))}
`;this._log(n,"WARNING")}logBox(t){if(this.disabled)return;let n=`
${(0,te.magenta)((0,zt.repeat)("─",this.boxSize))}
${(0,te.magenta)(this._padString(t))}
${(0,te.magenta)((0,zt.repeat)("─",this.boxSize))}
`;this._log(n,"INFO")}clean(){this.spinner.abort()}async initLogFile(t){this.disabled||await fa(t)}debounceTimeout;_log(t,n){this.disabled||(this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.spinner.pause(),n==="ERROR"?console.log(t):jr(()=>Promise.resolve(console.log(t))),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ke.getInterval()),this._printToFile(t,n))}_printToFile(t,n){wt.write(`${yf().toISOString()} ${n} ${hf(t)}
`)}_padString(t,n=2){return`${t}`.split(/[\n\r]/).map(r=>`${(0,zt.repeat)(" ",n)}${r}`).join(ya.EOL)}};function hf(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 yf(){let e=new Date,t=e.getTimezoneOffset()*6e4;return e.setTime(e.getTime()-t),e}var p=new Si;var ba=require("child_process"),wf=require("commander");function Y(e,t){let r={cwd:t||process.cwd(),maxBuffer:10485760};return new Promise((o,i)=>{(0,ba.exec)(e,r,(s,a,c)=>{s!==null?i(s):typeof c!="string"?i(c):o(a)})})}var Lr=process.env.CODESPACE_NAME&&process.env.CODESPACE_NAME.trim()!==""?process.env.CODESPACE_NAME:void 0;function va(e){if(!Lr)return;let t=process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN;return`${Lr}-${e}.${t}`}var Wn=process.env.GITPOD_WORKSPACE_URL&&process.env.GITPOD_WORKSPACE_URL.trim()!==""?process.env.GITPOD_WORKSPACE_URL:void 0;function Ta(e){if(!Wn)return;let t=new URL(Wn).hostname;return`${e}-${t}`}var ki=process.env.DT_APP_DEV_ENVIRONMENT_URL&&process.env.DT_APP_DEV_ENVIRONMENT_URL.trim()!==""?process.env.DT_APP_DEV_ENVIRONMENT_URL:void 0,me=Wn||Lr||ki;function vt(e){if(me)return ki?ki.replace(/^https?:\/\//,""):Wn?Ta(e):va(e)}function Wr(e){let t=vt(e);return t?`wss://${t.replace(/^https?:\/\//,"")}`:""}var Jt=require("undici");async function O(e,t){return(0,Jt.fetch)(e,t)}var Vn=require("path");var Ea=require("chalk"),Vr=(n=>(n.GENERIC_CLI_ERROR="DEC:D9",n.CONNECTION_ERROR="DEC:DA",n))(Vr||{}),E=(u=>(u[u.POSIX_SIGNAL_BASE=128]="POSIX_SIGNAL_BASE",u[u.UNCAUGHT=256]="UNCAUGHT",u[u.INTERNAL=257]="INTERNAL",u[u.USER=258]="USER",u[u.AUTH=259]="AUTH",u[u.TIMEOUT=260]="TIMEOUT",u[u.COMPILATION=261]="COMPILATION",u[u.NETWORKING=263]="NETWORKING",u[u.VALIDATION=264]="VALIDATION",u[u.BUILD=265]="BUILD",u[u.APP_GATEWAY_COMMUNICATION=266]="APP_GATEWAY_COMMUNICATION",u))(E||{}),Tf=`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 Hr(e){let t=[e,Tf];return new Error(t.filter(Boolean).join(`
`),{cause:259})}function xa(e){return e?e.replace(/\(|\)/g,"").split(" ").filter(Boolean).map(t=>t.includes(Vn.sep)?`${t.split(Vn.sep).pop()}`:t).join(" "):"No stacktrace is available for this error"}function rt(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(Vn.sep)?`${t.replace(/["']/g,"").split(Vn.sep).pop()}`:t).join(" ").substring(0,200).trim():""}function w(e){return e instanceof Error?e:new Error(String(e))}function Ca(e,t){throw new Error(`ERROR [${(0,Ea.green)(t)}]: ${e.message}`)}var Hn="/platform/app-engine/registry/v1",Ef="APP-REGISTRY";function Aa(e,t,n,r,o){let i=JSON.stringify(t,null,2),a=`${e}
HTTP ${n} ${r}
${t?.message??""}`+`
${xf(t,o)}`;return p.debug(`${a}${i}`,Ef),new Error(a,{cause:266})}function xf(e,t){return e?.details?.constraintViolations?e.details.constraintViolations.reduce((n,r)=>{let o=Cf(r,t);return`${n}
${o}`},""):""}function Cf(e,t){let{errorCode:n,errorCodeProperties:r,message:o}=e,i=o;if(n&&t){let s=r?.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=r?.availableVersion,l=r?.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 Gr(e){let t=["Error while connecting to the app registry",e];return new Error(t.filter(Boolean).join(`
`),{cause:266})}async function zr(e,t,n){try{let r=new URL(e);r.pathname=`${Hn}/apps/${n}`,r.searchParams.append("add-fields","manifest,resourceStatus.subResourceStatuses"),r.searchParams.append("latest-app-version","true");let o={headers:{authorization:`Bearer ${t}`}},i=await O(r.toString(),o);return await Af(i)===0?void 0:await i.json()}catch(r){throw Gr(w(r).message)}}async function Af(e){if(e.ok&&e.headers.get("content-type")?.includes("text/html"))return 1;if(!e.ok){if(e.status===403)throw Hr(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 Jr(e,t){try{let n=new URL(e),r={headers:{authorization:`Bearer ${t}`,"content-type":"application/octet-stream"}};n.pathname="/platform/metadata/v1/user";let o=await O(n.toString(),r);return!o.ok||o.headers.get("content-type")?.includes("text/html")?void 0:await o.json()}catch(n){throw Gr(w(n).message)}}async function Pa(e,t,n,r){try{let o=new URL(e);o.pathname=`${Hn}/apps`;let i=await O(o.toString(),{method:"POST",body:t,headers:{authorization:`Bearer ${n}`,"content-type":"application/zip"}});if(!i.ok){let s=await i.json();return Aa("Failed to install the app",s.error,i.status,i.statusText,r)}}catch(o){return Gr(w(o).message)}}async function Oa(e,t,n){try{let r=new URL(e);r.pathname=`${Hn}/apps/${t}`;let o=await O(r.toString(),{method:"DELETE",headers:{authorization:`Bearer ${n}`}});if(!o.ok){let i=await o.json();return Aa("Failed to uninstall the app",i.error,o.status,o.statusText)}}catch(r){return Gr(w(r).message)}}async function Sa(e,t){let n=await O(`${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 Kt(e){let t=new URL(e),[n,...r]=t.hostname.split(".");if(!r||r.length<1)throw new Error(`Invalid environment URL: "${e}"`,{cause:258});return{tenant:n,hostname:r.join(".")}}async function Pf(e,t,n,r){let o=await Sa(e,n),i=[3e3,3001,3002,3003,3004,3005,3e4,30001,30002,30003,30004,30005],s=i.flatMap(g=>me?[`https://${vt(g)}`]:[`http://localhost:${g}`,`https://localhost:${g}`]),a=i.flatMap(g=>me?[Wr(g)]:[`ws://localhost:${g}`,`wss://localhost:${g}`]),c={"script-src":["'unsafe-eval'",...s,...t.map(g=>`'sha256-${g}'`)],"connect-src":[...s,...a],"frame-ancestors":s},{tenant:l,hostname:d}=Kt(e),u=g=>g.replaceAll("{tenantId}",l).replaceAll("{hostname}",d),m={},f=[...Object.keys(o),...Object.keys(c)];for(let g of f){let y=new Set;for(let b of o[g]??[])y.add(u(b));for(let b of c[g]??[])y.add(u(b));m[g]=Array.from(y)}return m["frame-src"]=["*"],m["frame-ancestors"]=["*"],r&&Object.entries(r).forEach(([g,y])=>{m[g]?m[g].push(...y.map(b=>b.value)):m[g]=y.map(b=>b.value)}),Of(m)}function Of(e){return Object.entries(e).map(([t,n])=>`${t} ${n.join(" ")}`).join("; ")}var ka=new Map;async function Ra(e,t,n,r){let o=`${e}-${t.join(",")}-${r}`,i=ka.get(o);if(i)return i;let s=await Pf(e,t,n,r);return ka.set(o,s),s}var qt=require("fs");function M(e){if(!(0,qt.existsSync)(e)&&!(0,qt.lstatSync)(e,{throwIfNoEntry:!1})?.isFile())throw new Error(`[read-json.ts] File does not exist: ${e}`,{cause:257});let t=(0,qt.readFileSync)(e,"utf-8");return JSON.parse(t)}var Ni=require("jsonwebtoken");var Fa=require("path"),Da=require("os"),Et=require("fs"),Gn=require("fs/promises");var Tt=(0,Fa.join)((0,Da.homedir)(),".dt-app",".session"),Sf=19;function Ia(e){return e instanceof Error?{error:{name:e.name,message:e.message,stack:e.stack,cause:e.cause}}:e}function Fi(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ma(n)]))}function Ma(e){return e==null?e:Array.isArray(e)?e.map(t=>Ma(t)):typeof e=="object"?Fi(e):typeof e=="string"?rt(e):e}function Na(){return Math.floor(Math.random()*Math.pow(10,18))}function kf(e){return e!==""&&e.length<=Sf&&Number.isInteger(Number(e))}function _a(){try{if(!(0,Et.existsSync)(Tt))return;let e=(0,Et.statSync)(Tt).birthtime;Rf(e)&&(0,Et.unlinkSync)(Tt)}catch{p?.debug("Could not identify user uniquely",x)}}function Rf(e){return(new Date().getTime()-e.getTime())/(1e3*3600)>=24}async function $a(e){try{if((0,Et.existsSync)(Tt)){let n=(await(0,Gn.readFile)(Tt)).toString();kf(n)?e=Number(n):await(0,Gn.writeFile)(Tt,e.toString())}else await(0,Gn.writeFile)(Tt,e.toString())}catch(t){console.error("Error initializing session file:",t)}return e}async function Ua(e){let t=M(e),n=t?.app_token?.access_token||t?.toolkit_token?.access_token;if(n)return Jr(t.app_token?.environment_url||t.toolkit_token?.environment_url||"",n)}function _(e){return e.reduce((t,n,r,o)=>{if(n.startsWith("--")){let i=n.slice(2),s=o[r+1];s&&!s.startsWith("--")?t[i]=rt(s):t[i]=!0}return t},{})}function ja(e){return e.includes("dev")?"dev":e.includes("hardening")?"hardening":"prod"}function Di(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 Ii=(0,Mi.join)((0,ot.homedir)(),".dt-app",".uuid"),x="TELEMETRY",Ff=36,Yt=process.env.NODE_ENV==="test";function Va(){if(process.env.DT_APP_FORCE_TELEMETRY){Yt=!1;return}Yt=process.env.NODE_ENV==="test"||parseInt(process.env.DT_APP_DISABLE_TELEMETRY)===1}var Jn,H,Kn,qr,_i=!1,xt;function Df(e,t){p?.debug("Creating a new HTTP and HTTPS interceptor for tracing",x),[La.default,Wa.default].forEach(r=>{let o=r.request;r.request=function(){let i;try{arguments[0]instanceof zn.URL?i=arguments[0]:typeof arguments[0]=="string"?i=new zn.URL(arguments[0]):i=new zn.URL(`${arguments[0].protocol}//${arguments[0].hostname}${arguments[0].path}`)}catch{return o.apply(null,arguments)}for(let l of t)if(l.startsWith(i.origin))return o.apply(null,arguments);p?.debug(`Tracing request ${i.toString()}`,x);let s=e.traceWebRequest(i.toString()),a=0;(arguments[0]instanceof zn.URL||typeof arguments[0]=="string")&&(a=1),arguments[a]=arguments[a]??{},arguments[a].headers||(arguments[a].headers={}),arguments[a].headers[At.webRequestTagHeader]=s.getTag(),s.start();let c=o.apply(null,arguments);return c.once("response",l=>{s.stop(l.statusCode)}),c}})}async function $(e){if(Yt){p?.debug("Telemetry disabled",x);return}let t=process.env.DT_APP_TELEMETRY_DEV_ENDPOINT==="1"?JSON.parse((0,Ct.readFileSync)((0,Mi.join)(__dirname,"cli","../../../src/utils/reporting/telemetry.dev.json"),"utf8")):{beaconEndpoint:"https://bf96767wvv.bf.dynatrace.com/mbeacon",applicationId:"4b1eddd3-a461-4e9b-9596-6d61a8a2e876"};if(_a(),Kn=await $a(Na()),Jn=new At.OpenKitBuilder(t.beaconEndpoint,t.applicationId,Kn).withApplicationVersion(global.DT_APP_VERSION).withOperatingSystem((0,ot.platform)()).withLogLevel(global.VERBOSE_MODE?At.LogLevel.Info:At.LogLevel.Error).build(),await new Promise(r=>{Jn.waitForInit(o=>{o&&(H=Jn.createSession(),_i=!0,Df(H,[t.beaconEndpoint])),r(o)},3e4)})){p?.debug("Successfully initialized OpenKit",x),p?.debug(`Telemetry enabled: Session ID "${Kn}"`,x),xt={appId:e?.app?.id,appVersion:e?.app?.version,environmentUrl:e?.environmentUrl};try{let r="";if((0,Ct.existsSync)(Ii)){let i=(await(0,Yr.readFile)(Ii)).toString();if(i.length===Ff&&(qr=i,H.identifyUser(i),p?.debug("Identification successful",x)),e?.oauth2File&&(0,Ct.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,Ni.decode)(a);r=c}}}else if(e?.oauth2File&&(0,Ct.existsSync)(e.oauth2File)){let o=await Ua(e.oauth2File);o?.userId&&(qr=o.userId,r=o.emailAddress,H.identifyUser(o.userId),(0,Yr.writeFile)(Ii,o.userId),p.debug("Created uuid file to identify user uniquely",x))}xt={...xt,userType:Di(r)}}catch{p?.debug("Could not identify user uniquely",x)}}else p?.debug("Failed to initialize OpenKit, disabling telemetry",x)}async function U(e){if(!H)return;let t=H.enterAction(e);if(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,ot.platform)()),t.reportValue("operating_system_version",(0,ot.version)()),Yt)t.reportValue("yarn_version","test");else try{let n=await Y("yarn --version");t.reportValue("yarn_version",n)}catch{}if(Yt)t.reportValue("npm_version","test");else try{let n=await Y("npm --version");t.reportValue("npm_version",n.replace(`
`,""))}catch{}if(Yt)t.reportValue("git_version","test");else try{let n=await Y("git version");t.reportValue("git_version",n.replace("git version ",""))}catch{}return t}async function Z(e,t,n){if(e)try{if(n==="deploy"||n==="publish"){let i=!!t.selfMonitoringAgent;e.reportValue("selfmon_enabled",`${i}`)}if(t.oauth2File&&(0,Ct.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,Ni.decode)(s);e.reportValue("userType",Di(a))}}if(e.reportValue("app_id",t.appId),e.reportValue("app_version",t.appVersion),!t.environmentUrl.startsWith("http"))return;let{tenant:o}=Kt(t.environmentUrl);e.reportValue("tenant_id",o),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",x)}}async function j(e,t){if(e)try{Object.entries(t)?.forEach(n=>{e.reportValue(`command_arg_${(0,Ba.snakeCase)(n[0])}`,rt(JSON.stringify(n[1])))})}catch{p?.debug("Could not report command args",x)}}function P(e,t){if(!_i||!H||!Kn)return;let n=Fi(Ia(e.payload||{})),r=t?.environmentUrl||xt?.environmentUrl||"",o=t?.app?.id||xt.appId||"",i=t?.app?.version||xt.appVersion||"",s=process.version.charAt(0)==="v"?process.version.substring(1):process.version,a=r?{tenantId:Kt(r).tenant,sessionType:ja(r)}:{tenantId:"",sessionType:""},c={...qr&&{userId:qr},userType:xt.userType||""},l={sessionId:Kn.toString(),"event.type":`dt-app.${e["event.category"]}.${e.name}`,"event.category":e["event.category"],"event.provider":"dt-app",operatingSystemVersion:(0,ot.version)(),nodejsVersion:s,appId:o,appVersion:i,cliVersion:global.DT_APP_VERSION,...a,...c,...n};H.sendBizEvent(l["event.type"],l)}var Kr=e=>{let n=e.length;for(let r=e.length-1;r>=0;r--){let o=e.charCodeAt(r);o>127&&o<=2047?n++:o>2047&&o<=65535&&(n+=2),o>=56320&&o<=57343&&r--}return n>=14336};async function Ha(e,t){if(!H)return;let n=H.enterAction(e),{icons:r,packages:o,...i}=t;if(r){let s={appId:i.appId,appVersion:i.appVersion,appCommand:i.appCommand,icons:r};Kr(JSON.stringify(s))||H.sendBizEvent("designSystemIconsMetrics",s)}if(o){let s={appId:i.appId,appVersion:i.appVersion,appCommand:i.appCommand,packages:o};Kr(JSON.stringify(s))||H.sendBizEvent("dynatracePackageVersions",s)}if(i)if(!Kr(JSON.stringify(i)))H.sendBizEvent("designSystemComponentMetrics",i);else{for(i.incomplete=!0;Kr(JSON.stringify(i));)delete i.components[Object.keys(i.components).pop()];H.sendBizEvent("designSystemComponentMetrics",i)}return n}async function F(){if(Jn)return p?.debug("Closing OpenKit connection",x),new Promise(e=>{Jn.shutdown(()=>{p?.debug("Successfully closed OpenKit connection",x),e()}),_i=!1})}var Zt=require("fs"),qn=require("os"),Ga=require("path"),$i=(0,Ga.join)((0,qn.homedir)(),".dt-app","history"),Pt,za="◬";function Ja(){Ka();let e=process.argv.slice(1);if(!(e.length<1)){e[0].endsWith(".js")&&(e=e.slice(1));try{(0,Zt.appendFileSync)($i,`${e.join(" ")}${za}${qn.EOL}`)}catch{}}}function Ka(){Pt||(Pt=(0,Zt.existsSync)($i)?(0,Zt.readFileSync)($i,"utf-8").split(qn.EOL):[],Pt.length>0&&Pt[Pt.length-1]===""&&Pt.pop())}function If(){return Ka(),Pt??[]}function qa(){let e=If();if(e.length===0)return{command:"(none)"};let t=e[e.length-1],[n]=t.split(za);return{command:n}}var Ya=require("child_process"),Za=require("semver");function Xa(e){let{engines:t}=e;if(t){for(let[n,r]of Object.entries(t))if(n==="node"||n==="npm"){let o=(0,Ya.execSync)(`${n} --version`).toString();if(!(0,Za.satisfies)(o,r))throw new Error(`Your ${n} version does not satisfy the version requirements of ${r}, installed: ${o}`,{cause:258})}}}var Mf="%";function Qa(){let e=process.argv.indexOf("--verbose");if(e<0)return;let t=process.argv[e+1],n=!t||t.startsWith("-")?Mf:t;global.VERBOSE_MODE=n}function Zr(){console.log(`${global.DT_APP_VERSION}`)}function ec(...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 nt=require("commander");var Os=require("path"),xn=require("commander");function ne(e,t){return require.resolve(e,{paths:[t]})}var W=require("path"),Po=require("fs");var nc=require("path");var it=require("path"),Ot=require("fs"),Xt=`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 Qt(e){return(0,it.basename)(e,(0,it.extname)(e))}function tc(e){(0,Ot.existsSync)(e)&&(0,Ot.rmSync)(e,{recursive:!0})}function st(e){(0,Ot.existsSync)(e)||(0,Ot.mkdirSync)(e)}function Ee({name:e,suffix:t,allowNested:n=!0}){let{name:r,dir:o,base:i}=(0,it.parse)(e),a=`${n?r:i}.${t}`;return n?(0,it.join)(o,a):a}function en(e,t){let n=e.split("/").filter(Boolean),r="../".repeat(n.length);return t.compilerOptions.typeRoots=t.compilerOptions.typeRoots.map(o=>r+o),t}function tn(e){return/^[A-Za-z_][A-Za-z0-9_.-]*[^-.]$/.test(e)}function St(e,t){let n=(0,nc.join)(e,".dt-app",t);return st(n),n}var Xr=require("path");function R(){if(__filename.endsWith("bin.js"))return(0,Xr.resolve)(__dirname);if(__filename.endsWith("index.js"))return(0,Xr.resolve)(__dirname,"src");if(__filename.endsWith(".ts"))return(0,Xr.resolve)(__dirname,"..");throw new Error("Could not retrieve lib source folder!",{cause:257})}var Yn=()=>({name:"skip-css",setup(e){e.onResolve({filter:/\.css$/},({path:t})=>({path:t,external:!0,namespace:"skip-css"}))}});var bc=require("fs"),ct=T(require("fast-glob")),Fe=require("path");function v(e,t){let r=(Array.isArray(e)?e:e.split(/[\/\\]/g)).map(o=>o?o.replace(/\\/g,"/"):"").join("/").replace(/\/\.\//g,"/").replace(/(?<!:)\/{2,}/g,"/").replace(/^.\//,"");return t?.keepFullPath?r:r.replace(/^([a-zA-Z]):/,"")}var xe=require("path");function Zn(e,t){let n=xe.posix.normalize(xe.posix.join(t.split(xe.win32.sep).join(xe.posix.sep),"/")),r=new RegExp(`^.*?${n}`,"g"),o=xe.posix.parse(e.split(xe.win32.sep).join(xe.posix.sep).replace(r,""));return new URL("http://localhost"+xe.posix.normalize(xe.posix.join("/",o.dir,o.name.replace(/\.function$/,"")))).pathname}var eo=T(require("fs"));var to=require("path");var rc=T(require("path"));function nn(){return rc.default.resolve(R(),"utils","snippets")}var oc=T(require("fastify")),Ui=require("fs"),ic=T(require("ws"));function sc(e){let t={};e.https&&(t={https:{cert:(0,Ui.readFileSync)(e.https.cert),key:(0,Ui.readFileSync)(e.https.key)}});let n=(0,oc.default)({...t,bodyLimit:50*1048576});return n.removeAllContentTypeParsers(),n.addContentTypeParser("*",{parseAs:"buffer"},(r,o,i)=>{i(null,o)}),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,to.resolve)(nn(),"defaultIndex.snippet.html");return eo.default.readFileSync(e).toString("utf-8")}function rn(e,t){let{transformSync:n}=require(ne("esbuild",t)),r=(0,to.resolve)(nn(),"sdkWebShim.snippet.ts"),o=eo.default.readFileSync(r,"utf-8"),i={loader:"ts",define:{"process.env.INJECT":JSON.stringify(e)}};return n(o,i).code}function lc(e){let t=(0,to.resolve)(nn(),"selfmon_config.snippet.js");return eo.default.readFileSync(t,"utf-8").replace("{{PLATFORM_PREFIX}}",e)}var Qr;async function no(e){return Qr||(Qr=await(await O(e)).text(),Qr)}function on(e){let t=Wr(e.server.port),n=cc(e.server);return`window.socketUrl = '${t===""?n:t}';`}var dc=T(require("chalk"));var Nf=/(?<=(?:\||")cuc=).*?(?=\||")/g,ji;function uc(e){let t;ji?t=ji:(t=Nf.exec(e),ji=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 mc(e){try{if(!e.includes("http"))return 3;let t=await O(e),n=t.status,o=t.headers.get("content-type")?.includes("javascript"),s=(await t.text()).includes("cuc=");return n===404||!o||!s?2:(await no(e),0)}catch{return 1}}var pe=T(require("chalk"));var Re={green:"#73be28",purple:"#6f2da8",blue:"#1496ff",limeGreen:"#b4dc00"};function N(e,t){t&&console.log(`${e}
`),console.log(pe.default.hex(Re.green).bold(`${e}
`))}function S(e){if(e){console.log(`════════
`);return}console.log(pe.default.hex(Re.blue).bold("══")+pe.default.hex(Re.limeGreen).bold("══")+pe.default.hex(Re.green).bold("══")+pe.default.hex(Re.purple).bold("══")+`
`)}function A(e,t="white",n){if(n){process.stdout.write(e);return}process.stdout.write(re(e,t))}function sn(e,t="white",n){if(n){console.log(e);return}console.log(re(e,t))}function re(e,t="white"){return{white:pe.default.white,blue:pe.default.hex(Re.blue),green:pe.default.hex(Re.green),purple:pe.default.hex(Re.purple),limeGreen:pe.default.hex(Re.limeGreen),gray:pe.default.dim}[t](e)}function an(e){let n=process.stdout.columns<=100?process.stdout.columns:100;if(e){console.log("─".repeat(n)+`
`);return}console.log(pe.default.hex(Re.blue)("─".repeat(n))+`
`)}function D(){console.log(`
`)}function at(e,t=""){let n=(r,o="")=>{let i="│ ",s="├─ ",a="└─ ",c="";return r.items?.forEach((l,d)=>{let u=d===r.items.length-1,m=u?a:s,f=u?" ":i;c+=`${o}${m}${l.name}
`,l.items?.length&&(c+=n(l,o+f))}),c};console.log(n(e,t))}function ro(){console.log("")}function Xn(e,t,n,r=!0){let o={};e.forEach(s=>{let c=s.split("/")[0];o[c]||(o[c]=[]),o[c].push(s)});let i={items:[]};return Object.keys(o).forEach(s=>{let a={name:s,items:[]};o[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,r):gc(d,t,n))}else{let d=a;for(let m=0;m<l.length-1;m++){let f=l[m],g=d.items.find(y=>y.name===f&&Array.isArray(y.items));g||(g={name:f,items:[]},d.items.push(g)),d=g}let u=l[l.length-1];d.items.push(u.endsWith("widget.tsx")?fc(u,t,n,r):gc(u,t,n))}}),i.items.push(a)}),i}function fc(e,t,n,r){let o=[{name:`Local: ${t[e+"_local"]}`}];return r&&o.push({name:`Environment: ${t[e+"_environment"]}`}),{name:n[e],items:o}}function gc(e,t,n){return{name:`${n[e]}: ${t[e]}`}}var Bi=T(require("chalk")),Ce=require("path"),Qn=require("fs/promises");function ze(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:Bi.default.green`CREATED:`,updated:"UPDATED:",deleted:Bi.default.red`DELETED:`,copied:"COPIED:"};function kt(e){let t={},n={fileExists:r,throwIfFileDoesNotExist:o,getFile:i,getFilePathsByRegex:s,getFileMap:a,getFileName:c,setFile:l,setFiles:d,mapEsbuildOutputFiles:u,deleteFile:m,writeFileToDisc:f,writeFileMapToDisc:g,addAssetFiles:y,resetFileMap:b};return e&&d(e),n;function r(h){let C=ze(h);return!!t[C]}function o(h){let C=ze(h);if(!r(h))throw P({"event.category":"crash",name:"fileManager.setFile",payload:{error:`Failed to set file ${h} with fileManager.`}}),new Error(`File ${C} does not exist in fileMap!`)}function i(h){return h=ze(v(h)),o(h),t[h]}function s(h){return Object.keys(t).filter(C=>C.match(h))}function a(){return t}function c(h){return h=ze(v(h)),o(h),(0,Ce.basename)(h)}function l(h,C){h=ze(v(h)),t[h]={content:C}}function d(h){for(let C in h)l(C,h[C].content)}function u(h,C,q="dist"){let ve=v([C,"dist"]);return(h||[]).forEach(He=>{let Te=v(He.path),Ti=v([q,Te.replace(ve,"")]),Ei=ze(Ti);t[Ei]={content:Buffer.from(He.contents)}}),n}function m(h){h=ze(v(h)),delete t[h]}async function f(h){h=ze(v(h)),o(h),await(0,Qn.writeFile)((0,Ce.join)(h),t[h].content)}async function g(h){await Promise.all(Object.entries(t).map(async([C,{content:q,mode:ve}])=>{let He=(Buffer.byteLength(q,"utf8")/Math.pow(2,10)).toFixed(2),Te=(0,Ce.join)(h,C);return p.debug(`${ve!==void 0?hc[ve]:hc.created} ${Te} ${`(${He} KB)`}`,"FILES"),await(0,Qn.mkdir)((0,Ce.dirname)(Te),{recursive:!0}),(0,Qn.writeFile)(Te,q)}))}async function y(h){for(let C of h.assetConfigs){let q=(0,Ce.isAbsolute)(C.input)?C.input:(0,Ce.join)(h.root,C.input),ve=await(0,yc.default)(C.glob,{cwd:q,dot:!0,ignore:C.ignore});for(let He of ve){let Te=v([h.distDir,C.output,He]);l(Te,(0,wc.readFileSync)((0,Ce.join)(q,He)))}}}function b(){t={}}}var B=kt();var Je="documents",io="document-types";async function so(e,t,n,r){let o=await no(t);if(!r.startsWith("dynatrace.")){let i;try{i=uc(o)}catch(l){let d=l instanceof Error?l.message:String(l);p.error(d);return}let s=lc(i),a="./assets/agentConfig.js",c=v([n,a]);B.setFile(c,Buffer.from(s)),e.injectScript(a)}e.injectScript(t)}function fe(e){return(0,bc.existsSync)((0,Fe.join)(e.cwd,e.functionsFolder))?(0,ct.sync)(v([e.functionsFolder,e.glob]),{cwd:e.cwd}):[]}function vc(e){let t=fe({cwd:e.cwd,functionsFolder:e.functionsDir,glob:e.glob});if(!t.length)return;A("Available app functions served from '/api':","green"),D();let n={};t.forEach(i=>{n[i.split("/")[i.split("/").length-1]]=re(e.url+v(["/api",Zn(i,e.functionsDir)]),"gray")});let r=ao(t,e.cwd),o=Xn(t,n,r);at(o)}async function Tc(e){let t=await(0,ct.default)(`${e.actionsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]}),n=await(0,ct.default)(`${e.actionsDir}/*.action.ts`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(n.length===0&&t.length===0)return;A("Available workflow actions:","green"),D();let r=ao([...n,...t],e.cwd),o=_f(e,n,t),i=Xn([...n,...t],o,r);at(i)}function _f(e,t,n){let r={};return t.forEach(o=>{let i=oo(o),s=(0,Fe.basename)(o,".action.ts");r[i]=re(`${e.url}/api/${s}`,"gray")}),n.forEach(o=>{let i=oo(o),s=(0,Fe.basename)(o,".widget.tsx"),a=`${e.url}/widgets/actions/${s}`;r[`${i}_local`]=re(a,"gray"),r[`${i}_environment`]=re($f(e.environmentUrl,a,e.locationAppIds),"gray")}),r}function oo(e){let t=e.split("/");return t[t.length-1]}function $f(e,t,n){return`${e}/ui/apps/dynatrace.automations/dev-helper?src=${t}&locationAppIds=${n}`}async function pn(e,t){return(await(0,ct.default)(t,{cwd:e,ignore:["**/*.{test,spec}.ts","node_modules"]})).map(r=>(0,Fe.join)(e,r))}async function Ec(e){let t=await(0,ct.default)(`${e.widgetSettingsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(t.length===0)return;A("Available settings widgets:","green"),D();let n={};t.forEach(i=>{let s=oo(i),a=(0,Fe.basename)(s,".widget.tsx"),c=`${e.url}/widgets/settings/${a}`;n[`${s}_local`]=re(c,"gray")});let r=ao(t,e.cwd),o=Xn(t,n,r,!1);at(o)}async function xc(e){let t=await(0,ct.default)(`${e.documentsDir}/*.*`,{cwd:e.cwd,onlyFiles:!0});if(!t.length)return;A("Available documents:","green"),D();let n={};t.forEach(i=>{let s=oo(i),a=`${e.appId}.${(0,Fe.basename)(i).split(".")[0]}`;n[s]=re(a,"gray")});let r=ao(t,e.cwd),o=Xn(t,n,r);at(o)}function ao(e,t){let n={};return e.forEach(r=>{let o=(0,Fe.basename)(r);n[o]=Uf((0,Fe.join)(t,r),o)}),n}function Uf(e,t){return process.platform==="win32"&&(e="/"+e.replace(/\\/g,"/").replace(/^\/+/,"")),`\x1B]8;;file://${e.replace(/\\/g,"/")}\x1B\\${t}\x1B]8;;\x1B\\`}var po=require("lodash"),Wi=require("micromatch"),Oc=require("fs"),pt=require("path");var Cc=require("path");var Li;function le(e){return Li||(Li=require(ne("typescript",e))),Li}function Ke(e,t){return{category:t,text:e.text,filePath:e.location?.file?(0,Cc.resolve)(e.location.file):void 0,line:e.location?.line??1,column:(e.location?.column??0)+1}}function Ac(e,t){let n=le(t),r=`TS${e.code}`,o=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:r,category:i,text:o,filePath:e.file.fileName,column:a+1,line:s+1}}return{code:r,category:i,text:o,filePath:void 0,line:1,column:1}}var co={noEmit:!0,skipLibCheck:!0};function Pc(e){let{ScriptTarget:t}=le(e);return{ui:{target:t.ES2021,...co},functions:{target:t.ESNext,...co},actions:{target:t.ESNext,...co},widgets:{target:t.ESNext,...co}}}var lo=e=>({actions:`${e}/*.action.ts`,widgets:`${e}/*.widget.tsx`});function Ae(e){let{createCompilerHost:t,createProgram:n}=le(e.srcRoot),{tsConfigContents:r,tsConfigFileDiagnostics:o}=jf(e.srcRoot,e.tsConfigFullPath),i={...r.options,...Pc(e.srcRoot)[e.buildType],incremental:!1},s=t(r.options),a=[],c=(0,Wi.not)(e.entrypoints,r.raw.exclude).map(m=>(0,pt.isAbsolute)(m)?m:(0,pt.join)(e.srcRoot,m));if(r.options.composite)a=[...new Set([...c,...r.fileNames])];else{let m=r.fileNames.filter(g=>g.endsWith(".d.ts")),f=(0,Wi.not)(m,r.raw.exclude).map(g=>(0,pt.isAbsolute)(g)?g:(0,pt.join)(e.srcRoot,g));a=[...new Set([...c,...f])]}let l=n({rootNames:a,options:i,host:s,configFileParsingDiagnostics:o,projectReferences:r.projectReferences}),d=l.emit();return[...l.getSyntacticDiagnostics(),...l.getSemanticDiagnostics(),...l.getConfigFileParsingDiagnostics(),...l.getGlobalDiagnostics(),...l.getDeclarationDiagnostics(),...d.diagnostics].map(m=>Ac(m,e.appRoot))}function jf(e,t){let{sys:n,readConfigFile:r,parseJsonConfigFileContent:o}=le(e),i=r(t,c=>(0,Oc.readFileSync)(c).toString()),s=[];i.error&&(0,po.has)(i.error.file,"parseDiagnostics")&&(s=(0,po.get)(i.error?.file,"parseDiagnostics"));let a=o(i.config,n,(0,pt.dirname)(t));return s.push(...a.errors),{tsConfigContents:a,tsConfigFileDiagnostics:s}}function uo(e){return e.filter(t=>t.category==="Error"||!t.filePath||!t.filePath.includes("node_modules"))}function dn(e,t){return t?uo(e):e.filter(n=>n.category==="Error")}var Sc=require("@babel/code-frame"),ge=require("chalk"),kc=require("fs"),Rc=T(require("ansi-to-html"));var Bf=new Rc.default({});function he(e){for(let t of e)p.info(Lf(t))}var Lf=e=>{let t=e.filePath?`${(0,ge.cyan)(e.filePath)}:${(0,ge.yellow)(e.line)}:${(0,ge.yellow)(e.column)}`:"<no file>",n=e.category==="Error"?(0,ge.red)("Error:"):(0,ge.yellow)("Warning:"),r=e.code?(0,ge.gray)(` ${e.code}`):"",o=`> ${t} - ${n}${r} ${e.text}`,i=(0,ge.bold)(`${Fc(e)}`);return`${o}
${i}`},mo=e=>{try{return`<div class="dt-app-codesnippet" style="background-color:#15171B">${Bf.toHtml(Fc(e))}</div>`}catch(t){console.error(t)}return""},Fc=e=>{try{if(!e.filePath)return"";let t=(0,kc.readFileSync)(e.filePath,"utf-8"),n=t==="",r={start:{line:e.line,column:n?1:e.column}};return(0,Sc.codeFrameColumns)(n?" ":t,r,{forceColor:!0})}catch(t){console.error(t)}return""};var Dc=require("fs"),Wf="//# sourceMappingURL=data:application/json;base64,ewogICJtYXBwaW5ncyI6ICJBQUFBQSIsCiAgInNvdXJjZXMiOiBbIiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiIl0sCiAgIm5hbWVzIjogWyIiXSwKICAidmVyc2lvbiI6IDMsCiAgImZpbGUiOiAiIgp9",De=()=>({name:"excludeVendorFromSourceMap",setup(e){e.onLoad({filter:/node_modules/},t=>{if(t.path.endsWith(".js"))return{contents:`${(0,Dc.readFileSync)(t.path,"utf8")}
${Wf}`,loader:"default"}})}});var Ic=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>
);
`,Mc=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 Ft=require("path");var Nc={sourcemap:!1,includeVendorSourceMaps:!1},Vf={sourcemap:!0,includeVendorSourceMaps:!0};function Pe(e){if(e.sourcemaps===void 0)return e.dev?Vf:Nc;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 Nc}}var er=require("path");var mn=require("path");var un=require("path"),fo=require("fs");var _c=require("fast-glob"),$c=require("path");async function Uc(e,t){let n=le(e),r=(0,_c.sync)(v([e,t.input,t.glob]));return n.createProgram(r,{}).getSourceFiles().map(i=>(0,$c.relative)(e,i.fileName)).filter(i=>!i.includes("node_modules"))}function go(e){return e.map(Hf).filter(t=>!t.filePath?.includes("node_modules/"))}var jc=e=>Ke(e,"Error"),Hf=e=>Ke(e,"Warning");async function Bc(e,t){let n=e.build.functions,o=(await Uc(e.root,n)).length>0,i=(0,fo.existsSync)((0,un.join)(e.root,t));if(o&&!i)throw new Error(`Failed to build functions
${(0,un.join)(n.input,n.tsconfig)} must exist, if function source files are present in the ${n.input} directory.
Please create a tsconfig.json file in the ${n.input} directory, or delete the directory.
Example ${(0,un.join)(n.input,"tsconfig.json")}
${(0,fo.readFileSync)((0,un.join)(R(),"function/template/tsconfig.json"),"utf-8")}:
`,{cause:265});if(!o&&i)throw new Error(`Failed to build functions
${(0,un.join)(n.input,n.tsconfig)} exists, but no functions were found in the ${n.input} directory.
Please create a function in the ${n.input} directory, or delete the directory.
You can create functions with the generate command:
$ yarn generate:function
`,{cause:265})}function Ie(){return{sourcemap:!0,color:!0,loader:{".node":"empty"},bundle:!0,logLevel:"silent",charset:"utf8",write:!1}}async function ho(e,t,n){let r=require(ne("esbuild",t.cwd));if(!r.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. ${r.version?`Your current esbuild version being used is ${r.version}.`:""}`,{cause:258});let{context:o}=r,i=t.sourcemapOptions?.sourcemap??!1;i&&!t.sourcemapOptions?.includeVendorSourceMaps&&(t.plugins=[...t.plugins??[],De()]);let s=await o({...Ie(),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 Vi(e,t){let n=Date.now();try{let r=(0,er.join)(e.cwd,"dist"),o=await ho(r,e,t),i=Date.now(),s=o.warnings.map(l=>Ke(l,"Warning")).filter(l=>!l.filePath?.includes("node_modules/")),a=e.outDir??"dist";return{fileMap:o.outputFiles.reduce((l,d)=>{let u=`${er.sep}${(0,er.join)(a,d.path.replace(r,""))}`;return{...l,[u]:{content:Buffer.from(d.contents)}}},{}),diagnostics:s,duration:i-n,metafile:o.metafile}}catch(r){let o=Date.now();if(Gf(r)){let s=[...r.errors.map(a=>Ke(a,"Error")),...r.warnings.map(a=>Ke(a,"Warning")).filter(a=>!a.filePath?.includes("node_modules/"))];return{fileMap:{},diagnostics:s,duration:o-n}}throw r instanceof Error?r:new Error(String(r),{cause:261})}}function Gf(e){return typeof e=="object"&&typeof e?.errors<"u"}var To=require("@dynatrace/runtime-simulator"),Xi=require("chalk"),gn=require("http2"),ir=require("path");var Lc=require("url");async function yo({clientID:e,clientSecret:t,accountURN:n},r,o){if(!e||!t)throw new Error('"clientID" and "clientSecret" are required to fetch an automation token..',{cause:259});let i=new Lc.URLSearchParams;i.append("grant_type","client_credentials"),o&&i.append("scope",o.map(s=>s.name).join(" ")),i.append("client_id",e),i.append("client_secret",t),n&&i.append("resource",n);try{let s=await O(`${new URL(r).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 Hr(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 Vc=require("url");var Hi=new Map;async function Wc(e){if(Hi.has(e)){let o=Hi.get(e);return p.debug(`Found resolved URL in cache: ${o.toString()}`,"HTTP(S)"),o}p.debug(`Execute GET request without allowing redirection to '${e}'`,"HTTP(S)");let t=await O(e,{redirect:"follow"}),n,r=t.headers.get("location");return r?n=new URL(r):n=new URL(t.url),p.debug(`Resolved URL is ${n.toString()}`,"HTTP(S)"),Hi.set(e,n),n}async function Hc(e){try{let t=new Vc.URL(e);t.pathname="platform/oauth2/authorization/dynatrace-sso",p.debug(`Retrieving SSO-URL for environment '${e}'`,"AUTH");let n=(await Wc(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"),Ca(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 up=require("path"),mp=require("fs");var Xc=T(require("fastify")),Qc=T(require("open")),ep=require("mime-types"),tp=require("querystring");var tr=require("crypto"),wo=[{name:"app-engine:apps:run",comment:"cli-scope"}];function Gc(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function zf(e){return(0,tr.createHash)("sha256").update(e).digest()}var Gi=Gc((0,tr.randomBytes)(46)),zc=Gc(zf(Gi)),Jc=(0,tr.randomBytes)(20).toString("hex");async function Kc(e,t,n,r){let o=new URL(e);o.pathname="/sso/oauth2/token",o.searchParams.append("grant_type","authorization_code"),o.searchParams.append("code",n),o.searchParams.append("client_id",t),o.searchParams.append("redirect_uri",r.toString()),o.searchParams.append("code_verifier",Gi);let i=await O(o.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 qc(e,t){if(me){let n=`https://${vt(e)}/auth/login`;return`${t}/platform-reserved/app-registry/v1/cde-auth?cde-uri=${encodeURIComponent(n)}`}return`http://localhost:${e}/auth/login`}var Ji=T(require("fs")),zi;function Jf(){try{return Ji.default.statSync("/.dockerenv"),!0}catch{return!1}}function Kf(){try{return Ji.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Yc(){return zi===void 0&&(zi=Jf()||Kf()),zi}var np=require("@dynatrace/devkit");var Zc=`<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, 44);
--text-color: rgb(235, 236, 255);
--line-color: rgb(59, 59, 82);
--primary-color: rgb(153, 155, 237);
--text-accent-color: rgb(31, 32, 55);
--text-link-color: rgb(173, 176, 255);
}
}
body {
font-family: DynatraceFlow, Roboto, Helvetica, sans-serif;
color: var(--text-color);
background-color: var(--bg-color);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 16px;
height: 100%;
text-align: center;
}
* {
overflow-wrap: break-word;
font-style: normal;
color: inherit;
margin: 0px;
}
h1 {
font-size: 32px;
font-weight: 600;
line-height: 1.25;
}
p,div,a {
font-size: 14px;
font-weight: 400;
line-height: 20px;
}
.divider {
width: 100%;
height: 1px;
border: none;
margin: 0;
background-color: var(--line-color);
max-width: 512px;
}
button {
width: fit-content;
font-weight: 500;
font-size: 14px;
padding: 6px 8px;
background-color: var(--primary-color);
color: var(--text-accent-color);
cursor: pointer;
height: 32px;
border-radius: 8px;
border: 0;
outline-color: var(--text-accent-color);
}
button:disabled {
--primary-color: #54558780;
--text-accent-color: #dadbe780;
cursor: not-allowed;
}
a {
color: var(--text-link-color);
outline-color: var(--text-link-color);
text-decoration-color: var(--text-link-color);
}
a > span {
text-decoration: none;
}
a > span > svg {
margin-left: var(--dt-spacings-size-2, 2px);
width: 1lh;
height: 1lh;
max-height: min(1.5em, var(--dt-spacings-size-40, 40px));
max-width: min(1.5em, var(--dt-spacings-size-40, 40px));
vertical-align: middle;
margin-bottom: -0.1em;
margin-top: -0.1em;
}
</style>
<body>
<img style="max-width: 256px;"
src="data:image/svg+xml,%3Csvg width='128' height='128' viewBox='0 0 73 73' fill='none' xmlns='http://www.w3.org/2000/svg' %3E%3Cpath d='M24.736 6.39229C23.83 11.1739 22.7227 18.2708 22.1187 25.4684C21.0617 38.1523 21.716 46.6585 21.716 46.6585L3.84787 63.6207C3.84787 63.6207 2.48888 54.1078 1.78422 43.3869C1.38156 36.743 1.23056 30.9044 1.23056 27.3811C1.23056 27.1797 1.33123 26.9784 1.33123 26.7771C1.33123 26.5254 1.63322 24.1598 3.94853 21.9451C6.46517 19.5291 25.038 4.98297 24.736 6.39229Z' fill='%231496FF' /%3E%3Cpath d='M24.736 6.39226C23.83 11.1739 22.7227 18.2708 22.1187 25.4684C22.1187 25.4684 2.33788 23.1028 1.23056 27.8844C1.23056 27.6327 1.58289 24.7134 3.8982 22.4988C6.41484 20.0828 25.038 4.98294 24.736 6.39226Z' fill='%231284EA' /%3E%3Cpath d='M1.23057 26.7267C1.23057