@datadog/esbuild-plugin 3.2.6-dev.0 → 3.2.6-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/index.js +1 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/index.mjs +1 -1
- package/dist/src/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/src/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createUnplugin as e}from"unplugin";import t from"chalk";import n from"async-retry";import{File as o}from"buffer";import r,{mkdtemp as i}from"fs/promises";import s from"fs";import{JsonStreamStringify as a}from"json-stream-stringify";import u from"path";import{Readable as c}from"stream";import{spawn as d}from"child_process";import{randomBytes as l,createHash as p,randomUUID as f}from"crypto";import m from"http";import h,{tmpdir as g}from"os";import*as y from"eslint-scope";import b from"jszip";import{glob as w}from"glob";import v from"pretty-bytes";import $ from"p-queue";import k from"@jridgewell/remapping";import{performance as x}from"perf_hooks";import{instrument as E}from"@datadog/js-instrumentation-wasm";import{simpleGit as S}from"simple-git";import I from"magic-string";import D from"esbuild";import A from"node:url";import P from"node:path";import j from"node:module";const M=A.fileURLToPath(import.meta.url),T=P.dirname(M),C=j.createRequire(import.meta.url),O="__datadog-helper-file",N=new RegExp(O),R=["development","production","test"],_=["datadoghq.com","us3.datadoghq.com","us5.datadoghq.com","datadoghq.eu","ddog-gov.com","us2.ddog-gov.com","ap1.datadoghq.com","ap2.datadoghq.com","datad0g.com"],F=_[0],z="datadog-build-plugins",L=t.bold.green,U=t.bold.yellow,B=["API_KEY","APP_KEY","SOURCEMAP_INTAKE_URL","APPS_INTAKE_URL","APPS_UPLOAD_ASSETS","APPS_VERSION_NAME","APPS_AUTH_METHOD","SITE"],q=e=>process.env[`DATADOG_${e}`]||process.env[`DD_${e}`],V=e=>{const t=[];return process.env[`DD_${e}`]&&t.push(`DD_${e}`),process.env[`DATADOG_${e}`]&&t.push(`DATADOG_${e}`),t},K=(e,t,n)=>{if(void 0!==e)return(e=>_.some((t=>t===e)))(e)?e:void n.push(`${t} "${e}" is not a supported Datadog site. See the site parameters in https://docs.datadoghq.com/getting_started/site/.`)},H=e=>{if(null===e||"object"!=typeof e)return"";const t="title"in e&&"string"==typeof e.title?e.title:void 0,n="detail"in e&&"string"==typeof e.detail?e.detail:void 0;return t&&n?`${t}: ${n}`:t||(n?`detail: ${n}`:"")},W=e=>({"DD-EVP-ORIGIN":`${e.bundler}-build-plugin_${e.plugin}`,"DD-EVP-ORIGIN-VERSION":e.version}),J=async e=>{const{getForm:t,defaultHeaders:n={},zip:o=!0}=e,r=await t(),i=new Request("fake://url",{method:"POST",body:r});return{data:o?i.body.pipeThrough(new CompressionStream("gzip")):i.body,headers:{"Content-Encoding":o?"gzip":"multipart/form-data",...n,...Object.fromEntries(i.headers.entries())}}},G=[400,401,403,404,405,409,413],Y=async e=>{const{auth:t,url:o,method:r="GET",getData:i,type:s="text"}=e,a={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return n((async(e,n)=>{let a;try{const e={method:r,duplex:"half"};let n={"X-Datadog-Origin":"build-plugins"};if(t&&"accessToken"in t?t.accessToken&&(n.Authorization=`Bearer ${t.accessToken}`):(t?.apiKey&&(n["DD-API-KEY"]=t.apiKey),t?.appKey&&(n["DD-APPLICATION-KEY"]=t.appKey)),"function"==typeof i){const{data:t,headers:o}=await i();e.body=t,n={...n,...o}}a=await fetch(o,{...e,headers:n})}catch(t){return e(t),{}}if(!a.ok){let t=`HTTP ${a.status} ${a.statusText}`;try{const e=(e=>{try{const t=JSON.parse(e);if(null!==t&&"object"==typeof t)if("errors"in t&&Array.isArray(t.errors)){const e=t.errors.map(H).filter((e=>e.length>0)).join("\n");if(e)return e}else{const e=H(t);if(e)return e}}catch{}return e})(await a.text());e&&(t+=`\n${e}`)}catch{}if(G.includes(a.status))return e(new Error(t)),{};throw new Error(t)}try{let e;return e="json"===s?await a.json():await a.text(),e}catch(t){return e(t),{}}}),a)},Q=e=>({message:t,context:n})=>Y({retries:2,minTimeout:100,url:"https://browser-http-intake.logs.datadoghq.com/v1/input/pub44d5f4eb86e1392037b7501f7adc540e",method:"POST",type:"json",getData:async()=>{const o={ddsource:e.packageName||z,message:t,service:"build-plugins",team:"language-foundations",env:e.env,version:e.version,bundler:{name:e.bundler.name,version:e.bundler.version},metadata:e.metadata,...n};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}}),Z=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),X=e=>e.includes(O),ee=e=>{const t={bundler:e.bundler,errors:e.errors,metadata:e.metadata,warnings:e.warnings,logs:e.logs,timings:e.timings,start:e.start,end:e.end,duration:e.duration,writeDuration:e.writeDuration,entries:[],inputs:[],outputs:[]};for(const n of e.entries||[]){const e={...n,inputs:[],outputs:[]};n.inputs&&(e.inputs=n.inputs.map((e=>e.filepath))),n.outputs&&(e.outputs=n.outputs.map((e=>e.filepath))),t.entries.push(e)}for(const n of e.inputs||[]){const e={...n,dependencies:[],dependents:[]};if(n.dependencies)for(const t of n.dependencies)e.dependencies.push(t.filepath);if(n.dependents)for(const t of n.dependents)e.dependents.push(t.filepath);t.inputs.push(e)}for(const n of e.outputs||[]){const e={...n,inputs:[]};n.inputs&&(e.inputs=n.inputs.map((e=>e.filepath))),t.outputs.push(e)}return t},te=e=>{const t=!!e.errorTracking?.sourcemaps,n=e.enableGit??!0;return t&&n},ne=e=>{const t=Math.floor(e/1e3/60/60/24),n=new Date(e-24*t*60*60*1e3),o=n.getUTCHours(),r=n.getUTCMinutes(),i=n.getUTCSeconds(),s=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${o?`${o}h `:""}${r?`${r}m `:""}${i?`${i}s`:""}`.trim();return`${a}${!a||s?` ${s}ms`:""}`.trim()},oe=(e,t=60,n="[...]")=>{if(e.length<=t)return e;const o=Math.max(4,t-n.length),r=Math.min(10,Math.floor(o/2)),i=o-r;return`${e.slice(0,r)}${n}${e.slice(-i)}`},re=(e="")=>{try{if(!e||e.startsWith("git@"))return e;const t=new URL(e),n="/"===t.pathname?"":t.pathname;return`${t.protocol?`${t.protocol}//`:""}${t.host}${n}`}catch{return e}},ie=e=>e.trim().toLowerCase().replace(/[^a-z0-9_:./-]+/g,"_").replace(/^_+|_+$/g,"")||"unknown",se=e=>Object.entries(e).map((([e,n])=>` - ${e}: ${t.bold.green((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if(Array.isArray(e))return e.join(", ");if("object"==typeof e)try{return JSON.stringify(e,null,2)}catch{return String(e)}return e?.toString()??""})(n))}`)).join("\n"),ae={debug:0,info:1,warn:2,error:3,none:4},ue=e=>e.split(">").map(Z).join(">"),ce=(e,n,o,r)=>{const i=ue(e);return(s,a="debug",{forward:u,context:c}={})=>{let d=t.dim,l=console.log;"error"===a?(d=t.red,l=console.error):"warn"===a?(d=t.yellow,l=console.warn):"info"===a&&(d=t.cyan,l=console.log);const p=`[${n.metadata?.name?`${n.metadata.name}|`:""}${a}|${n.bundler.name}|${i}]`,f="string"==typeof s?s:JSON.stringify(s,null,2);if(o.logs.push({bundler:n.bundler.name,pluginName:e,type:a,message:f,time:Date.now()}),"error"===a&&o.errors.push(f),"warn"===a&&o.warnings.push(f),u){const t=async()=>{try{const t=Q(n);await t({message:f,context:{plugin:e,status:a,...c}})}catch(t){ce(e,n,o,r)(`Error forwarding log: ${t}`,"debug")}};o.queue.push(t())}ae[a]>=ae[r]&&l(`${d(p)} ${f}`)}},de=(e,n,o)=>(r,i={})=>{const{level:s="debug",start:a=!0,log:u=!0,tags:c=[]}=i,d={pluginName:e,label:r,spans:[],tags:[...c,`plugin:${e}`,`level:${s}`],logLevel:s,total:0};n.push(d);const l=()=>d.spans.filter((e=>!e.end)),p=n=>{l().length||(!d.spans.length&&u&&o(t.dim(`[${t.cyan(r)}] : start`),"debug"),d.spans.push({start:n||Date.now(),tags:[`plugin:${e}`]}))},f=(e,n=!0)=>{const i=l();if(i?.length){i.length>1&&o(`Timer ${t.cyan(r)} has more than one ongoing span.`,"debug");for(const t of i)t.end=e||Date.now()}else n&&o(`Timer ${t.cyan(r)} cannot be paused, no ongoing span.`,"debug")};if(a){let e;"number"==typeof a&&(e=a),p(e)}return{timer:d,resume:p,end:e=>{f(e,!1);const n=d.spans.reduce(((e,t)=>e+(t.end-t.start)),0);d.total=n,u&&o(`[${t.cyan(r)}] : ${t.cyan(ne(n))}`,s)},pause:f,tag:(e,t={})=>{const{span:n=!1}=t;if(n){const t=l();for(const n of t)n.tags.push(...e)}else d.tags.push(...e)}}},le=(e,t,n="warn")=>o=>{const r=ce(o,e,t,n);return{getLogger:r=>le(e,t,n)(`${ue(o)}>${r}`),time:de(o,t.timings,r),error:(e,t)=>r(e,"error",t),warn:(e,t)=>r(e,"warn",t),info:(e,t)=>r(e,"info",t),debug:(e,t)=>r(e,"debug",t)}},pe=["buildEnd","buildStart","load","resolveId","transform","watchChange","writeBundle","buildRoot","init","buildReport","bundlerReport","git"],fe=(e,t,n,o)=>{const r=n=>function(...r){const i=o.time(`${e} | ${t}`,{log:!1,tags:["type:hook",`hook:${t}`]}),s=n.apply(this,r);return s instanceof Promise?s.finally((()=>{i.end()})):(i.end(),s)};return"object"==typeof n&&null!==n&&"handler"in n?{...n,handler:r(n.handler)}:r(n)},me=(e,t,n)=>{const o=e.getLogger(z);return e=>{const r=o.time(`hook | init ${n}`,{log:!1}),i=t(e).map((e=>((e,t)=>{const n={...e},o=Z(e.name);for(const r of pe){const i=e[r];i&&(n[r]=fe(o,r,i,t))}return n})(e,o))),s=i.map((e=>`plugin:${e.name}`));return r.tag(s),r.end(),i}},he=new Set,ge=(e,t,n)=>{const o=e[t];if(o&&"object"==typeof o&&"enable"in o){const e=o.enable;if("boolean"!=typeof e&&void 0!==e&&(he.has(t)||(he.add(t),n.warn(`\`${t}.enable\` should be a boolean, got ${typeof e}. Non-boolean values are coerced today but will be rejected in the next major.`))),void 0!==e)return!!e}return!!o},ye="apps",be="datadog-apps-plugin",we="api/unstable/app-builder-code/apps",ve="datadog-apps-assets.zip",$e=/\.backend\.(ts|tsx|js|jsx)$/,ke=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],xe=["apiKey","oauth"],Ee=e=>{const t=e[ye]||{},n=(e=>{if(void 0!==e){if(xe.includes(e))return e;throw new Error(`apps.authOverrides.method must be one of: ${xe.join(", ")}`)}})(q("APPS_AUTH_METHOD")||t.authOverrides?.method)||((e=>Boolean((q("API_KEY")||e.auth?.apiKey)&&(q("APP_KEY")||e.auth?.appKey)))(e)?"apiKey":"oauth");return{include:t.include||[],dryRun:t.dryRun??!q("APPS_UPLOAD_ASSETS"),identifier:t.identifier?.trim(),name:t.name?.trim()||e.metadata?.name?.trim(),authOverrides:{method:n}}},Se=async e=>r.rm(e,{force:!0,maxRetries:3,recursive:!0}),Ie=async e=>r.mkdir(e,{recursive:!0}),De=(e,t)=>{var n;n=u.dirname(e),s.mkdirSync(n,{recursive:!0}),s.writeFileSync(e,t,{encoding:"utf-8"})},Ae=e=>s.readFileSync(e,{encoding:"utf-8"}),Pe=e=>{try{return s.existsSync(e)}catch(e){if("ENOENT"===e.code)return!1;throw e}},je=async(e,t)=>{if("function"==typeof s.openAsBlob){const n=await s.openAsBlob(e,{type:t.contentType});return new o([n],t.filename)}{const n=c.toWeb(s.createReadStream(e)),r=await new Response(n).blob();return new o([r],t.filename,{type:t.contentType})}},Me=async e=>{const t={empty:!1,exists:!0};try{const{size:n}=await r.stat(e);0===n&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t};var Te=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Te||{});const Ce=()=>import("oauth4webapi"),Oe=t.cyan.bold,Ne=e=>e.toString("base64url"),Re=e=>{const t=(e=>"datad0g.com"===e?"f4bacdd2-0c8c-49f5-bf3e-a62ba3ec02e6":"e17b9ffa-3daf-4124-ba1b-4ac8c547d506")(e);return{authorizationUrl:`https://app.${e}/oauth2/v1/authorize`,cacheTokens:!0,clientId:t,openBrowser:!0,redirectUri:"http://localhost:8060",timeoutMs:3e5,tokenUrl:`https://api.${e}/oauth2/v1/token`}},_e=e=>({client_id:e}),Fe=e=>({issuer:new URL(e.authorizationUrl).origin,authorization_endpoint:e.authorizationUrl,token_endpoint:e.tokenUrl}),ze=(e,t)=>`${e}:${t.clientId}:${((e,t)=>p("sha256").update([t.clientId,e,t.authorizationUrl,t.tokenUrl].join("|")).digest("hex").slice(0,16))(e,t)}`,Le=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=UTF-8"}),e.end(n)},Ue=(e,t,n=Date.now())=>({accessToken:e.access_token,expiresAt:"number"==typeof e.expires_in?n+1e3*e.expires_in:void 0,expiresIn:e.expires_in,refreshToken:e.refresh_token,scope:e.scope,site:t,tokenType:e.token_type}),Be=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),qe=e=>e instanceof Error?e.message:String(e),Ve=e=>{const t=qe(e).toLowerCase();return"NoEntry"===(e=>Be(e)&&"string"==typeof e.code?e.code:void 0)(e)||t.includes("noentry")||t.includes("no matching entry")||t.includes("not found")},Ke=async(e,t)=>{const{AsyncEntry:n}=await import("@napi-rs/keyring");return new n("datadog-build-plugins:oauth",ze(e,t))},He=(e,t)=>new Error(`Could not ${e} Datadog OAuth token in the OS credential store. ${t instanceof Error?t.message:String(t)}`),We=async(e,t)=>{try{const n=await Ke(e,t),o=await n.getPassword();if(!o)return;const r=JSON.parse(o);return(e=>{if(Be(e)&&1===e.version&&Be(e.token)&&"string"==typeof e.token.accessToken&&"string"==typeof e.token.clientId&&"string"==typeof e.token.site)return e})(r)?.token}catch(e){if(Ve(e))return;throw He("read",e)}},Je=async(e,t,n,o=e.site)=>{if(t.cacheTokens)try{await(async(e,t,n)=>{try{const o=await Ke(e,n),r={version:1,token:t};await o.setPassword(JSON.stringify(r))}catch(e){throw He("save",e)}})(o,((e,t)=>({accessToken:e.accessToken,clientId:t,expiresAt:e.expiresAt,refreshToken:e.refreshToken,scope:e.scope,site:e.site,tokenType:e.tokenType}))(e,t.clientId),t),n.debug("Saved Datadog OAuth token to the OS credential store.")}catch(e){n.warn(`Could not save Datadog OAuth token to the OS credential store; continuing without a persistent cache. ${qe(e)}`)}},Ge=async(e,t,n)=>{if(t.cacheTokens)try{await(async(e,t)=>{try{const n=await Ke(e,t);await n.deletePassword()}catch(e){if(!Ve(e))throw He("delete",e)}})(e,t)}catch(e){n.warn(`Could not delete cached Datadog OAuth token. ${qe(e)}`)}},Ye=async(e,t,n)=>{if(!t.cacheTokens)return;let o;try{o=await We(e,t)}catch(e){n.warn(`Could not read cached Datadog OAuth token; starting browser authorization. ${qe(e)}`)}if(o){if(void 0===(r=o).expiresAt||r.expiresAt>Date.now()+3e5)return n.debug("Using cached Datadog OAuth access token."),(e=>({accessToken:e.accessToken,expiresAt:e.expiresAt,refreshToken:e.refreshToken,scope:e.scope,site:e.site,tokenType:e.tokenType}))(o);var r;if(o.refreshToken)try{n.debug("Refreshing cached Datadog OAuth access token.");const r=await(async(e,t,n)=>{const o=await Ce(),r=Fe(t),i=_e(t.clientId),s=await o.refreshTokenGrantRequest(r,i,o.None(),n),a=await o.processRefreshTokenResponse(r,i,s);return Ue({...a,refresh_token:a.refresh_token||n},e)})(e,t,o.refreshToken);return await Je(r,t,n),r}catch(o){return n.warn(`Cached Datadog OAuth token could not be refreshed; starting browser authorization. ${o instanceof Error?o.message:String(o)}`),void await Ge(e,t,n)}}},Qe=async(e,t,n)=>{const o=await Ce(),r=Fe(t),i=_e(t.clientId),s=Ne(l(32)),a=await(async e=>(await Ce()).calculatePKCECodeChallenge(e))(s),u=Ne(l(32)),c=(e=>{const t=new URL(e.authorizationUrl);return t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("client_id",e.clientId),t.searchParams.set("response_type","code"),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("state",e.state),t})({authorizationUrl:t.authorizationUrl,clientId:t.clientId,codeChallenge:a,redirectUri:t.redirectUri,state:u}),p=(async e=>{const t=new URL(e.redirectUri),n=Number(t.port||80);if("http:"!==t.protocol)throw new Error("OAuth redirect URI must use http for the local OAuth callback.");if(!Number.isInteger(n)||n<=0)throw new Error("OAuth redirect URI must include a valid port.");let o,r=!1;const i=m.createServer();try{return await new Promise(((s,a)=>{const u=e=>{r||(r=!0,e())};i.on("request",((n,o)=>{const r=new URL(n.url||"/",t.origin);if(r.pathname!==t.pathname)return void Le(o,404,"Not found.");let i;try{i=e.oauth.validateAuthResponse(e.authorizationServer,e.client,r,e.state)}catch(e){return Le(o,400,"OAuth authorization failed. You may now close this tab."),void u((()=>a(e instanceof Error?e:new Error(String(e)))))}if(!i.get("code"))return Le(o,400,"Missing OAuth authorization code. You may now close this tab."),void u((()=>a(new Error("Missing OAuth authorization code."))));Le(o,200,"OAuth authorization complete. You may now close this tab."),u((()=>s({callbackParameters:i})))})),i.once("error",(e=>u((()=>a(e))))),o=setTimeout((()=>{u((()=>a(new Error(`Timed out waiting for OAuth callback after ${e.timeoutMs}ms.`))))}),e.timeoutMs);try{const e="localhost"===t.hostname?void 0:t.hostname;i.listen(n,e)}catch(e){u((()=>a(e instanceof Error?e:new Error(String(e)))))}}))}finally{o&&clearTimeout(o),i.listening&&(i.close(),i.closeAllConnections?.(),i.closeIdleConnections?.())}})({authorizationServer:r,client:i,oauth:o,redirectUri:t.redirectUri,state:u,timeoutMs:t.timeoutMs});n.info(`Authorize Datadog Apps upload:\n ${Oe(c.toString())}`),t.openBrowser&&((e,t)=>{const n="darwin"===process.platform?{command:"open",args:[e]}:"win32"===process.platform?{command:"cmd",args:["/c","start","",e]}:{command:"xdg-open",args:[e]};try{const e=d(n.command,n.args,{detached:!0,stdio:"ignore"});e.once("error",(e=>{t.warn(`Could not open browser automatically: ${qe(e)}`)})),e.unref()}catch(e){t.warn(`Could not open browser automatically: ${qe(e)}`)}})(c.toString(),n);return(async e=>{const t=await Ce(),n=Fe(e),o=_e(e.clientId),r=await t.authorizationCodeGrantRequest(n,o,t.None(),e.callbackParameters,e.redirectUri,e.codeVerifier),i=await t.processAuthorizationCodeResponse(n,o,r);return Ue(i,e.site)})({callbackParameters:(await p).callbackParameters,clientId:t.clientId,codeVerifier:s,redirectUri:t.redirectUri,site:e,tokenUrl:t.tokenUrl,authorizationUrl:t.authorizationUrl})},Ze=new Map,Xe=async(e,t)=>{const n=Re(e),o=`${e}:${n.clientId}`;let r=Ze.get(o);return r||(r=(async(e,t,n)=>{const o=await Ye(e,t,n);return o?{persistAfterSuccessfulRequest:!1,token:o}:{persistAfterSuccessfulRequest:!0,token:await Qe(e,t,n)}})(e,n,t).catch((e=>{throw Ze.delete(o),e})),Ze.set(o,r)),r},et='Set apps.authOverrides.method: "oauth" or DD_APPS_AUTH_METHOD=oauth to use OAuth, or set DD_API_KEY and DD_APP_KEY to use API/App key auth.';class tt extends Error{constructor(){super(`Missing authentication. ${et}`),this.statusCode=400,this.name="MissingAuthenticationError"}}const nt=(e,t,n)=>{if("oauth"===e)return e=>(async({auth:e,log:t,...n})=>{const{site:o}=e,{persistAfterSuccessfulRequest:r,token:i}=await Xe(o,t);if(!i.accessToken)throw new Error("OAuth authentication did not return an access token.");const s=await Y({...n,auth:{accessToken:i.accessToken}});return r&&await Je(i,Re(o),t,o),s})({...e,auth:t,log:n});if(t.apiKey&&t.appKey)return e=>Y({...e,auth:{apiKey:t.apiKey,appKey:t.appKey}});throw new tt};function ot(e,t){if(!function(e){return"Program"===e.type}(e))throw new Error(`Expected a Program node from this.parse() for ${t}, got ${e.type}`);return e}function rt(e){return"object"==typeof e&&null!==e&&"Literal"===e.type&&"string"==typeof e.value}function it(e){return"type"===e.importKind||"type"===e.exportKind}function st(e,t){return function(e,t){const n=ot(e,t),o=function(e){const t=new Map;for(const n of e.body)if("FunctionDeclaration"===n.type&&n.id)t.set(n.id.name,{kind:"function"});else if("ClassDeclaration"===n.type&&n.id)t.set(n.id.name,{kind:"class"});else if("VariableDeclaration"===n.type)for(const e of n.declarations)"Identifier"===e.id.type&&t.set(e.id.name,{kind:"variable",init:e.init});else if("ImportDeclaration"===n.type)for(const e of n.specifiers)t.set(e.local.name,{kind:"import"});return t}(n),r=[];for(const e of n.body){if("ExportDefaultDeclaration"===e.type)throw new Error(`Default exports are not supported in .backend.ts files. Use a named export instead: ${t}`);if("ExportAllDeclaration"===e.type)throw new Error(`"export *" is not supported in .backend.ts files. Use explicit named exports instead: ${t}`);if("ExportNamedDeclaration"!==e.type)continue;e.declaration&&r.push(...ct(e.declaration,t).map((e=>({kind:"local",name:e,localName:e}))));const n="string"==typeof e.source?.value?e.source.value:null;for(const i of e.specifiers){if("Identifier"!==i.exported.type)continue;if("default"===i.exported.name)throw new Error(`Default exports are not supported in .backend.ts files. Use a named export instead: ${t}`);const e="Identifier"===i.local.type?i.local.name:"string"==typeof i.local.value?i.local.value:null;e&&(n?r.push({kind:"re-export",name:i.exported.name,localName:e,source:n}):("Identifier"===i.local.type&&dt(e,o,t),r.push({kind:"local",name:i.exported.name,localName:e})))}}return r}(e,t).map((e=>e.name))}const at=new Set(["ArrayExpression","Literal","ObjectExpression","TemplateLiteral"]);function ut(e){return null==e||at.has(e.type)}function ct(e,t){if("FunctionDeclaration"===e.type&&e.id)return[e.id.name];if("ClassDeclaration"===e.type)throw new Error(`Class exports are not supported in .backend.ts files. Only function exports are allowed: ${t}`);if("VariableDeclaration"===e.type)return e.declarations.flatMap((e=>{if("Identifier"!==e.id.type)throw new Error(`Destructured exports are not supported in backend files. Use individual named exports instead: ${t}`);if(ut(e.init))throw new Error(`Non-function export "${e.id.name}" in backend file ${t}. Only function exports are supported — use "export function ${e.id.name}(…) { }" instead.`);return[e.id.name]}));throw new Error(`Unsupported export declaration type "${e.type}" in backend file ${t}. Only function and variable exports are allowed.`)}function dt(e,t,n){const o=t.get(e);if(o){if("class"===o.kind)throw new Error(`Class exports are not supported in .backend.ts files. Only function exports are allowed: ${n}`);if("variable"===o.kind&&ut(o.init))throw new Error(`Non-function export "${e}" in backend file ${n}. Only function exports are supported — use "export function ${e}(…) { }" instead.`)}}function lt(e){const t=e.relativePath.split(u.sep).join("/");return`${p("sha256").update(t).digest("hex")}.${e.name}`}function pt(e){const t=[];for(const{exportName:n,queryName:o}of e)t.push(`export async function ${n}(...args) {`),t.push(` return globalThis.DD_APPS_RUNTIME.executeBackendFunction(${JSON.stringify(o)}, args);`),t.push("}"),t.push("");return t.join("\n")}function ft(e,t,n){const o=[];return o.push(`import { ${e} } from ${JSON.stringify(t)};`),function(e){try{return C.resolve("@datadog/action-catalog/action-execution",{paths:[e]}),!0}catch{return!1}}(n)&&o.push("import { setExecuteActionImplementation } from '@datadog/action-catalog/action-execution';"),o.push(""),o.push('/** @param {import("./context.types").Context} $ */'),o.push("export async function main($) {"),o.push(" globalThis.$ = $;"),o.push(""),o.push(" // Register the $.Actions-based implementation for executeAction"),o.push(" if (typeof setExecuteActionImplementation === 'function') {\n setExecuteActionImplementation(async (actionId, request) => {\n const actionPath = actionId.replace(/^com\\.datadoghq\\./, '');\n const pathParts = actionPath.split('.');\n let actionFn = $.Actions;\n for (const part of pathParts) {\n if (!actionFn) throw new Error('Action not found: ' + actionId);\n actionFn = actionFn[part];\n }\n if (typeof actionFn !== 'function') throw new Error('Action is not a function: ' + actionId);\n return actionFn(request);\n });\n }"),o.push(""),o.push(" const args = $.backendFunctionArgs ?? [];"),o.push(` const result = await ${e}(...args);`),o.push(" return result;"),o.push("}"),o.join("\n")}function mt(e,t,n){const o={state:t},r=e=>{n._?.(e,o),function(e,t){return t[e.type]}(e,n)?.(e,o);for(const t of Object.keys(e))"type"!==t&&i(e[t])},i=e=>{if(Array.isArray(e))for(const t of e)ht(t)&&r(t);else ht(e)&&r(e)};r(e)}function ht(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type}function gt(e){mt(e,null,{_(e){const t=e;t.range||"number"!=typeof t.start||"number"!=typeof t.end||(t.range=[t.start,t.end])}});const t=y.analyze(e,{ecmaVersion:2022,ignoreEval:!0,sourceType:"module"}),n=new Map;for(const e of t.scopes)for(const t of e.references)n.set(t.identifier,t);return{scopeManager:t,referencesByIdentifier:n,moduleScope:vt(t)}}function yt(e,t){return t.referencesByIdentifier.get(e)?.resolved??void 0}function bt(e){return e.defs.some((e=>"ImportBinding"===e.type))}function wt(e,t){return t.moduleScope.set.get(e)}function vt(e){return e.scopes.find((e=>"module"===e.type))??e.globalScope}function $t(e,t,n){const o={scopeAnalysis:t,unsupportedAliases:kt(e,t)},r=[];return mt(e,o,{CallExpression(e,{state:t}){(function(e,t,n){const o=e.callee;if("Identifier"===o.type){if(It(o,t.unsupportedAliases,t.scopeAnalysis))throw jt(n,"action-catalog call aliases");if(It(o,t.scopeAnalysis.actionFunctions,t.scopeAnalysis)){if(e.optional)throw jt(n,"optional action-catalog calls");return!0}return!1}if("MemberExpression"!==o.type)return!1;if(!xt(o,t.scopeAnalysis))return!1;if(e.optional||St(o))throw jt(n,"optional or computed action-catalog namespace calls");return!0})(e,t,n)&&r.push(e)}}),r}function kt(e,t){const n=new Set;return mt(e,t,{VariableDeclarator(e,{state:t}){for(const o of function(e,t){if("Identifier"===e.id.type&&"Identifier"===e.init?.type&&It(e.init,t.actionFunctions,t))return At(e,t,[e.id.name]);if("Identifier"===e.id.type&&"MemberExpression"===e.init?.type&&xt(e.init,t))return At(e,t,[e.id.name]);if("ObjectPattern"!==e.id.type||"Identifier"!==e.init?.type||!It(e.init,t.actionNamespaces,t))return[];const n=e.id.properties.flatMap((e=>"RestElement"===e.type||e.computed?[]:Pt(e.value))).map((e=>e.name));return At(e,t,n)}(e,t))n.add(o)},AssignmentExpression(e,{state:t}){for(const o of function(e,t){if("Identifier"===e.left.type&&"Identifier"===e.right.type&&It(e.right,t.actionFunctions,t))return Dt([e.left],t);if("Identifier"===e.left.type&&"MemberExpression"===e.right.type&&xt(e.right,t))return Dt([e.left],t);if("ObjectPattern"!==e.left.type||"Identifier"!==e.right.type||!It(e.right,t.actionNamespaces,t))return[];const n=e.left.properties.flatMap((e=>"RestElement"===e.type||e.computed?[]:Pt(e.value)));return Dt(n,t)}(e,t))n.add(o)}}),n}function xt(e,t){const n=Et(e);return!!n&&It(n,t.actionNamespaces,t)}function Et(e){return"Identifier"===e.object.type?e.object:"MemberExpression"===e.object.type?Et(e.object):void 0}function St(e){return!(!e.optional&&!e.computed)||"MemberExpression"===e.object.type&&St(e.object)}function It(e,t,n){return function(e,t,n){const o=yt(e,n);return!!o&&t.has(o)}(e,t,n.moduleScope)}function Dt(e,t){return e.flatMap((e=>{const n=yt(e,t.moduleScope);return n?[n]:[]}))}function At(e,t,n){const o=new Set(n);return t.moduleScope.scopeManager.getDeclaredVariables(e).filter((e=>o.has(e.name)))}function Pt(e){switch(e.type){case"Identifier":return[e];case"ObjectPattern":return e.properties.flatMap((e=>"RestElement"===e.type?Pt(e.argument):Pt(e.value)));case"ArrayPattern":return e.elements.flatMap((e=>e?Pt(e):[]));case"RestElement":return Pt(e.argument);case"AssignmentPattern":return Pt(e.left);case"MemberExpression":return[]}}function jt(e,t){return new Error(`Unsupported action-catalog call in ${e}: ${t} could hide a connectionId.`)}const Mt="@datadog/action-catalog";function Tt(e,t,n){const o=e.get(t);if(!o)return zt(t,[],n.name);const r=yt(n,o.scopeAnalysis);return r?function(e,t){return t.defs.some((t=>t.name===e))}(n,r)?Lt(t,[],n.name):Nt({modules:e,visitedExports:new Set},t,r,[]):Lt(t,[],n.name)}function Ct(e,t,n,o){const r=e.modules.get(t);if(!r)return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-module-record",requestKind:"export",exportName:n,message:`Module '${e}' was not collected while resolving export '${n}'.`,hops:t}}(t,o,n);if("default"===n)return _t(t,o,n);const i=`${t}\0${n}`;if(e.visitedExports.has(i))return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"cycle",exportName:n,message:`Resolving export '${n}' from module '${e}' would cycle through the module graph.`,hops:t}}(t,o,n);e.visitedExports.add(i);try{const t=r.exportsByName.get(n);return t?function(e,t,n,o,r){if("unsupported"===o.kind)return function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"unsupported-export",exportName:n,exportReason:o,message:`Export '${n}' from module '${e}' is unsupported: ${o}.`,hops:t}}(t.id,r,n,o.reason);if("re-export"===o.kind)return"default"===o.importedName?_t(t.id,r,n):Ct(e,o.resolvedId,o.importedName,[...r,{kind:"re-export",moduleId:t.id,exportName:n,sourceModuleId:o.resolvedId,sourceExportName:o.importedName}]);return Nt(e,t.id,o.variable,[...r,{kind:"local-export",moduleId:t.id,exportName:n,localName:o.variable.name}])}(e,r,n,t,o):function(e,t,n,o){let r;for(const i of t.starExports){const s=Ct(e,i.resolvedId,n,[...o,{kind:"star-export",moduleId:t.id,exportName:n,sourceModuleId:i.resolvedId}]);if("unsupported"===s.kind){if("missing-export"===s.reason)continue;return s}if(!r||!Ot(r,s)){if(r)return Rt(t.id,o,n);r=s}}return r??function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-export",exportName:n,message:`Module '${e}' does not expose export '${n}'.`,hops:t}}(t.id,o,n)}(e,r,n,o)}finally{e.visitedExports.delete(i)}}function Ot(e,t){return e.moduleId===t.moduleId&&e.variable===t.variable}function Nt(e,t,n,o){const r=e.modules.get(t);if(!r)return zt(t,o,n.name);const i=r.importsByVariable.get(n);if(i)return function(e,t,n,o,r){if("default"===o.kind)return Ft(t,r,n);if("namespace"===o.kind)return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"namespace-import",variableName:n,message:`Variable '${n}' in module '${e}' is an unsupported namespace import.`,hops:t}}(t,r,n);if("default"===o.importedName)return Ft(t,r,n);return Ct(e,o.resolvedId,o.importedName,[...r,{kind:"import",moduleId:t,localName:n,exportName:o.importedName,sourceModuleId:o.resolvedId}])}(e,r.id,n.name,i,o);const s=r.topLevelBindingsByVariable.get(n);return s?"const"===s.kind?{kind:"local",moduleId:r.id,variable:n,binding:s,hops:o}:"mutable"===s.kind?function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"mutable-binding",variableName:n,declarationKind:o,message:`Variable '${n}' in module '${e}' is declared with mutable '${o}'.`,hops:t}}(r.id,o,n.name,s.declarationKind):function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"unsupported-binding",variableName:n,bindingReason:o,message:`Variable '${n}' in module '${e}' has unsupported binding: ${o}.`,hops:t}}(r.id,o,n.name,s.reason):function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-static-binding",variableName:n,message:`Variable '${n}' in module '${e}' does not have a recorded top-level static binding.`,hops:t}}(r.id,o,n.name)}function Rt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"ambiguous-star-export",exportName:n,message:`Module '${e}' exposes ambiguous star exports for '${n}'.`,hops:t}}function _t(e,t,n){return{kind:"unsupported",moduleId:e,reason:"default-export",exportName:n,message:`Export '${n}' from module '${e}' resolves through an unsupported default export.`,hops:t}}function Ft(e,t,n){return{kind:"unsupported",moduleId:e,reason:"default-import",variableName:n,message:`Variable '${n}' in module '${e}' is an unsupported default import.`,hops:t}}function zt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-module-record",requestKind:"variable",variableName:n,message:`Module '${e}' was not collected while resolving variable '${n}'.`,hops:t}}function Lt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"unresolved-identifier",variableName:n,message:`Identifier '${n}' in module '${e}' is not a resolvable reference.`,hops:t}}function Ut(e,t,n){const o=Zt(n);switch(o.type){case"Literal":return function(e,t){if("string"==typeof t.value)return{kind:"resolved",moduleId:e,value:t.value};return function(e,t){return{kind:"unsupported",moduleId:e,reason:"non-string-literal",valueType:t,message:`Literal value type '${t}' in module '${e}' is not a string.`}}(e,typeof t.value)}(t,o);case"TemplateLiteral":return function(e,t){if(t.expressions.length>0)return function(e){return{kind:"unsupported",moduleId:e,reason:"dynamic-template-literal",message:`Dynamic template literals in module '${e}' cannot be resolved to static strings.`}}(e);return{kind:"resolved",moduleId:e,value:t.quasis.map((e=>e.value.cooked??e.value.raw)).join("")}}(t,o);case"Identifier":return function(e,t,n){const o=Tt(e.modules,t,n);if("unsupported"===o.kind)return un(o,n.name);if(!o.binding.expression)return cn(o.moduleId,o.variable.name);if(e.seenVariables.has(o.variable))return nn(o.moduleId,o.variable.name);e.seenVariables.add(o.variable);try{return Ut(e,o.moduleId,o.binding.expression)}finally{e.seenVariables.delete(o.variable)}}(e,t,o);case"MemberExpression":return function(e,t,n){const o=Bt(e,t,n);if("unsupported"===o.kind)return o;return Ut(e,o.moduleId,o.expression)}(e,t,o);default:return function(e,t){return{kind:"unsupported",moduleId:e,reason:"unsupported-expression",expressionType:t,message:`Expression type '${t}' in module '${e}' cannot be resolved to a static string.`}}(t,o.type)}}function Bt(e,t,n){if(n.optional)return function(e){return{kind:"unsupported",moduleId:e,reason:"optional-member-expression",message:`Optional member expressions in module '${e}' cannot be resolved to static strings.`}}(t);if(n.computed)return function(e){return{kind:"unsupported",moduleId:e,reason:"computed-member-expression",message:`Computed member expressions in module '${e}' cannot be resolved to static strings.`}}(t);if("Identifier"!==n.property.type)return function(e,t){return{kind:"unsupported",moduleId:e,reason:"non-static-member-property",propertyType:t,message:`Member property type '${t}' in module '${e}' is not statically named.`}}(t,n.property.type);const o=qt(e,t,n.object);return"unsupported"===o.kind?o:function(e,t,n){let o;for(const r of t.properties){if("SpreadElement"===r.type)return an(e);if(r.computed)return tn(e);if(Qt(r)===n){if(o)return on(e,n);if("init"!==r.kind)return en(e,n);if(!Vt(r))return sn(e,n,r.value.type);o=r}}if(!o)return function(e,t){return{kind:"unsupported",moduleId:e,reason:"missing-object-property",propertyName:t,message:`Static object in module '${e}' does not have property '${t}'.`}}(e,n);return{kind:"resolved",moduleId:e,expression:o.value}}(o.moduleId,o.expression,n.property.name)}function qt(e,t,n){if("Super"===n.type)return rn(t,n.type);const o=Zt(n);if("ObjectExpression"===o.type)return{kind:"resolved",moduleId:t,expression:o};if("MemberExpression"===o.type){const n=Bt(e,t,o);return"unsupported"===n.kind?n:qt(e,n.moduleId,n.expression)}if("Identifier"!==o.type)return rn(t,o.type);const r=Tt(e.modules,t,o);if("unsupported"===r.kind)return un(r,o.name);if(!r.binding.expression)return cn(r.moduleId,r.variable.name);if(e.mutatedImportedObjectVariables.has(r.variable))return function(e,t){return{kind:"unsupported",moduleId:e,reason:"imported-object-mutation",variableName:t,message:`Imported object '${t}' from module '${e}' is mutated in the module graph.`}}(r.moduleId,r.variable.name);if(e.seenVariables.has(r.variable))return nn(r.moduleId,r.variable.name);e.seenVariables.add(r.variable);try{return qt(e,r.moduleId,r.binding.expression)}finally{e.seenVariables.delete(r.variable)}}function Vt(e){const{value:t}=e;return"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&"RestElement"!==t.type&&"AssignmentPattern"!==t.type}function Kt(e){const t=new Set;for(const n of e.values())mt(n.ast,{modules:e,mutatedVariables:t,record:n},{AssignmentExpression(e,{state:t}){Wt(e.left,t)},UpdateExpression(e,{state:t}){Wt(e.argument,t)},UnaryExpression(e,{state:t}){"delete"===e.operator&&Wt(e.argument,t)},ForInStatement(e,{state:t}){Ht(e.left,t)},ForOfStatement(e,{state:t}){Ht(e.left,t)}});return t}function Ht(e,t){"VariableDeclaration"!==e.type&&Wt(e,t)}function Wt(e,t){if("Identifier"!==e.type)if("MemberExpression"!==e.type)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"RestElement"!==e.type?"AssignmentPattern"===e.type&&Wt(e.left,t):Wt(e.argument,t);else for(const n of e.elements)n&&Wt(n,t);else for(const n of e.properties)Wt("RestElement"===n.type?n.argument:n.value,t);else{const n=Yt(e);n&&Jt(n,t)}else Jt(e,t)}function Jt(e,t){const n=Gt(t,e,new Set);n&&t.mutatedVariables.add(n)}function Gt(e,t,n){const o=yt(t,e.record.scopeAnalysis);if(!o||n.has(o))return;if(n.add(o),bt(o)){const n=Tt(e.modules,e.record.id,t);return"local"===n.kind?n.variable:void 0}const r=function(e){for(const t of e.defs){const e=t.node;if("VariableDeclarator"===e.type&&e.init)return e.init}return}(o);if(!r)return;const i=function(e){const t=Zt(e);if("Identifier"===t.type)return t;if("MemberExpression"===t.type)return Yt(t);return}(r);return i?Gt(e,i,n):void 0}function Yt(e){return"Identifier"===e.type?e:"MemberExpression"===e.type?Yt(e.object):void 0}function Qt(e){return"Identifier"===e.key.type?e.key.name:"Literal"===e.key.type&&"string"==typeof e.key.value?e.key.value:void 0}function Zt(e){let t=e;for(;Xt(t);)t=t.expression;return t}function Xt(e){const t=e.type;return("TSAsExpression"===t||"TSSatisfiesExpression"===t||"TSNonNullExpression"===t||"TSTypeAssertion"===t)&&!!e.expression}function en(e,t){return{kind:"unsupported",moduleId:e,reason:"accessor-object-property",propertyName:t,message:`Static object property '${t}' in module '${e}' is an accessor.`}}function tn(e){return{kind:"unsupported",moduleId:e,reason:"computed-object-property",message:`Computed object properties in module '${e}' cannot be resolved to static strings.`}}function nn(e,t){return{kind:"unsupported",moduleId:e,reason:"cycle",variableName:t,message:`Resolving variable '${t}' in module '${e}' would cycle through static string values.`}}function on(e,t){return{kind:"unsupported",moduleId:e,reason:"duplicate-object-property",propertyName:t,message:`Static object in module '${e}' has duplicate property '${t}'.`}}function rn(e,t){return{kind:"unsupported",moduleId:e,reason:"non-object-member-value",expressionType:t,message:`Expression type '${t}' in module '${e}' is not a static object value.`}}function sn(e,t,n){return{kind:"unsupported",moduleId:e,reason:"unsupported-object-property-value",propertyName:t,valueType:n,message:`Static object property '${t}' in module '${e}' has unsupported value type '${n}'.`}}function an(e){return{kind:"unsupported",moduleId:e,reason:"object-spread",message:`Object spreads in module '${e}' cannot be resolved to static strings.`}}function un(e,t){return{kind:"unsupported",moduleId:e.moduleId,reason:"static-definition-unsupported",variableName:t,definition:e,message:`Variable '${t}' could not be resolved to a static definition: ${e.message}`}}function cn(e,t){return{kind:"unsupported",moduleId:e,reason:"uninitialized-const",variableName:t,message:`Const variable '${t}' in module '${e}' does not have an initializer.`}}const dn=new Set(["node_modules",".yarn"]);function ln(e,t,n,o=[]){if(!Pn(e,t))return null;const r=ot(n,e),i=gt(r),s=function(e,t){const n=function(e){return e.body.flatMap((e=>("ImportDeclaration"===e.type||"ExportNamedDeclaration"===e.type||"ExportAllDeclaration"===e.type)&&e.source&&rt(e.source)?[e.source.value]:[]))}(e);return t.map(((e,t)=>({source:n[t]??e,resolvedId:e})))}(r,o);return{id:e,ast:r,scopeAnalysis:i,staticDependencies:s,unsupportedDependencies:Dn(r),importsByVariable:pn(r,i,s),exportsByName:fn(r,i,s),starExports:gn(r,s),topLevelBindingsByVariable:yn(r,i)}}function pn(e,t,n){const o=new Map;for(const r of e.body){if("ImportDeclaration"!==r.type||!rt(r.source))continue;const e=In(n,r.source.value);for(const n of r.specifiers){const[r]=t.scopeManager.getDeclaredVariables(n);r&&("ImportSpecifier"!==n.type?o.set(r,{kind:"ImportDefaultSpecifier"===n.type?"default":"namespace",resolvedId:e}):o.set(r,{kind:"named",importedName:En(n.imported),resolvedId:e}))}}return o}function fn(e,t,n){const o=new Map;for(const r of e.body)"ExportNamedDeclaration"!==r.type?"ExportDefaultDeclaration"!==r.type?"ExportAllDeclaration"===r.type&&hn(r,n,o):o.set("default",{kind:"unsupported",reason:"default export"}):mn(r,t,n,o);return o}function mn(e,t,n,o){if(e.declaration)!function(e,t,n){if(!e)return;if("VariableDeclaration"===e.type){for(const o of e.declarations){const e=t.scopeManager.getDeclaredVariables(o);if("Identifier"!==o.id.type){for(const t of e)n.set(t.name,{kind:"unsupported",reason:"binding pattern export"});continue}const[r]=e;r&&n.set(o.id.name,{kind:"local",variable:r})}return}if(("FunctionDeclaration"===e.type||"ClassDeclaration"===e.type)&&e.id){const[o]=t.scopeManager.getDeclaredVariables(e);o&&n.set(e.id.name,{kind:"local",variable:o})}}(e.declaration,t,o);else if(e.source&&rt(e.source)){const t=In(n,e.source.value);for(const n of e.specifiers){if("ExportSpecifier"!==n.type)continue;const e=En(n.exported);"default"!==e?o.set(e,{kind:"re-export",importedName:En(n.local),resolvedId:t}):o.set(e,{kind:"unsupported",reason:"default re-export",resolvedId:t})}}else for(const n of e.specifiers){if("ExportSpecifier"!==n.type)continue;const e=En(n.exported);if("default"===e){o.set(e,{kind:"unsupported",reason:"default export"});continue}const r=wt(En(n.local),t);o.set(e,r?{kind:"local",variable:r}:{kind:"unsupported",reason:"unresolved local export"})}}function hn(e,t,n){const o=Sn(e);o&&rt(e.source)&&n.set(o,{kind:"unsupported",reason:"namespace re-export",resolvedId:In(t,e.source.value)})}function gn(e,t){return e.body.flatMap((e=>"ExportAllDeclaration"!==e.type||Sn(e)||!rt(e.source)?[]:[{resolvedId:In(t,e.source.value)}]))}function yn(e,t){const n=new Map;for(const o of e.body)bn(o,t,n);return function(e,t,n){mt(e,{scopeAnalysis:t,bindings:n},{AssignmentExpression(e,{state:t}){$n(e.left,t.scopeAnalysis,t.bindings)},UpdateExpression(e,{state:t}){$n(e.argument,t.scopeAnalysis,t.bindings)},UnaryExpression(e,{state:t}){"delete"===e.operator&&$n(e.argument,t.scopeAnalysis,t.bindings)},ForInStatement(e,{state:t}){vn(e.left,t.scopeAnalysis,t.bindings)},ForOfStatement(e,{state:t}){vn(e.left,t.scopeAnalysis,t.bindings)}})}(e,t,n),n}function bn(e,t,n){if("VariableDeclaration"===e.type)return void wn(e,t,n);if("ExportNamedDeclaration"===e.type&&"VariableDeclaration"===e.declaration?.type)return void wn(e.declaration,t,n);const o="ExportNamedDeclaration"===e.type||"ExportDefaultDeclaration"===e.type?e.declaration:e;if(o&&("FunctionDeclaration"===o.type||"ClassDeclaration"===o.type)&&o.id){const[e]=t.scopeManager.getDeclaredVariables(o);e&&n.set(e,{kind:"unsupported",reason:`${o.type} binding`})}}function wn(e,t,n){for(const o of e.declarations){const r=t.scopeManager.getDeclaredVariables(o);if("Identifier"!==o.id.type){for(const e of r)n.set(e,{kind:"unsupported",reason:"binding pattern"});continue}const[i]=r;i&&("const"===e.kind?n.set(i,{kind:"const",expression:o.init??null}):n.set(i,{kind:"mutable",declarationKind:e.kind}))}}function vn(e,t,n){"VariableDeclaration"!==e.type&&$n(e,t,n)}function $n(e,t,n){if("Identifier"!==e.type)if("MemberExpression"!==e.type)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"RestElement"!==e.type?"AssignmentPattern"===e.type&&$n(e.left,t,n):$n(e.argument,t,n);else for(const o of e.elements)o&&$n(o,t,n);else for(const o of e.properties)$n("RestElement"===o.type?o.argument:o.value,t,n);else{const o=xn(e);o&&kn(o,t,n,"mutated object binding")}else kn(e,t,n,"reassigned binding")}function kn(e,t,n,o){const r=yt(e,t);if(!r||bt(r)||!n.has(r))return;const i=n.get(r);"mutable"!==i?.kind&&n.set(r,{kind:"unsupported",reason:o})}function xn(e){return"Identifier"===e.type?e:"MemberExpression"===e.type?xn(e.object):void 0}function En(e){return"Identifier"===e.type?e.name:String(e.value)}function Sn(e){const t=e.exported;return t?En(t):void 0}function In(e,t){return e.find((e=>e.source===t))?.resolvedId??t}function Dn(e){const t=[];return mt(e,t,{ImportExpression(e,{state:t}){const n=function(e){return Mn(e.source,"non-literal dynamic import")}(e);An(n)&&t.push({specifier:n,kind:"dynamic-import"})},CallExpression(e,{state:t}){if(function(e){return"Import"===e.callee.type}(e)){const n=function(e){return Mn(e.arguments[0],"non-literal dynamic import")}(e);An(n)&&t.push({specifier:n,kind:"dynamic-import"})}else(function(e){if("Identifier"!==e.callee.type||"require"!==e.callee.name)return!1;const[t]=e.arguments;return!t||!rt(t)||Tn(t.value)})(e)&&t.push({specifier:jn(e),kind:"require"})}}),t}function An(e){return"non-literal dynamic import"===e||Tn(e)}function Pn(e,t){if(!ke.some((t=>e.endsWith(t))))return!1;const n=u.relative(u.resolve(t),e);return!n.startsWith("..")&&!u.isAbsolute(n)&&!n.split(u.sep).some((e=>dn.has(e)))}function jn(e){return Mn(e.arguments[0],"local require")}function Mn(e,t){return rt(e)?e.value:t}function Tn(e){return e.startsWith(".")||e.startsWith("/")}function Cn(e,t){return new Error(`Unsupported local module graph for ${e}: ${t} could hide an action-catalog connectionId.`)}function On(e,t,n){const o=new Set;return function(e,t,n,o){const r=[e],i=new Set;for(;r.length>0;){const s=r.shift();if(i.has(s))continue;i.add(s);const a=t.get(s);if(!a)throw Cn(e,`missing module record for ${s}`);o({entryId:e,moduleId:s,record:a});for(const t of a.unsupportedDependencies)throw Cn(e,`${t.kind} ${t.specifier}`);for(const o of a.staticDependencies){const i=o.resolvedId;if(Pn(i,n)){if(!t.has(i))throw Cn(e,`uncollected local import ${i} from ${a.id}`);r.push(i)}}}}(e,t,n,(({record:e})=>{const n=function(e){const t=new Set,n=new Set;for(const r of e.body)if("ImportDeclaration"===r.type&&"string"==typeof(o=r.source.value)&&(o===Mt||o.startsWith(`${Mt}/`))&&!it(r))for(const e of r.specifiers)it(e)||("ImportNamespaceSpecifier"===e.type?n.add(e.local.name):t.add(e.local.name));var o;return{functions:t,namespaces:n}}(e.ast),r=function(e,t){const n=new Set,o=new Set;for(const r of e.scopeManager.scopes)for(const e of r.variables)bt(e)&&(t.functions.has(e.name)&&n.add(e),t.namespaces.has(e.name)&&o.add(e));return{moduleScope:e,actionFunctions:n,actionNamespaces:o}}(e.scopeAnalysis,n);for(const n of $t(e.ast,r,e.id)){const r=Nn(n,t,e);r&&o.add(r)}})),[...o].sort()}function Nn(e,t,n){const[o]=e.arguments;if(!o||"ObjectExpression"!==o.type)throw Fn(n.id,"non-object action-catalog call arguments");const r=function(e,t){let n;for(const o of e.properties){if("SpreadElement"===o.type)throw Fn(t,"spread object arguments");if(o.computed)throw Fn(t,"computed object property keys");if(_n(o)){if(n)throw Fn(t,"multiple connectionId properties");if("init"!==o.kind)throw Fn(t,"accessor connectionId properties");if(!Rn(o))throw Fn(t,"destructuring pattern in connectionId value");n=o}}return n}(o,n.id);if(!r)return;const i=function(e,t,n){return Ut({modules:e,mutatedImportedObjectVariables:Kt(e),seenVariables:new Set},t,n)}(t,n.id,r.value);if("resolved"===i.kind)return i.value;throw s=n.id,a=`static string resolution ${function(e){return"static-definition-unsupported"===e.reason?`${e.reason}/${e.definition.reason}`:e.reason}(i)}: ${i.message}`,new Error(`Unsupported action-catalog connectionId in ${s}: ${a}.`);var s,a}function Rn(e){const{value:t}=e;return"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&"RestElement"!==t.type&&"AssignmentPattern"!==t.type}function _n(e){return"connectionId"===function(e){if("Identifier"===e.key.type)return e.key.name;if("Literal"===e.key.type&&"string"==typeof e.key.value)return e.key.value;return}(e)}function Fn(e,t){return new Error(`Unsupported action-catalog call in ${e}: ${t} could hide a connectionId.`)}const zn=/^(?:\0|virtual:)/;function Ln(e){const t=new Map;return{plugin:{name:"dd-backend-module-graph-collector",moduleParsed(n){const o=Un(n.id);if(r=o,zn.test(r))return;var r;const i=ln(o,e,n.ast,function(e){return e.importedIdResolutions?.map((({id:e})=>e))??[...e.importedIds]}(n).map(Un));i&&t.set(i.id,i)}},getModuleRecords:()=>t}}function Un(e){return e.split("?")[0]}function Bn(e,t){const n=Ln(t);return{plugin:n.plugin,getAllowedConnectionIds:()=>On(e,n.getModuleRecords(),t)}}function qn(e,t){return{name:e,enforce:"pre",resolveId:e=>t[e]?{id:e,moduleSideEffects:!0}:null,load:e=>t[e]?t[e]:null}}function Vn(e,t,n=[]){return{configFile:!1,root:e,logLevel:"silent",build:{minify:!1,target:"esnext",rollupOptions:{output:{format:"es",exports:"named",inlineDynamicImports:!0},preserveEntrySignatures:"exports-only",treeshake:!1,onwarn(e,t){"MODULE_LEVEL_DIRECTIVE"!==e.code&&t(e)}}},resolve:{extensions:[...ke,".json"]},plugins:[qn("dd-backend-resolve",t),...n]}}function Kn(e){return`${e.relativePath}/${e.name}`}async function Hn(e,t,n,o){const r=Kn(t),i=`virtual:dd-backend-dev:${r}`,s=function(e,t,n){return ft(e,t,n??process.cwd())}(t.name,t.absolutePath,n),a=Bn(t.absolutePath,n);o.debug(`Bundling backend function "${r}" from ${t.absolutePath}`);const u=Vn(n,{[i]:s},[a.plugin]),c=await e({...u,build:{...u.build,write:!1,rollupOptions:{...u.build.rollupOptions,input:i,output:u.build.rollupOptions.output}}}),d=Array.isArray(c)?c[0]:c;if(!("output"in d))throw new Error(`Unexpected vite.build result for "${r}"`);const l="chunk"===d.output[0].type?d.output[0].code:"",p={...t,allowedConnectionIds:a.getAllowedConnectionIds()};return o.debug(`Bundled "${r}" (${l.length} bytes)`),{func:p,code:l}}async function Wn(e,t,n,o,r,i){const s=`https://api.${o.site}/api/v2/app-builder/queries/preview-async`,a=Kn(t);i.debug(`Calling Datadog API: ${s}`);const u=JSON.stringify({data:{type:"queries",attributes:{query:{id:f(),name:a,type:"action",properties:{spec:{fqn:"com.datadoghq.datatransformation.jsFunctionWithActions",inputs:{script:e,allowedConnectionIds:t.allowedConnectionIds,context:{backendFunctionArgs:n}}},onlyTriggerManually:!0}},template_params:{}}}}),c=await r({url:s,method:"POST",type:"json",getData:()=>({data:u,headers:{"Content-Type":"application/json"}})}),d=c.data?.id;if(!d)throw new Error("No receipt ID returned from Datadog API");return i.debug(`Query execution started with receipt: ${d}`),async function(e,t,n,o){const r=`https://api.${t.site}/api/v2/app-builder/queries/execution-long-polling/${e}`,i=10;for(let e=0;e<i;e++){o.debug(`Long-poll attempt ${e+1}/${i}...`);const t=await n({url:r,type:"json"});if(t.errors?.length){const e=t.errors.map((e=>e.detail||e.title)).join("; ");throw new Error(`Query execution failed: ${e}`)}const s=t.data?.attributes;if(o.debug(`Long-poll response, done: ${s?.done}`),s?.done){if(!s.outputs)throw new Error("Query execution completed without outputs");return s.outputs}}throw new Error("Query execution timed out")}(d,o,r,i)}function Jn(e,t,n){e.statusCode=t,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify({success:!1,error:n}))}class Gn extends Error{constructor(e,t){super(t),this.statusCode=e}}async function Yn(e,t,n){const{functionName:o,args:r=[]}=await function(e){return new Promise(((t,n)=>{let o="";e.on("data",(e=>{o+=e.toString()})),e.on("end",(()=>{try{t(JSON.parse(o))}catch{n(new Error("Invalid JSON body"))}})),e.on("error",n)}))}(e);if(!o||"string"!=typeof o)throw new Gn(400,"Missing or invalid functionName");const i=t.get(o);if(!i)throw new Gn(404,`Backend function "${o}" not found`);return{...await n(i),args:r}}function Qn(e,t,n,o,r,i){const s=t=>Hn(e,t,r,i),a=t();return a.length>0&&i.info(`Dev server middleware active for ${a.length} backend function(s): ${a.map((e=>e.name)).join(", ")}`),o||i.warn(`Auth credentials not configured. The /__dd/executeAction endpoint will be unavailable. ${et}`),(e,r,a)=>{if("POST"!==e.method)return void a();const u=(c=t(),new Map(c.map((e=>[lt(e),e]))));var c;if("/__dd/debugBundle"===e.url)(async function(e,t,n,o){try{const{code:r}=await Yn(e,n,o);t.statusCode=200,t.setHeader("Content-Type","text/plain"),t.end(r)}catch(e){Jn(t,e instanceof Gn?e.statusCode:500,e instanceof Error?e.message:"Internal server error")}})(e,r,u,s).catch((()=>{Jn(r,500,"Unexpected error")}));else if("/__dd/executeAction"===e.url){if(!o)return void Jn(r,400,`Auth credentials not configured. ${et}`);(async function(e,t,n,o,r,i,s){try{const{func:a,code:u,args:c}=await Yn(e,n,o),d=Kn(a);s.debug(`Executing action: ${d} with args`);const l=await Wn(u,a,c,r,i,s);t.statusCode=200,t.setHeader("Content-Type","application/json"),t.end(JSON.stringify({success:!0,result:l}))}catch(e){const n=e instanceof Gn?e.statusCode:500,o=e instanceof Error?e.message:"Internal server error";s.debug(`Error handling executeAction: ${o}`),Jn(t,n,o)}})(e,r,u,s,n,o,i).catch((()=>{Jn(r,500,"Unexpected error")}))}else a()}}const Zn=async(e,t)=>{const n=(await Promise.all(e.map((e=>w(e,{absolute:!0,cwd:t,nodir:!0}))))).flat(),o=Array.from(new Set(n)).map((e=>u.relative(t,e))),r=(e=>{if(0===e.length)return"";const t=e[0].split(u.sep);let n="";for(let o=0;o<t.length-1;o++){const r=t.slice(0,o+1).join(u.sep);if(!e.every((e=>e.startsWith(`${r}${u.sep}`))))break;n=r}return n})(o);return o.map(((e,t)=>{const o=r?e.slice(r.length+1):e;return{absolutePath:n[t],relativePath:o.split(u.sep).join("/")}}))},Xn=(e,t)=>X(t)?O:t.startsWith(e)||u.isAbsolute(t)?t:u.resolve(e,t),eo=(e,t)=>{let n,o=Xn(process.cwd(),e);for(;!n;){const e=u.resolve(o,t);if(Pe(e)&&(n=e),o=o.split(u.sep).slice(0,-1).join(u.sep),[u.sep,""].includes(o))break}return n},to=(e,t)=>{const n=[...e].map((e=>Xn(t||process.cwd(),e).split(u.sep))),o=n.length?Math.min(...n.map((e=>e.length))):0,r=[];for(let e=0;e<o;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;r.push(t)}return r.length>0&&r.join(u.sep)||u.sep},no=t.bold.red,oo=t.bold.yellow,ro=e=>{const t=eo(e,"package.json");if(t)try{const e=Ae(t);return JSON.parse(e)}catch(e){return}},io=(e,t,n)=>{if(n?.name&&n?.identifier)return{identifier:n?.identifier,name:n.name};const o=ro(e);o||t.warn(oo("No package.json found to infer the app name."));const r=n?.name||o?.name?.trim();r||t.error(no("Unable to determine the app name to compute the app identifier."));const i=((e,t)=>{const n=e||(e=>{if(e&&e.repository)return"string"==typeof e.repository?e.repository:"url"in e.repository?e.repository.url:void 0})(t);if(!n)return;const o=re(n.trim());return o?o.replace(/\.git$/,""):void 0})(n?.url,o);i||t.error(no("Unable to determine the git remote to compute the app identifier."));const s=n?.identifier||((e,t)=>{if(!e||!t)return;const n=`${e}:${t}`;return p("sha256").update(n).digest("hex").slice(0,32)})(i,r);return s&&r||t.error(no("Unable to compute the app identifier.")),{identifier:s,name:r}},so=t.green.bold,ao=t.yellow.bold,uo=t.cyan.bold,co=t.bold,lo=(e,t={},n)=>async()=>{const o=await je(e,{contentType:"application/zip",filename:ve});return J({getForm:()=>{const e=new FormData;e.append("name",n),e.append("bundle",o,ve);const t=q("APPS_VERSION_NAME")?.trim();return t&&e.append("version",t),e},defaultHeaders:t,zip:!1})},po=async(e,t,n)=>{const o=[],r=[],i=t.doAuthenticatedRequest;if(!t.identifier)return o.push(new Error("No app identifier provided")),{errors:o,warnings:r};const s=(a=t.site,u=t.identifier,q("APPS_INTAKE_URL")||`https://api.${a}/${we}/${u}/upload`);var a,u;const d=W({bundler:t.bundlerName,plugin:"apps",version:t.version}),l=se({identifier:t.identifier,intakeUrl:s,defaultHeaders:`\n${JSON.stringify(d,null,2)}`}),p=`an archive of:\n - ${so(e.assets.length.toString())} files\n - ${so(v(e.size))}\n\nWith the configuration:\n${l}`;if(t.dryRun)return n.error(`\n${uo("Dry run enabled")}\n\nSkipping assets upload.\nWould have uploaded ${p}`),{errors:o,warnings:r};try{const o=await i({url:s,method:"POST",type:"json",getData:lo(e.archivePath,d,t.name),onRetry:(e,t)=>{const o=`Failed to upload archive (attempt ${ao(`${t}/5`)}): ${e.message}`;r.push(o),n.warn(o)}});if(n.debug(`Uploaded ${p}\n`),o.app_builder_id){const e=`https://app.${t.site}/app-builder/apps/${o.app_builder_id}`;n.info(`Your application is available at:\n ${uo(e)}`)}if(o.version_id){const e=((e,t)=>`https://api.${e}/${we}/${t}/release/live`)(t.site,t.identifier);await i({url:e,method:"PUT",type:"json",getData:async()=>({data:c.from(JSON.stringify({version_id:o.version_id})),headers:{"Content-Type":"application/json",...d}}),onRetry:(e,t)=>{const o=`Failed to release version (attempt ${ao(`${t}/5`)}): ${e.message}`;r.push(o),n.warn(o)}}),n.info(`Published uploaded version ${co(o.version_id)} to live.`)}}catch(e){const t=e instanceof Error?e:new Error(String(e));o.push(t)}return{errors:o,warnings:r}},fo=t.yellow.bold,mo=t.red.bold,ho="manifest.json";async function go(e){const t=await r.mkdtemp(u.join(h.tmpdir(),"dd-apps-manifest-")),n=u.join(t,ho);try{await r.writeFile(n,JSON.stringify(function(e){const t={};for(const n of e)t[lt(n)]={allowedConnectionIds:[...n.allowedConnectionIds]};return{backend:{functions:t}}}(e),null,2))}catch(e){throw await Se(t),e}return{manifestAsset:{absolutePath:n,relativePath:ho},cleanup:()=>Se(t)}}const yo=async({backendOutputs:e,backendFunctions:t,context:n,doAuthenticatedRequest:o,options:i})=>{const a=n.getLogger(be),{auth:c,buildRoot:d,bundler:{name:l,outDir:p},git:f,version:m}=n,g=a.time("handle assets");let y,w,v;try{const n=a.time("resolve identifier"),{name:g,identifier:v}=io(d,a,{url:f?.remote,name:i.name,identifier:i.identifier});if(!v||!g)throw new Error("Missing apps identification.\nEither:\n - pass an 'options.apps.identifier' and 'options.apps.name' to your plugin's configuration.\n - have a 'name' and a 'repository' in your 'package.json'.\n - have a valid remote url on your git project.\n");n.end();const $=u.relative(d,p),k=[...i.include,`${$}/**/*`],x=await Zn(k,d);if(!x.length)return void a.debug("No assets to upload.");const E=new Set(e.values()),S=x.filter((e=>!E.has(e.absolutePath))).map((e=>({...e,relativePath:`frontend/${e.relativePath}`})));for(const[t,n]of e)S.push({absolutePath:n,relativePath:`backend/${t}.js`});const{manifestAsset:I,cleanup:D}=await go(t);w=D,S.push(I);const A=a.time("archive assets"),P=await(async e=>{const t=await r.mkdtemp(u.join(h.tmpdir(),"dd-apps-")),n=u.join(t,ve),o=new b;for(const t of e)o.file(t.relativePath,s.createReadStream(t.absolutePath),{binary:!0,compression:"DEFLATE",compressionOptions:{level:9}});await new Promise(((e,t)=>{const r=s.createWriteStream(n),i=o.generateNodeStream({type:"nodebuffer",streamFiles:!0,compression:"DEFLATE",compressionOptions:{level:9}});i.on("error",t),r.on("error",t),r.on("close",e),i.pipe(r)}));const{size:i}=await r.stat(n);return{archivePath:n,size:i,assets:e}})(S);A.end(),y=u.dirname(P.archivePath);const j=a.time("upload assets"),{errors:M,warnings:T}=await po(P,{bundlerName:l,doAuthenticatedRequest:o,dryRun:i.dryRun,identifier:v,name:g,site:c.site,version:m},a);if(j.end(),T.length>0&&a.warn(`${fo("Warnings while uploading assets:")}\n - ${T.join("\n - ")}`),M.length>0){const e=M.map((e=>e.cause||e.stack||e.message||e)).join("\n - ");throw new Error(` - ${e}`)}}catch(e){v=e,a.error(`${mo("Failed to upload assets:")}\n${e?.message||e}`)}if(y&&await Se(y),w&&await w(),g.end(),v)throw v};const bo=u.join(T,"./apps-runtime.mjs"),wo=async()=>{throw new Error("Dry run should not perform authenticated requests.")},vo=({bundler:e,context:t,options:n})=>{const o=t.getLogger(be),{auth:r,buildRoot:s}=t;t.inject({type:"file",position:Te.MIDDLE,value:bo});const{setBackendFunctions:a,getBackendFunctions:c}=function(){const e=new Map;return{setBackendFunctions(t,n){e.set(t,n)},getBackendFunctions:()=>Array.from(e.values()).flat()}}();return{transform:{filter:{id:{include:[$e],exclude:[/node_modules/,/[/\\]dist[/\\]/]}},handler(e,t){const n=st(this.parse(e),t);if(0===n.length)return o.warn(`Backend file ${t} has no exported functions. Did you forget to add a named export?`),a(t,[]),{code:"",map:null};const{functions:r,proxyCode:i}=function(e,t,n){const o=u.relative(n,t).replace($e,""),r=[],i=[];for(const n of e){const e={relativePath:o,name:n,absolutePath:t,allowedConnectionIds:[]};r.push(e),i.push({exportName:n,queryName:lt(e)})}return{functions:r,proxyCode:pt(i)}}(n,t,s);return a(t,r),o.debug(`Generated proxy for ${t} with ${r.length} export(s)`),{code:i,map:null}}},async closeBundle(){let a,d=new Map,l=c();if(l.length>0){const t=await async function(e,t,n,o){const r=await i(u.join(g(),"dd-apps-backend-")),s=new Map,a=new Map;o.debug(`Building ${t.length} backend function(s) via vite.build()`);for(const i of t){const t=lt(i),c=`\0dd-backend:${t}`,d=ft(i.name,i.absolutePath,n),l=Bn(i.absolutePath,n),p=Vn(n,{[c]:d},[l.plugin]),f=await e({...p,build:{...p.build,write:!0,outDir:r,emptyOutDir:!1,rollupOptions:{...p.build.rollupOptions,input:{[t]:c},output:{...p.build.rollupOptions.output,entryFileNames:"[name].js"}}}}),m=Array.isArray(f)?f[0]:f;if("output"in m)for(const e of m.output){if("chunk"!==e.type||!e.isEntry)continue;const n=u.resolve(r,e.fileName);s.set(t,n),o.debug(`Backend function "${t}" output: ${n}`)}a.set(i.absolutePath,l.getAllowedConnectionIds())}return{outDir:r,outputs:s,functions:t.map((e=>({...e,allowedConnectionIds:a.get(e.absolutePath)})))}}(e.build,l,s,o);a=t.outDir,d=t.outputs,l=t.functions}try{const e=n.dryRun?wo:nt(n.authOverrides.method,r,o);await yo({backendOutputs:d,backendFunctions:l,context:t,doAuthenticatedRequest:e,options:n})}finally{a&&await Se(a)}},configureServer(t){let i;try{i=nt(n.authOverrides.method,r,o)}catch(e){if(!(e instanceof tt))throw e}t.middlewares.use(Qn(e.build,c,r,i,s,o))}}},$o=({options:e,context:t,bundler:n})=>{const o=t.getLogger(be),r=Ee(e);return"vite"!==t.bundler.name?(o.warn(`The apps plugin only supports Vite; skipping under '${t.bundler.name}'.`),[]):[{name:be,enforce:"post",vite:vo({bundler:n,context:t,options:r})}]},ko="errorTracking",xo="datadog-error-tracking-plugin",Eo=(e,n,o)=>{if(".map"!==u.extname(o))throw new Error(`The file ${t.green.bold(o)} is not a sourcemap.`);const r=o.replace(/\.map$/,""),i=u.relative(n,r),s=((e,t)=>{if(e.startsWith("/"))return u.join(e,t);try{const n=e.replace(/\/*$/,"/"),o=new URL(n),r=t.replace(/^[\\/]*/,"");return new URL(r,o).href}catch{return`${e}${t}`}})(e,i);return{minifiedFilePath:r,minifiedUrl:s,relativePath:i}},So=/[/]+|[\\]+/g,Io=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,Do=(e,t)=>{const n=e.replace(Io,"").split(So),o=t.replace(Io,"").split(So),r=n.join("/");let i="";for(let e=0;e<o.length;e+=1){const t=o.slice(-e).join("/");r.startsWith(t)&&(i=t)}return i},Ao=async(e,t,n,o)=>{const r=await(async(e,t)=>{const[n,o]=await Promise.all([Me(e.minifiedFilePath),Me(e.sourcemapFilePath)]);return{file:n,sourcemap:o,repeatedPrefix:Do(e.relativePath,t)}})(e,n),i=[],s=[],a=new Map([["event",{type:"string",options:{contentType:"application/json",filename:"event"},value:JSON.stringify({...t,minified_url:e.minifiedUrl})}],["source_map",{type:"file",path:e.sourcemapFilePath,options:{filename:"source_map",contentType:"application/json"}}],["minified_file",{type:"file",path:e.minifiedFilePath,options:{filename:"minified_file",contentType:"application/javascript"}}]]);if(o)try{a.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:o.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{s.push(`${u.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:o.hash,repository_url:o.remote}],version:1})})}catch(t){s.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return r.file.empty&&i.push(`Minified file is empty: ${e.minifiedFilePath}`),r.file.exists||i.push(`Minified file not found: ${e.minifiedFilePath}`),r.sourcemap.empty&&i.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),r.sourcemap.exists||i.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),r.repeatedPrefix&&s.push(`The minified file path contains a repeated pattern with the minified path prefix: ${r.repeatedPrefix}`),{content:a,errors:i,warnings:s}},Po=e=>{const t=e.message.match(/HTTP (\d{3})/);return t?`status_code:${t[1]}`:"status_code:unknown"},jo=e=>{const t=Po(e);return"status_code:unknown"!==t?`error_type:http_${t.replace("status_code:","")}`:`error_type:${ie(e.name||"unknown")}`},Mo=(e,t,n)=>{const o=((e,t)=>`${e}|${t.join("|")}`)(t,n),r=e.metrics.get(o);r?r.value++:e.metrics.set(o,{name:t,value:1,tags:n})},To=(e,t,n)=>{Mo(e,"retry",[...e.baseTags,`attempt:${n}`,Po(t),jo(t)])},Co=(e,t)=>{Mo(e,"failure",[...e.baseTags,Po(t),jo(t)])},Oo=(e,t)=>{if(!t.sendMetrics)return;if(!e.metrics.size)return;const n=(e=>{const t=Math.floor(Date.now()/1e3);return Array.from(e.metrics.values()).map((e=>({metric:`sourcemaps.upload.${e.name}`,type:"count",points:[[t,e.value]],tags:e.tags})))})(e);for(const e of n)t.addMetric(e)},No=t.green.bold,Ro=t.yellow.bold,_o=t.red.bold,Fo=(e,t={})=>async()=>J({getForm:async()=>{const t=new FormData;for(const[n,o]of e.content){const e="file"===o.type?await je(o.path,o.options):new Blob([o.value],{type:o.options.contentType});t.append(n,e,o.options.filename)}return t},defaultHeaders:t,zip:!0}),zo=async(e,t,n,o)=>{const r=[],i=[];if(!n.apiKey)return r.push({error:new Error("No authentication token provided")}),{errors:r,warnings:i};if(0===e.length)return i.push("No sourcemaps to upload"),{errors:r,warnings:i};const s=o.time("Queue uploads"),a=new($.default?$.default:$)({concurrency:t.maxConcurrency}),u=(c=n.site,q("SOURCEMAP_INTAKE_URL")||`https://sourcemap-intake.${c}/api/v2/srcmap`);var c;const d=W({bundler:n.bundlerName,plugin:"sourcemaps",version:n.version}),l=(e=>({metrics:new Map,baseTags:[`service:${e.service}`]}))(t),p=se({...t,intakeUrl:u,outDir:n.outDir,defaultHeaders:`\n${JSON.stringify(d,null,2)}`}),f=`\nUploading ${No(e.length.toString())} sourcemaps with configuration:\n${p}`;o.debug(f);const m=[];for(const s of e){const e={sourcemap:s.content.get("source_map")?.path.replace(n.outDir,"."),file:s.content.get("minified_file")?.path.replace(n.outDir,".")};m.push(a.add((async()=>{try{await Y({auth:{apiKey:n.apiKey},url:u,method:"POST",getData:Fo(s,d),onRetry:(t,n)=>{To(l,t,n);const r=`Failed to upload ${Ro(e.sourcemap)} | ${Ro(e.file)}:\n ${t.message}\nRetrying ${n}/5`;i.push(r),o.debug(r)}})}catch(n){if(Co(l,n),r.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}s.end(),o.debug(`Queued ${No(e.length.toString())} uploads.`);try{await Promise.all(m),await a.onIdle()}finally{Oo(l,n)}return{warnings:i,errors:r}},Lo=async(e,t,n)=>{const o=n.time("get sourcemaps files"),r=((e,t)=>{if(!t.outputs||0===t.outputs.length)throw new Error("No output files found.");return t.outputs.filter((e=>e.filepath.endsWith(".map"))).map((e=>e.filepath)).map((n=>({...Eo(e.minifiedPathPrefix,t.outDir,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,{outDir:t.outDir,outputs:t.outputs});o.end();const i=n.time("send sourcemaps");await(async(e,t,n,o)=>{const r=Date.now(),i=t.minifiedPathPrefix,s={git_repository_url:n.git?.remote,git_commit_sha:n.git?.hash,plugin_version:n.version,project_path:n.outDir,service:t.service,type:"js_sourcemap",version:t.releaseVersion},a=o.time("Compute payloads"),u=await Promise.all(e.map((e=>Ao(e,s,i,n.git))));a.end();const c=u.map((e=>e.errors)).flat(),d=u.map((e=>e.warnings)).flat();if(d.length>0&&o.warn(`Warnings while preparing payloads:\n - ${d.join("\n - ")}`),c.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${c.join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e);return}const l=o.time("Upload sourcemaps"),{errors:p,warnings:f}=await zo(u,t,{apiKey:n.apiKey,bundlerName:n.bundlerName,version:n.version,outDir:n.outDir,site:n.site,sendMetrics:n.sendMetrics,addMetric:n.addMetric},o);if(l.end(),o.debug(`Done uploading ${No(`${e.length-p.length}/${e.length}`)} sourcemaps in ${No(ne(Date.now()-r))}.`),p.length>0){const e=`Failed to upload some sourcemaps:\n - ${p.map((({metadata:e,error:t})=>{const n=t.cause||t.stack||t.message;return e?`${_o(e.file)} | ${_o(e.sourcemap)} :\n${n}`:n})).join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e)}f.length>0&&o.warn(`Warnings while uploading sourcemaps:\n - ${f.join("\n - ")}`)})(r,e.sourcemaps,{addMetric:t.addMetric,apiKey:t.apiKey,bundlerName:t.bundlerName,git:t.git,outDir:t.outDir,sendMetrics:t.sendMetrics,site:t.site,version:t.version},n),i.end()},Uo=e=>{const n=t.bold.red,o=e[ko]||{},r={errors:[]};if(o.sourcemaps){const t=o.sourcemaps,i=t.releaseVersion||e.metadata?.version;i||r.errors.push(`${n("sourcemaps.releaseVersion")} is required (set it directly or via ${n("metadata.version")}).`),t.releaseVersion&&e.metadata?.version&&t.releaseVersion!==e.metadata.version&&r.errors.push(`${n("sourcemaps.releaseVersion")} must match ${n("metadata.version")} when both are configured.`),t.service||r.errors.push(`${n("sourcemaps.service")} is required.`),t.minifiedPathPrefix||r.errors.push(`${n("sourcemaps.minifiedPathPrefix")} is required.`),t.minifiedPathPrefix&&!(e=>{let t;try{t=new URL(e).host}catch{}return!(!t&&!e.startsWith("/"))})(t.minifiedPathPrefix)&&r.errors.push(`${n("sourcemaps.minifiedPathPrefix")} must be a valid URL or start with '/'.`),i&&(r.config={bailOnError:!1,dryRun:!1,maxConcurrency:20,...t,releaseVersion:i})}return r},Bo=({options:e,context:t})=>{const n=t.getLogger(xo),o=n.time("validate options"),r=((e,t)=>{const n=[],o=Uo(e);if(n.push(...o.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${xo}.`);return{...e[ko],sourcemaps:o.config}})(e,n);o.end();const i=ge(e,"metrics",n);let s,a,u=!1;const c=async()=>{if(!r.sourcemaps||u)return;u=!0;const e=n.time("sourcemaps process");await Lo(r,{apiKey:t.auth.apiKey,bundlerName:t.bundler.name,git:s,addMetric:t.addMetric,outDir:t.bundler.outDir,outputs:a?.outputs||[],sendMetrics:i,site:t.auth.site,version:t.version},n),e.end()};return[{name:xo,enforce:"post",async git(e){s=e,a&&await c()},async buildReport(t){a=t,!s&&te(e)||await c()},async asyncTrueEnd(){u||await c()}}]},qo="liveDebugger",Vo="datadog-live-debugger-plugin",Ko="if(typeof globalThis.$dd_probes==='undefined'){globalThis.$dd_probes=function(){}}",Ho="__DD_LIVE_DEBUGGER_BUILD__",Wo=e=>void 0===e?Ko:`${Ko};if(typeof globalThis.${Ho}==='undefined'){globalThis.${Ho}={version:${JSON.stringify(e)}}}`;function Jo(e){return"function"==typeof e?e:e.default}function Go(e,t,n,o,r){const i=u.relative(t,e).replace(/\\/g,"/"),s=Yo(n,r);if(s)return`${i};${s}`;const a=function(e){const t=e.node.loc?.start.line??0,n=e.node.loc?.start.column??0;return`${t}:${n}`}(n);return`${i};<anonymous>@${a}:${o}`}function Yo(e,t){const n=e.node,o=e.parent;return"id"in n&&t.isIdentifier(n.id)?n.id.name:t.isObjectMethod(n)||t.isClassMethod(n)||t.isClassPrivateMethod(n)?Xo(n.key,t):t.isVariableDeclarator(o)&&t.isIdentifier(o.id)?o.id.name:t.isAssignmentExpression(o)?function(e,t){if(t.isIdentifier(e))return e.name;if(t.isMemberExpression(e)||t.isOptionalMemberExpression(e)){const n=Qo(e.object,t),o=Zo(e.property,e.computed,t);if(n&&o)return`${n}.${o}`}return null}(o.left,t):t.isObjectProperty(o)||t.isClassProperty(o)||t.isClassPrivateProperty(o)?Xo(o.key,t):null}function Qo(e,t){if(t.isIdentifier(e))return e.name;if(t.isThisExpression(e))return"this";if(t.isMemberExpression(e)||t.isOptionalMemberExpression(e)){const n=Qo(e.object,t),o=Zo(e.property,e.computed,t);if(n&&o)return`${n}.${o}`}return null}function Zo(e,t,n){return n.isPrivateName(e)&&n.isIdentifier(e.id)?`#${e.id.name}`:t?null:n.isIdentifier(e)?e.name:null}function Xo(e,t){return t.isIdentifier(e)?e.name:t.isStringLiteral(e)||t.isNumericLiteral(e)||t.isBigIntLiteral(e)?String(e.value):t.isPrivateName(e)&&t.isIdentifier(e.id)?`#${e.id.name}`:null}function er(e,t){if(e.node.leadingComments)for(const n of e.node.leadingComments)if(n.value.includes(t))return!0;return!1}function tr(e,t){const n=[];if(t.isBlockStatement(e.body)){const o=e.params.flatMap((e=>ar(e,t))),r=new Set(o),i="id"in e&&t.isIdentifier(e.id)?e.id.name:"";for(const o of e.body.body)if(t.isVariableDeclaration(o)){const e=o.end;if(null==e)continue;for(const s of o.declarations)for(const o of ar(s.id,t))r.has(o)||o===i||n.push({name:o,declarationEnd:e,temporalDeadZones:[]})}}const o=n.length>25?n.slice(0,25):n;if(t.isBlockStatement(e.body)){const n=o.map((({name:e})=>e)),r=new Set(n),i=function(e,t,n){const o=new Map;for(const r of e.body)nr(r,t,o,n);return o}(e.body,r,t);for(const e of o)e.temporalDeadZones=i.get(e.name)??[]}return o}function nr(e,t,n,o){o.isFunctionDeclaration(e)||o.isClassDeclaration(e)||(o.isBlockStatement(e)?or(e,t,n,o):o.isIfStatement(e)?(nr(e.consequent,t,n,o),e.alternate&&nr(e.alternate,t,n,o)):o.isForStatement(e)||o.isForInStatement(e)||o.isForOfStatement(e)||o.isWhileStatement(e)||o.isDoWhileStatement(e)?nr(e.body,t,n,o):o.isSwitchStatement(e)?function(e,t,n,o){for(const r of e.cases){rr(r.consequent,e.start,t,n,o);for(const e of r.consequent)nr(e,t,n,o)}}(e,t,n,o):o.isTryStatement(e)?(or(e.block,t,n,o),e.handler&&or(e.handler.body,t,n,o),e.finalizer&&or(e.finalizer,t,n,o)):(o.isLabeledStatement(e)||o.isWithStatement(e))&&nr(e.body,t,n,o))}function or(e,t,n,o){rr(e.body,e.start,t,n,o);for(const r of e.body)nr(r,t,n,o)}function rr(e,t,n,o,r){if(null!=t)for(const i of e)r.isVariableDeclaration(i)&&"var"!==i.kind?ir(i,t,n,o,r):r.isClassDeclaration(i)&&i.id&&sr(i.id.name,t,i.end,n,o)}function ir(e,t,n,o,r){for(const i of e.declarations)for(const s of ar(i.id,r))sr(s,t,e.end,n,o)}function sr(e,t,n,o,r){if(null==n||!o.has(e))return;const i=r.get(e)??[];i.push({start:t,end:n}),r.set(e,i)}function ar(e,t){return t.isIdentifier(e)?[e.name]:t.isRestElement(e)?t.isIdentifier(e.argument)?[e.argument.name]:ar(e.argument,t):t.isAssignmentPattern(e)?ar(e.left,t):t.isObjectPattern(e)?e.properties.flatMap((e=>t.isRestElement(e)?ar(e.argument,t):ar(e.value,t))):t.isArrayPattern(e)?e.elements.flatMap((e=>e?ar(e,t):[])):t.isTSParameterProperty(e)&&t.isIdentifier(e.parameter)?[e.parameter.name]:[]}const ur=["@babel/parser","@babel/traverse","@babel/types","magic-string"];let cr,dr,lr,pr,fr=!1;function mr(e){try{return function(e){switch(e){case"@babel/parser":return C("@babel/parser");case"@babel/traverse":return C("@babel/traverse");case"@babel/types":return C("@babel/types");case"magic-string":return C("magic-string");default:throw new Error(`Unknown peer dependency: ${e}`)}}(e)}catch(e){throw function(e){if(!function(e){if(!(e instanceof Error))return!1;const t=e.code;if("MODULE_NOT_FOUND"!==t&&"ERR_MODULE_NOT_FOUND"!==t)return!1;return ur.some((t=>e.message.includes(t)))}(e))return e instanceof Error?e:new Error(String(e));const t=ur.find((t=>e.message.includes(t))),n=t??ur.join(", ");return new Error(`Datadog Live Debugger could not load "${n}". It is an optional peer dependency that must be installed in your project when the \`liveDebugger\` plugin is enabled. Install the peer dependencies with: \`npm install --save-dev ${ur.join(" ")}\` (or the yarn/pnpm/bun equivalent). Underlying error: ${e.message}`)}(e)}}const hr=/\bfunction\b|=>|\bclass\b|\)\s*\{/;function gr(e){const{code:t,filePath:n,buildRoot:o,honorSkipComments:r,functionTypes:i,namedOnly:s}=e;let a=0,u=0,c=0,d=0,l=0;if(function(e){return/['"][^'"]*(?:@css-module:|\?worker\b|\?sprite\b|dynamic!)[^'"]*['"]/.test(e)}(t))return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:1,skippedUnsupportedCount:d,totalFunctions:l};if(!hr.test(t))return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l};fr||(cr=mr("@babel/parser").parse,dr=Jo(mr("@babel/traverse")),lr=mr("@babel/types"),pr=Jo(mr("magic-string")),fr=!0);const p=cr(t,{sourceType:"unambiguous",plugins:["jsx","typescript"],sourceFilename:n}),f=[],m=new Map,h=new Set,g=new Map,y=new Map;let b=0;if(dr(p,{Function(e){l++;const t=function(e,t){if(t.isClassMethod(e.node)&&"constructor"===e.node.kind&&xr(e,t))return e.node;return}(e,lr);if(t&&(m.set(t,t.body.start),g.set(t,function(e,t){const n=[];for(const o of e)wr(o,n,t);return n}(t.body.body,lr))),!function(e,t){const n=e.node;return!(n.generator||t.isClassMethod(n)&&"constructor"===n.kind)}(e,lr))return void d++;if(r&&function(e,t,n){let o=e;for(;o;){if(er(o,t))return!0;if(n.isStatement(o.node)||n.isExportDeclaration(o.node)){if(o.parentPath&&n.isExportDeclaration(o.parentPath.node))return er(o.parentPath,t);break}o=o.parentPath}return!1}(e,"@dd-no-instrumentation",lr))return void c++;if(i&&!i.includes(function(e,t){if(t.isFunctionDeclaration(e))return"functionDeclaration";if(t.isArrowFunctionExpression(e))return"arrowFunction";if(t.isObjectMethod(e))return"objectMethod";if(t.isClassPrivateMethod(e))return"classPrivateMethod";if(t.isClassMethod(e))return"classMethod";return"functionExpression"}(e.node,lr)))return void d++;if(s&&!Yo(e,lr))return void d++;let p=0;if(!Yo(e,lr)){const t=e.parentPath?.node;t&&(p=y.get(t)||0,y.set(t,p+1))}const w=Go(n,o,e,p,lr);try{const t=e.node,n=b++,o=`$dd_p${n}`,r=function(e,t){const n=[];for(const o of e.params)for(const e of ar(o,t))"this"!==e&&n.push(e);return n.length>25?n.slice(0,25):n}(t,lr),i=tr(t,lr),s=lr.isArrowFunctionExpression(t)&&!lr.isBlockStatement(t.body),a=s&&lr.isSequenceExpression(t.body),c=function(e,t){if(t.isFunction(e.node)&&!t.isArrowFunctionExpression(e.node))return;let n=e.parentPath;for(;n;){const e=n.node;if(t.isClassMethod(e)&&"constructor"===e.kind){if(!xr(n,t))return;return{node:e,parent:n.parent,parentPath:n.parentPath}}if(t.isFunction(e)){if(t.isArrowFunctionExpression(e)){n=n.parentPath;continue}return}n=n.parentPath}return}(e,lr),d=null!=c;c&&(h.add(c.node),m.set(c.node,c.node.body.start));const l=[],p=s||!lr.isBlockStatement(t.body)||!Ir(t.body.body,lr);let g;if(!s&&lr.isBlockStatement(t.body)&&Sr(t.body.body,l,lr),!s&&lr.isBlockStatement(t.body)&&t.body.directives.length>0){g=t.body.directives[t.body.directives.length-1].end}f.push({bodyStart:t.body.start,bodyEnd:t.body.end,functionEnd:t.end,isExpressionBody:s,hasSequenceExpressionBody:a,aliasesExpressionBodySuperCall:d&&s&&kr(t.body,lr),needsTrailingReturn:p,useThisAlias:d,bodyParenStart:s&&"number"==typeof t.body.extra?.parenStart?t.body.extra.parenStart:void 0,directivesEnd:g,functionId:w,probeVarName:o,probeIdx:String(n),entryVars:r,localVars:i,returns:l}),u++}catch(e){a++}}}),0===u)return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l};const w=new pr(t),v=function(e){const t=new Set;for(const n of e)n.aliasesExpressionBodySuperCall&&t.add($r({start:n.bodyStart,end:n.bodyEnd}));return t}(f),$=function(e,t,n,o){const r=[];for(const i of e){const e=t.get(i);null!=e&&r.push({bodyStart:e,superCalls:(n.get(i)??[]).filter((e=>!o.has($r(e))))})}return r}(h,m,g,v);for(let e=f.length-1;e>=0;e--)yr(w,t,f[e]);for(const e of $)br(w,t,e);return{code:w.toString(),map:w.generateMap({source:n,hires:!0}),failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l}}function yr(e,t,n){const{probeVarName:o,probeIdx:r,functionId:i,entryVars:s,localVars:a,returns:u,bodyStart:c,bodyEnd:d,functionEnd:l,isExpressionBody:p,hasSequenceExpressionBody:f,aliasesExpressionBodySuperCall:m,useThisAlias:h,bodyParenStart:g,directivesEnd:y}=n,b=`$dd_rv${r}`,w=h?"$dd_t":"this",v=s.join(", "),$=""!==v,k=`{${v}}`,x=$?`, ${k}`:"";const E=`const ${o} = $dd_probes('${i.replace(/['\\\n\r\u2028\u2029]/g,(e=>{switch(e){case"'":return"\\'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}}))}');`,S=`if (${o}) $dd_entry(${o}, ${w}${x});`,I=`catch(e) { if (${o}) $dd_throw(${o}, e, ${w}${x}); throw e; }`;if(p){if(null!=g){const n=function(e,t,n){const o=[];for(let r=t;r<n;r++)"("===e[r]&&o.push(r);return o}(t,g,c),o=function(e,t,n){const o=[];for(let r=n-1;r>=t;r--)")"===e[r]&&o.push(r);return o}(t,d,l),r=Math.min(n.length,o.length);for(let t=0;t<r;t++){const r=n[t],i=o[t];e.remove(r,r+1),e.remove(i,i+1)}}const n=["{",E,"try {",S,m?`const ${b} = ($dd_t = `:`const ${b} = `].filter(Boolean).join("\n");let r=f?");":";";m&&(r=f?"));":");");const i=[r,`if (${o}) $dd_return(${o}, ${b}, ${w}${Er(k,$,a,d)});`,`return ${b};`,`} ${I}`,"}"].join("\n");if(d-c>=2){const o=f?`${n}(${t[c]}`:n+t[c];e.update(c,c+1,o),e.appendRight(d,i)}else e.update(c,d,n+t.slice(c,d)+i)}else{const r=[E,"try {",`let ${b};`,S].filter(Boolean).join("\n");for(const t of u){const n=Er(k,$,a,t.start);if(null!=t.argStart&&null!=t.argEnd){const r=t.hasSequenceExpressionArgument?`(${b} = (`:`(${b} = `,i=t.hasSequenceExpressionArgument?")":"";e.appendLeft(t.argStart,r),e.appendLeft(t.argEnd,`${i}, ${o} ? $dd_return(${o}, ${b}, ${w}${n}) : ${b})`)}else e.appendLeft(t.start,`if (${o}) $dd_return(${o}, undefined, ${w}${n}); `)}if(null!=y){const n=y-1;e.update(n,y,`${t[n]}\n${r}`)}else e.update(c,c+1,`${t[c]}${r}`);const i=Er(k,$,a,d),s=`\n${n.needsTrailingReturn?`if (${o}) $dd_return(${o}, undefined, ${w}${i});\n`:""}} ${I}\n`;e.update(d-1,d,`${s}${t[d-1]}`)}}function br(e,t,n){e.update(n.bodyStart,n.bodyStart+1,`${t[n.bodyStart]}let $dd_t;`);for(const t of n.superCalls)e.appendLeft(t.start,"($dd_t = "),e.appendLeft(t.end,")")}function wr(e,t,n){kr(e,n)&&t.push({start:e.start,end:e.end});const o=Object.values(e);for(const e of o)if(Array.isArray(e))for(const o of e)vr(o,t,n);else vr(e,t,n)}function vr(e,t,n){n.isNode(e)&&(n.isFunction(e)&&!n.isArrowFunctionExpression(e)||wr(e,t,n))}function $r(e){return`${e.start}:${e.end}`}function kr(e,t){return t.isCallExpression(e)&&t.isSuper(e.callee)}function xr(e,t){const n=e.parentPath?.parentPath;if(!n)return!1;const o=n.node;return(t.isClassDeclaration(o)||t.isClassExpression(o))&&null!=o.superClass}function Er(e,t,n,o){const r=function(e,t){const n=e.filter((({declarationEnd:e,temporalDeadZones:n})=>e<=t&&!function(e,t){return e.some((({start:e,end:n})=>e<=t&&t<n))}(n,t))).map((({name:e})=>e));if(0===n.length)return;return`{${n.join(", ")}}`}(n,o);return t&&r?`, ${e}, ${r}`:t?`, ${e}`:r?`, undefined, ${r}`:""}function Sr(e,t,n){for(const o of e)if(n.isReturnStatement(o))t.push({start:o.start,end:o.end,argStart:o.argument?.start??void 0,argEnd:o.argument?.end??void 0,hasSequenceExpressionArgument:n.isSequenceExpression(o.argument)});else if(!n.isFunctionDeclaration(o)&&!n.isClassDeclaration(o))if(n.isBlockStatement(o))Sr(o.body,t,n);else if(n.isIfStatement(o))Sr([o.consequent],t,n),o.alternate&&Sr([o.alternate],t,n);else if(n.isForStatement(o)||n.isForInStatement(o)||n.isForOfStatement(o)||n.isWhileStatement(o)||n.isDoWhileStatement(o))Sr([o.body],t,n);else if(n.isSwitchStatement(o))for(const e of o.cases)Sr(e.consequent,t,n);else n.isTryStatement(o)?(Sr(o.block.body,t,n),o.handler&&Sr(o.handler.body.body,t,n),o.finalizer&&Sr(o.finalizer.body,t,n)):(n.isLabeledStatement(o)||n.isWithStatement(o))&&Sr([o.body],t,n)}function Ir(e,t){if(0===e.length)return!1;const n=e[e.length-1];if(t.isReturnStatement(n))return!0;if(t.isIfStatement(n)&&n.alternate){const e=t.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent],o=t.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];return Ir(e,t)&&Ir(o,t)}return!1}const Dr=["functionDeclaration","functionExpression","arrowFunction","objectMethod","classMethod","classPrivateMethod"],Ar=t.bold.red,Pr=Number(process.env.DD_LD_LIMIT)||1/0,jr=(e,t)=>{const n=t.getLogger(Vo);let o=0,r=0,i=0,s=0,a=0,u=0,c=0,d=0;return{name:Vo,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(l,p){if(e.include.length>0){if(!e.include.some((e=>"string"==typeof e?p.includes(e):e.test(p))))return{code:l}}for(const t of e.exclude){if("string"==typeof t?p.includes(t):t.test(p))return{code:l}}if(d>=Pr)return{code:l};try{const f=gr({code:l,filePath:p,buildRoot:t.buildRoot,honorSkipComments:e.honorSkipComments,functionTypes:e.functionTypes,namedOnly:e.namedOnly});if(o+=f.instrumentedCount,c+=f.totalFunctions,r+=f.failedCount,i+=f.skippedByCommentCount,s+=f.skippedFileCount,a+=f.skippedUnsupportedCount,f.totalFunctions>0&&d++,0===f.instrumentedCount)return{code:l};u++;const m=function(e){const t=e.getNativeBuildContext?.();return t?.inputSourceMap}(this),h=f.map&&m?function(e,t,n,o){try{return k(e,((e,n)=>1===n.depth?t:null))}catch(t){return o.error(`Failed to compose source map for ${n}: ${t}`,{forward:!0}),e}}(f.map,m,p,n):f.map;return{code:f.code,map:h}}catch(e){return n.error(`Instrumentation Error in ${p}: ${e}`,{forward:!0}),{code:l}}}},buildEnd:()=>{c>0&&n.info(`Live Debugger: ${o}/${c} functions instrumented across ${u}/${d} files`,{forward:!0,context:{failedCount:r,skippedByCommentCount:i,skippedFileCount:s,skippedUnsupportedCount:a,totalFilesWithFunctions:d,instrumentedCount:o,totalFunctions:c,transformedFileCount:u}})}}},Mr=({options:e,context:t})=>{const n=((e,t)=>{const n=e[qo]||{},o=e.metadata?.version,r=[];if(void 0!==n.include)if(Array.isArray(n.include)){for(const e of n.include)if("string"!=typeof e&&!(e instanceof RegExp)){r.push(`${Ar("include")} patterns must be strings or RegExp`);break}}else r.push(`${Ar("include")} must be an array of strings or RegExp`);if(void 0!==n.exclude)if(Array.isArray(n.exclude)){for(const e of n.exclude)if("string"!=typeof e&&!(e instanceof RegExp)){r.push(`${Ar("exclude")} patterns must be strings or RegExp`);break}}else r.push(`${Ar("exclude")} must be an array of strings or RegExp`);if(void 0!==n.honorSkipComments&&"boolean"!=typeof n.honorSkipComments&&r.push(`${Ar("honorSkipComments")} must be a boolean`),void 0!==n.functionTypes)if(Array.isArray(n.functionTypes)){for(const e of n.functionTypes)if(!Dr.includes(e)){r.push(`${Ar("functionTypes")} contains invalid value "${e}". Valid values: ${Dr.join(", ")}`);break}}else r.push(`${Ar("functionTypes")} must be an array of FunctionKind values`);if(void 0!==n.namedOnly&&"boolean"!=typeof n.namedOnly&&r.push(`${Ar("namedOnly")} must be a boolean`),r.length)throw t.error(`\n - ${r.join("\n - ")}`),new Error(`Invalid configuration for ${Vo}.`);return{version:o,include:n.include||[/\.[jt]sx?$/],exclude:n.exclude||[/\/node_modules\//,/\.min\.js$/,/\/pyodide-lib\//,/^vite\//,/\0/,/commonjsHelpers\.js$/,/__vite-browser-external/,/@datadog\/browser-/,/browser-sdk\/packages\//],honorSkipComments:n.honorSkipComments??!0,functionTypes:n.functionTypes,namedOnly:n.namedOnly??!1}})(e,t.getLogger(Vo));return t.inject({type:"code",position:Te.BEFORE,injectIntoAllChunks:!0,value:Wo(n.version)}),[jr(n,t)]};const Tr=[e=>/modules\.tree\.(count|size)$/.test(e.metric)?null:e,e=>e.tags.some((e=>/^assetName:.*\.map$/.test(e)||/^moduleName:\/node_modules/.test(e)))?null:e,e=>{const t={size:1e5,count:10,duration:1e3};/^sourcemaps\.upload\.(failure|retry)$/.test(e.metric)&&(t.count=0),/(entries|loaders|warnings|errors)\.count$/.test(e.metric)&&(t.count=0),/(modules\.(dependencies|dependents)$)/.test(e.metric)&&(t.count=30),/modules\.tree\.count$/.test(e.metric)&&(t.count=150),/modules\.tree\.size$/.test(e.metric)&&(t.size=15e5),/entries\.size$/.test(e.metric)&&(t.size=0),/entries\.modules\.count$/.test(e.metric)&&(t.count=0);return(e.points.length?e.points.reduce(((e,t)=>e+t[1]),0)/e.points.length:0)>t[e.type]?e:null}],Cr="metrics",Or="datadog-metrics-plugin",Nr=e=>Math.floor((e||Date.now())/1e3),Rr=(e,t)=>{const n=[`bundler:${ie(e.bundler.name)}`,`plugin_version:${ie(e.version)}`,`site:${ie(e.auth.site)}`];return e.build.metadata.name&&n.push(`build_name:${ie(e.build.metadata.name)}`),e.build.metadata.version&&n.push(`build_version:${ie(e.build.metadata.version)}`),[...n,...t]},_r=(e,t,n)=>({...e,tags:[...e.tags,...t],metric:n?`${n}.${e.metric}`:e.metric}),Fr=(e,t,n,o,r)=>{const i=new Set;for(const t of e){let e={...t,toSend:!0};if(n?.length)for(const t of n){const n=t({metric:e.metric,type:e.type,points:e.points,tags:e.tags});n?e={...n,toSend:e.toSend}:e.toSend=!1}i.add(_r(e,o,r))}const s=Array.from(i).filter((e=>e.toSend)).length;return i.add(_r({metric:"metrics.count",type:"count",points:[[t,s+1]],tags:[],toSend:!0},o,r)),i},zr=(e="")=>e.endsWith("/")?e:`${e}/`,Lr=(e,t)=>{let n=e;return e.split(zr(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},Ur=(e,t)=>e.split("!").pop().replace(zr(t),"./"),Br=(e,t,n)=>{let o=e.name||e.userRequest;return o||(o=((e,t)=>{let n=e.userRequest;if(!n){let o;o=t.moduleGraph&&"function"==typeof t.moduleGraph.getIssuer?t.moduleGraph.getIssuer(e):e.issuer,n=o?.userRequest,n||(n=e._identifier?.split("!").pop())}return n||"unknown"})(e,t)),Ur(o||"no-name",n)},qr=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),Vr=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),Kr=t.bold.red,Hr=t.bold.cyan,Wr=e=>(t,n)=>{let o,r;return"function"==typeof e?(o=e(t),r=e(n)):(o=t[e],r=n[e]),o>r?-1:o<r?1:0},Jr=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(Wr("duration"));const o={name:`${e} duration`,values:n.map((e=>({name:e.name,value:ne(e.duration)}))),top:!0};n.sort(Wr("increment"));return[o,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},Gr=(e,t,n)=>{const o=[];var r;n&&(o.push(...Jr("Loader",n.loaders)),o.push(...Jr("Tapable",n.tapables)),o.push(...Jr("Module",n.modules))),o.push(...(e=>{const t={name:"Module total dependents",values:[],top:!0},n={name:"Module total dependencies",values:[],top:!0},o={name:"Module size",values:[],top:!0},r={name:"Module aggregated size",values:[],top:!0},i=new Set,s=ee(e.build),a=new Map,u=new Map,c=new Map;for(const e of s.inputs||[]){if("map"===e.type)continue;const t=new Set(e.dependencies),n=new Set(e.dependents);for(const n of t)c.has(n)||c.set(n,new Set),c.get(n).add(e.filepath);for(const t of n)u.has(t)||u.set(t,new Set),u.get(t).add(e.filepath);if(u.has(e.filepath)){const n=u.get(e.filepath);for(const e of n)t.add(e)}if(c.has(e.filepath)){const t=c.get(e.filepath);for(const e of t)n.add(e)}u.set(e.filepath,t),c.set(e.filepath,n),a.set(e.filepath,{name:e.name,size:e.size,dependencies:t,dependents:n})}for(const[e,t]of a){const n=u.get(e)||new Set,o=c.get(e)||new Set;let r=t.size;for(const e of n)r+=a.get(e)?.size||0;i.add({name:t.name,size:t.size,aggregatedSize:r,dependents:o,dependencies:n})}if(!i.size)return[t,n,o];const d=Array.from(i);return d.sort(Wr((e=>e.dependents.size))),t.values=d.map((e=>({name:e.name,value:e.dependents.size.toString()}))),d.sort(Wr((e=>e.dependencies.size))),n.values=d.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),d.sort(Wr("size")),o.values=d.map((e=>({name:e.name,value:v(e.size)}))),d.sort(Wr("aggregatedSize")),r.values=d.map((e=>({name:e.name,value:v(e.aggregatedSize||e.size)}))),[t,n,o,r]})(e)),o.push(...(r=e,[{name:"Asset size",values:(r.build.outputs||[]).filter((e=>"map"!==e.type)).sort(Wr((e=>e.size))).map((e=>({name:e.name,value:v(e.size)}))),top:!0},{name:"Entry aggregated size",values:(r.build.entries||[]).sort(Wr((e=>e.size))).map((e=>({name:e.name,value:v(e.size)}))),top:!0},{name:"Entry number of modules",values:(r.build.entries||[]).sort(Wr((e=>e.size))).map((e=>({name:e.name,value:e.inputs.length.toString()})))||[],top:!0}])),o.push(...(e=>{const t={name:"General Numbers",values:[],top:!1},n=e.build.inputs?e.build.inputs.length:0,o=e.build.outputs?e.build.outputs.length:0,r=e.build.warnings.length,i=e.build.errors.length,s=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:ne(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:ne(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:ne(e.build.writeDuration)}),t.values.push({name:"Number of modules",value:n.toString()},{name:"Number of assets",value:o.toString()},{name:"Number of entries",value:s.toString()},{name:"Number of warnings",value:r.toString()},{name:"Number of errors",value:i.toString()}),[t]})(e));const i=(e=>{let t="";for(const t of e){t.top&&t.values.length>=5&&(t.values=t.values.slice(0,5),t.name=`Top 5 ${t.name}`);for(const e of t.values)e.name=oe(e.name,60)}const n=Math.max(...e.map((e=>e.name.length))),o=Math.max(...e.flatMap((e=>e.values.map((e=>e.name.length))))),r=Math.max(...e.flatMap((e=>e.values.map((e=>e.value.length))))),i=Math.max(n+4,o+r+4);for(const n of e){if(0===n.values.length)continue;const e=i-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=r-e.value.length;t+=` [${Kr(e.value)}] ${" ".repeat(n)}${Hr(e.name)}\n`}}return t})(o);t.info(i)},Yr="api/v1/series",Qr=t.bold.green,Zr=(e,t,n)=>{if(!t.apiKey)return void n.info("Won't send metrics to Datadog: missing API Key.");if(!e.size)return void n.debug("No metrics to send.");const o=Array.from(e).filter((e=>e.toSend)).map((e=>({...e,toSend:void 0}))),r=new Map;for(const e of o)r.has(e.metric)||r.set(e.metric,0),r.set(e.metric,r.get(e.metric)+1);const i=Array.from(r.entries()).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${o.length} metrics with configuration:\n - intake: ${Qr(`https://api.${t.site}/${Yr}`)}\n\nMetrics:\n - ${i.join("\n - ")}`),Y({method:"POST",url:`https://api.${t.site}/${Yr}?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:o})})}).catch((e=>{n.error(`Error sending metrics ${e}`)}))},Xr=["onStart","onLoad","onResolve","onEnd"],ei=new Map,ti=new Map,ni=new Map,oi=(e,t,n)=>{const o=Object.assign({},e);for(const r of Xr)o[r]=async(o,i)=>{const s=ti.get(t)||{name:t,increment:0,duration:0,events:{}};s.events[r]=s.events[r]||{name:r,values:[]};const a="onLoad"===r;return(0,e[r])(o,(async(...e)=>{const o=Ur(e[0].path,n),u=ni.get(o)||{name:o,increment:0,duration:0,events:{}};u.events[r]=u.events[r]||{name:r,values:[]};const c=x.now();try{return await i(...e)}finally{const n=x.now(),i=n-c,d={start:c,end:n,duration:i,context:Vr(e)};if(s.events[r].values.push(d),s.duration+=i,s.increment+=1,ti.set(t,s),u.events[r].values.push(d),u.duration+=i,u.increment+=1,ni.set(o,u),a){const e=ei.get(t)||{name:t,increment:0,duration:0,events:{}};e.events[r]=e.events[r]||{name:r,values:[]},e.events[r].values.push(d),e.duration+=i,e.increment+=1,ei.set(t,e)}}}))};return o},ri=(e,t)=>({setup:n=>{n.initialOptions.metafile=!0;const o=t.time("wrapping plugins");((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const o of n){const n=o.setup;o.setup=async r=>{const i=oi(r,o.name,t);await n({...i,initialOptions:{...i.initialOptions,plugins:e}})}}}})(n,e.buildRoot),o.end(),n.onEnd((async n=>{if(!n.metafile)return void t.warn("Missing metafile, can't proceed with modules data.");const o=t.time("getting plugins results"),{plugins:r,loaders:i,modules:s}={plugins:ti,modules:ni,loaders:ei};o.end(),await e.asyncHook("timings",{tapables:r,loaders:i,modules:s})}))}});class ii{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=Br(e,t,this.cwd),o=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(qr))(e);o.length||o.push("no-loader"),this.started[n]={module:Lr(n),timings:{start:x.now(),duration:0,end:0},loaders:o}}doneModule(e,t){const n=Br(e,t,this.cwd),o=this.started[n];o&&(o.timings.end=x.now(),o.timings.duration=o.timings.end-o.timings.start,this.finished.push(o),delete this.started[n])}getResults(){const e=new Map,t=new Map;for(const n of this.finished){const o=n.timings.end-n.timings.start,r=t.get(n.module)||{name:n.module,increment:0,duration:0,events:{}},i=n.loaders.join(",");r.events[i]=r.events[i]||{name:i,values:[]},r.events[i].values.push(n.timings),r.increment+=1,r.duration+=o,t.set(n.module,r);for(const t of n.loaders){const n=e.get(t)||{name:t,increment:0,duration:0,events:{}};n.increment+=1,n.duration+=o,e.set(t,n)}}return{loaders:e,modules:t}}}class si{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,o,r,i){const s=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};s.events[n]||(s.events[n]={name:n,values:[]}),s.events[n].values.push({start:r,end:i,duration:i-r,context:o,type:e}),s.duration+=i-r,s.increment+=1,this.timings.set(t,s)}getResults(){const e=this.timings;for(const[t,n]of this.timings){const o=n;o.duration=Object.values(n.events).map((e=>e.values.reduce(((e,t)=>e+t.end-t.start),0))).reduce(((e,t)=>e+t),0),e.set(t,o)}return{monitoredTaps:this.monitoredTaps,tapables:this.tapables,hooks:this.hooks,timings:e}}getPromiseTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=t.apply(this,r),a=()=>{this.saveResult(e,n,o,Vr(r),i,x.now())};return s.then(a,a),s}}getAsyncTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=r.pop();return t.apply(this,[...r,(...t)=>(this.saveResult(e,n,o,Vr(r),i,x.now()),s(...t))])}}getDefaultTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=t.apply(this,r);return this.saveResult(e,n,o,Vr(r),i,x.now()),s}}getTapPatch(e,t,n,o){switch(e){case"promise":return this.getPromiseTapPatch(e,t,n,o);case"async":return this.getAsyncTapPatch(e,t,n,o);default:return this.getDefaultTapPatch(e,t,n,o)}}newTap(e,t,n,o){return(r,i)=>{const s="string"==typeof(a=r)?a:a.name;var a;const u=`${t}-${s}`;if(this.monitoredTaps[u])return n.call(o,r,i);this.monitoredTaps[u]=!0;const c=this.getTapPatch(e,i,s,t);return n.call(o,r,c)}}replaceTaps(e,t){t.tap=this.newTap("default",e,t.tap,t),t.tapAsync=this.newTap("async",e,t.tapAsync,t),t.tapPromise=this.newTap("promise",e,t.tapPromise,t)}patchHook(e,t,n){n._fakeHook||e.includes(Or)||(this.hooks[e]||(this.hooks[e]=[]),this.hooks[e].includes(t)||(this.hooks[e].push(t),this.replaceTaps(t,n)))}patchHooks(e){const t=e.constructor.name,n=Object.keys(e.hooks).filter((e=>!this.ignoredHooks.includes(e)&&!this.hooks[t]?.includes(e)));for(const o of n)this.patchHook(t,o,e.hooks[o])}checkNewHooks(){for(const e of this.tapables)this.patchHooks(e)}throughHooks(e){this.tapables.includes(e)||this.tapables.push(e),this.patchHooks(e)}}const ai=e=>async t=>{const n=e.getLogger(Or),o={name:Or},r=new si(e.buildRoot),i=new ii(e.buildRoot),s=n.time("parse compiler hooks");r.throughHooks(t),s.end(),t.hooks.thisCompilation.tap(o,(e=>{const t=n.time("parse compilation hooks");r.throughHooks(e),t.end(),e.hooks.buildModule.tap(o,(t=>{i.startModule(t,e)})),e.hooks.succeedModule.tap(o,(t=>{i.doneModule(t,e)})),e.hooks.failedModule&&e.hooks.failedModule.tap(o,(t=>{i.doneModule(t,e)}))})),t.hooks.afterEmit.tapPromise(o,(async()=>{const{timings:t}=r.getResults(),{loaders:n,modules:o}=i.getResults();await e.asyncHook("timings",{tapables:t,loaders:n,modules:o})}))},ui={filters:Tr},ci=({options:e,context:t,stores:n})=>{const o=t.getLogger(Or);let r=0;((e,t)=>{e.addMetric=e=>{t.metrics.add(e)}})(t,n);const i=((e,t)=>{const n=e[Cr],o=Nr(n?.timestamp);let r=!1===n?.enableDefaultPrefix?"":`build.${t}`;return n?.prefix&&(r+=r?`.${n.prefix}`:n.prefix),{enableDefaultPrefix:!0,enableTracing:!1,filters:Tr,tags:[],...e[Cr],timestamp:o,prefix:r.toLowerCase().replace(/(^\.*|\.*$)/g,"")}})(e,t.bundler.name),s=[],a={name:Or,enforce:"pre",esbuild:ri(t,o),webpack:ai(t),rspack:ai(t)},u=o.time("build",{start:!1}),c=i.enableTracing&&["esbuild","webpack","rspack"].includes(t.bundler.name);let d,l;const p=async()=>{if(!n.metrics.size)return;const e=o.time("aggregating collected metrics"),r=(()=>{const e=new Set(n.metrics);n.metrics.clear();const o=Rr(t,i.tags);return Fr(e,i.timestamp,i.filters,o,i.prefix)})();await t.asyncHook("metrics",r),e.end();const s=o.time("sending collected metrics to Datadog");await Zr(r,{apiKey:t.auth.apiKey,site:t.auth.site},o),s.end()},f=async()=>{t.build.end=Date.now(),t.build.duration=t.build.end-t.build.start,t.build.writeDuration=t.build.end-r;const e=o.time("aggregating metrics"),n=i.timestamp,s=o.time("aggregate universal metrics"),a=((e,t)=>{const n=new Set,o=e.inputs||[],r=e.outputs||[],i=e.entries||[],s=e.warnings.length,a=e.errors.length,u=e.duration,c=new Map,d=new Map,l=new Map;for(const e of i){for(const t of e.inputs)c.has(t.filepath)||c.set(t.filepath,[]),c.get(t.filepath).push(e.name);for(const t of e.outputs){const n=t.filepath.replace(/\.map$/,"");l.has(n)||l.set(n,[]),l.get(n).push(e.name)}}for(const e of r)for(const t of e.inputs)d.has(t.filepath)||d.set(t.filepath,[]),d.get(t.filepath).push(e.name);n.add({metric:"assets.count",type:"count",points:[[t,r.length]],tags:[]}).add({metric:"entries.count",type:"count",points:[[t,i.length]],tags:[]}).add({metric:"errors.count",type:"count",points:[[t,a]],tags:[]}).add({metric:"modules.count",type:"count",points:[[t,o.length]],tags:[]}).add({metric:"warnings.count",type:"count",points:[[t,s]],tags:[]}),u&&n.add({metric:"compilation.duration",type:"duration",points:[[t,u]],tags:[]});for(const e of o){const o=[`moduleName:${e.name}`,`moduleType:${e.type}`];c.has(e.filepath)&&o.push(...c.get(e.filepath).map((e=>`entryName:${e}`))),d.has(e.filepath)&&o.push(...d.get(e.filepath).map((e=>`assetName:${e}`))),n.add({metric:"modules.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"modules.dependencies",type:"count",points:[[t,e.dependencies.size]],tags:o}).add({metric:"modules.dependents",type:"count",points:[[t,e.dependents.size]],tags:o})}for(const e of r){const o=[`assetName:${e.name}`,`assetType:${e.type}`],r=e.filepath.replace(/\.map$/,"");l.has(r)&&o.push(...l.get(r).map((e=>`entryName:${e}`))),n.add({metric:"assets.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"assets.modules.count",type:"count",points:[[t,e.inputs.length]],tags:o})}for(const e of i){const o=[`entryName:${e.name}`];n.add({metric:"entries.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"entries.modules.count",type:"count",points:[[t,e.inputs.length]],tags:o}).add({metric:"entries.assets.count",type:"count",points:[[t,e.outputs.length]],tags:o})}return n})(l,n);s.end();const u=o.time("aggregate plugins metrics"),c=((e,t)=>{const n=new Set;if(!e)return n;n.add({metric:"plugins.count",type:"count",points:[[t,e.size]],tags:[]});for(const o of e.values()){let e=0,r=0;for(const i of Object.values(o.events)){let s=0;r+=i.values.length;for(const t of i.values){const n=t.end-t.start;s+=n,e+=n}n.add({metric:"plugins.hooks.duration",type:"duration",points:[[t,s]],tags:[`pluginName:${o.name}`,`hookName:${i.name}`]}).add({metric:"plugins.hooks.increment",type:"count",points:[[t,i.values.length]],tags:[`pluginName:${o.name}`,`hookName:${i.name}`]})}n.add({metric:"plugins.duration",type:"duration",points:[[t,e]],tags:[`pluginName:${o.name}`]}).add({metric:"plugins.increment",type:"count",points:[[t,r]],tags:[`pluginName:${o.name}`]})}return n})(d?.tapables,n);u.end();const p=o.time("aggregate loaders metrics"),f=((e,t)=>{const n=new Set;if(!e)return n;n.add({metric:"loaders.count",type:"count",points:[[t,e.size]],tags:[]});for(const o of e.values())n.add({metric:"loaders.duration",type:"duration",points:[[t,o.duration]],tags:[`loaderName:${o.name}`]}).add({metric:"loaders.increment",type:"count",points:[[t,o.increment]],tags:[`loaderName:${o.name}`]});return n})(d?.loaders,n);p.end();const m=new Set([...a,...c,...f]),h=Rr(t,i.tags),g=Fr(m,n,i.filters,h,i.prefix);await t.asyncHook("metrics",g),e.end();const y=o.time("outputing report");Gr(t,o,d),y.end();const b=o.time("sending metrics to Datadog");await Zr(g,{apiKey:t.auth.apiKey,site:t.auth.site},o),b.end()},m={name:"datadog-universal-metrics-plugin",enforce:"post",buildStart(){u.resume(),t.build.start=t.build.start||Date.now(),e[Cr]?.timestamp||(i.timestamp=Nr(t.build.start))},buildEnd(){u.end(),r=Date.now()},async timings(e){d=e,l&&await f()},async buildReport(e){l=e,!d&&c||await f()},async flush(){await p()}};return i.enableTracing&&s.push(a),s.push(m),s},di="output",li="datadog-output-plugin",pi=(e,t)=>"string"==typeof t?t.replace(/(\.json)?$/,".json"):!0===t?`${e}.json`:t,fi=e=>{const t=void 0===e;return{build:pi("build",e?.build??t),bundler:pi("bundler",e?.bundler??t),dependencies:pi("dependencies",e?.dependencies??t),errors:pi("errors",e?.errors??t),logs:pi("logs",e?.logs??t),metrics:pi("metrics",e?.metrics??t),timings:pi("timings",e?.timings??t),warnings:pi("warnings",e?.warnings??t)}},mi=(e,t)=>n=>{n.hooks.done.tap("bundler-outputs",(n=>{t((()=>{const t=e.time("stats serialization"),o=n.toJson({all:!1,assets:!0,children:!0,chunks:!0,chunkGroupAuxiliary:!0,chunkGroupChildren:!0,chunkGroups:!0,chunkRelations:!0,entrypoints:!0,errors:!0,ids:!0,modules:!0,nestedModules:!0,relatedAssets:!0,warnings:!0,reasons:!1,chunkModules:!1});return t.end(),o}))}))},hi=e=>{const t=new Set;return{buildStart(){t.clear()},writeBundle(e,n){t.add(n)},closeBundle(){e((()=>Array.from(t)))}}},gi=({options:e,context:t})=>{const n=t.getLogger(li),o=(e=>({path:"./",...e[di],files:fi(e[di]?.files)}))(e),r=(e,r)=>{const i=o.files[e];if(!r||!1===i)return;t.queue((async()=>{const e=n.time(`output ${i}`),c=((e,t,n)=>{const o=u.isAbsolute(t)?t:u.resolve(e,t);return u.resolve(o,n)})(t.bundler.outDir,o.path,i);let d;try{const e="function"==typeof r?await r():r;await(async(e,t)=>{await Ie(u.dirname(e));const n=s.createWriteStream(e),o=new a(t,void 0,2),r=new Promise(((e,t)=>{o.on("end",(()=>{e()})),o.on("error",(e=>{t(e)}))}));return o.pipe(n),r})(c,e)}catch(e){d=e}d?n.error(`Failed writing ${i}: ${d}`):n.debug(`Wrote "./${u.relative(t.buildRoot,c)}"`),e.end()})())};return[{name:li,buildReport(e){const t=n.time("serialize report"),o=ee(e);t.end(),r("build",{bundler:o.bundler,metadata:o.metadata,start:o.start,end:o.end,duration:o.duration,writeDuration:o.writeDuration,entries:o.entries,outputs:o.outputs}),r("logs",o.logs),r("timings",o.timings),r("dependencies",o.inputs),r("errors",o.errors),r("warnings",o.warnings)},metrics(e){r("metrics",(()=>Array.from(e)))},esbuild:{setup(e){e.onEnd((e=>{r("bundler",e.metafile)}))}},rspack:mi(n,(e=>{r("bundler",e)})),rollup:hi((e=>{r("bundler",e)})),vite:hi((e=>{r("bundler",e)})),webpack:mi(n,(e=>{r("bundler",e)}))}]},yi="rum",bi="datadog-rum-plugin",wi=["8","9","a","b"],vi=(e,t)=>{const n={service:e.service,version:e.version};return e.debugId&&(n.ddDebugId=t?(e=>{const t=p("sha256").update(e).digest("hex").slice(0,32),n=`${t.slice(0,12)}4${t.slice(13)}`,o=n.charCodeAt(16)%4,r=`${n.slice(0,16)}${wi[o]}${n.slice(17)}`;return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")})(t):f()),`(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(n)},${JSON.stringify("DD_SOURCE_CODE_CONTEXT")});`},$i="datadog-rum-privacy-plugin";const ki=(e,t)=>{const n=t.getLogger($i),o=function(e,t){const n={privacy:{addToDictionaryHelper:{expression:{code:e}}}};return["esbuild","webpack","rspack"].includes(t)&&(n.output={...n.output,inlineSourceMap:!1,embedCodeInSourceMap:!0}),n}(e.helperCodeExpression,t.bundler.name);let r=0,i=0;return{name:$i,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(e,t){try{const n=function(e){if("rspack"===e?.framework||"webpack"===e?.framework)switch(typeof e.inputSourceMap){case"undefined":return;case"string":return e.inputSourceMap;default:return JSON.stringify(e.inputSourceMap)}}(this.getNativeBuildContext?.()),s=E({id:t,code:e,map:n},o);return 0===s.privacyDictionarySize?{code:e}:(r+=s.privacyDictionarySize,i++,s)}catch(t){return n.error(`Instrumentation Error: ${t}`,{forward:!0}),{code:e}}}},buildEnd:()=>{n.debug(`Privacy dictionary will include ${r} entries across ${i} files`,{forward:!0,context:{dictionaryEntryCount:r,fileCount:i}})}}},xi=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,Ei=(e,t)=>{const n=e.sdk;if(n.clientToken)return xi(e);if(!t.auth.apiKey||!t.auth.appKey)throw new Error('Missing "auth.apiKey" and/or "auth.appKey" to fetch "rum.sdk.clientToken".');return async()=>{let o;try{const e=await Y({url:`https://api.${t.auth.site}/api/v2/rum/applications/${n.applicationId}`,type:"json",auth:t.auth});o=e.data?.attributes?.client_token}catch(e){throw new Error(`Could not fetch the clientToken: ${e.message}`)}if(!o)throw new Error("Missing clientToken in the API response.");return xi({...e,sdk:{clientToken:o,...n}})}},Si=e=>{const n=t.bold.red,o=e[yi]||{},r={errors:[]};if(!o.sdk)return r;o.sdk.applicationId||r.errors.push(`Missing ${n("applicationId")} in the SDK configuration.`),e.auth.apiKey&&e.auth.appKey||o.sdk.clientToken||r.errors.push(`Missing ${n('"auth.apiKey"')} and/or ${n('"auth.appKey"')} to fetch missing client token.`);const i={applicationId:"unknown_application_id",allowUntrustedEvents:!1,compressIntakeRequests:!1,defaultPrivacyLevel:"mask",enablePrivacyForActionName:!1,sessionReplaySampleRate:0,sessionSampleRate:100,silentMultipleInit:!1,site:e.auth.site||"datadoghq.com",startSessionReplayRecordingManually:!1,storeContextsAcrossPages:!1,telemetrySampleRate:20,traceSampleRate:100,trackingConsent:"granted",trackLongTasks:!1,trackResources:!1,trackUserInteractions:!1,trackViewsManually:!1};return r.config={...i,...o.sdk},r},Ii=e=>{const t=e[yi]||{},n={errors:[]};if(t.privacy){const e={exclude:[/\/node_modules\//,/\.preval\./,/^[!@#$%^&*()=+~`-]/],include:[/\.(?:c|m)?(?:j|t)sx?$/],addToDictionaryFunctionName:"$",helperCodeExpression:"/*__PURE__*/((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()"};n.config={...e,...t.privacy}}return n},Di=e=>{const n=t.bold.red,o=e[yi]||{},r={errors:[]};if(!o.sourceCodeContext)return r;const i=o.sourceCodeContext;return i?.debugId||i?.service&&"string"==typeof i.service||r.errors.push(`Missing ${n('"rum.sourceCodeContext.service"')}.`),r.config={...i,version:i.version||e.metadata?.version},r},Ai=({options:e,context:t})=>{const n=((e,t)=>{const n=[],o=Si(e),r=Ii(e),i=Di(e);if(n.push(...o.errors),n.push(...r.errors),n.push(...i.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${bi}.`);const s={...e[yi],sdk:void 0,privacy:void 0,sourceCodeContext:void 0};return o.config&&(s.sdk=o.config),r.config&&(s.privacy=r.config,t.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(s.privacy,((e,t)=>t instanceof RegExp?t.toString():t))}`,{forward:!0})),i.config&&(s.sourceCodeContext=i.config),s})(e,t.getLogger(bi)),o=[],r=n.sourceCodeContext;if(r&&t.inject({type:"code",position:Te.BEFORE,injectIntoAllChunks:!0,value:e=>vi(r,e)}),n.sdk&&(t.inject({type:"file",position:Te.MIDDLE,value:u.join(T,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Te.MIDDLE,value:Ei(n,t)})),n.privacy){t.inject({type:"file",position:Te.BEFORE,value:u.join(T,"./privacy-helpers.js")});const e=ki(n.privacy,t);o.push(e)}return o},Pi="datadog-analytics-plugin",ji=({context:e})=>{const t=e.getLogger(Pi);return[{name:Pi,async buildStart(){"production"===e.env&&e.queue((async()=>{try{await e.sendLog({message:"Build started",context:{plugins:e.pluginNames}})}catch(e){t.debug(`Could not submit data to Datadog: ${e}`)}})())}}]},Mi="datadog-async-queue-plugin",Ti=e=>{const{context:t,stores:n}=e,o=t.getLogger(Mi),r=[];return t.queue=e=>{const t=e.catch((e=>{r.push(e.message||e.toString())}));n.queue.push(t)},[{name:Mi,asyncTrueEnd:async()=>{await Promise.all(n.queue),r.length>0&&o.error(`Error occurred while processing async queue:\n ${r.join("\n ")}`)}}]},Ci=async(e,t,n)=>{const o=[],r=e.initialOptions.entryPoints,i=[],s=[];if(Array.isArray(r))for(const e of r){const t=e&&"object"==typeof e?e.in:e;i.push({path:t})}else r&&"object"==typeof r&&i.push(...Object.entries(r).map((([e,t])=>({name:e,path:t}))));const a=i.flatMap((e=>{return(t=e.path,t.includes("*")?w.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,r])=>{const i=await e.resolve(r,{kind:"entry-point",resolveDir:t.buildRoot});i.errors.length&&s.push(...i.errors.map((e=>e.text))),i.path&&o.push({name:n.name,resolved:i.path,original:n.path})}));for(const e of s)n.error(e);return await Promise.all(a),o},Oi=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,Ni=/(\?|%3F|\|)+/gi,Ri=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=zi(e),Oi.lastIndex=0,Oi.exec(t)?.[1]||"unknown");var t},_i=["unknown","commonjsHelpers.js",`vite${u.sep}preload-helper.js`],Fi=(e,t,n)=>{const o=new Set;for(const n of e){const e=zi(n);X(n)||e===t||_i.includes(e)||o.add(e)}return o},zi=e=>e.split("!").pop().split(Ni).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/\\]+/,""),Li=(e,t)=>X(t)?O:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):((e,t)=>{const n=t.split(u.sep),o=e.split(u.sep).filter(((e,t)=>e===n[t])).join(u.sep);return e.replace(o,"")})(t.split("!").pop(),e).split("node_modules").pop().split(Ni).shift().replace(/^((\.\.?)?[/\\])+/g,""),Ui=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Xn(t,e),n]))),Bi=(e,t)=>({setup(n){const o=new Map;let r=[];const i=t.time("build report",{start:!1});n.onStart((async()=>{o.clear(),r=[],i.resume();const s=t.time("process entries");r.push(...await Ci(n,e,t));for(const t of r){const n=Li(e.bundler.outDir,t.resolved);t.name?o.set(n,t.name):o.set(n,n)}s.end(),i.pause()})),n.onEnd((async n=>{i.resume();const r=t.time("collecting errors and warnings"),s=e.bundler.outDir,a=e.buildRoot;for(const t of n.errors)e.build.errors.push(t.text);for(const t of n.warnings)e.build.warnings.push(t.text);if(r.end(),!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const c=[],d=[],l=[],p=[],f=[],m={},h={},g=t.time("indexing metafile data"),y=Ui(n.metafile.inputs,a),b=Ui(n.metafile.outputs,a);g.end();const w=e=>{if(!X(e))return e;const t=y[Xn(a,e)];if(!t)return e;const n=t.imports.find((e=>!X(e.path)));return n?n.path:e},v=t.time("looping through inputs");for(const[e,t]of Object.entries(n.metafile.inputs)){if(X(e))continue;const n=Xn(a,e),o={name:Li(s,e),filepath:n,dependents:new Set,dependencies:new Set,size:t.bytes,type:Ri(e)};m[n]=o,c.push(o)}v.end();const $=t.time("looping through outputs");for(const[e,r]of Object.entries(n.metafile.outputs)){const n=Xn(a,e),i=Li(s,n),u=[];for(const e of Object.keys(r.inputs)){if(X(e))continue;const n=m[Xn(a,e)];n?u.push(n):t.debug(`Input ${e} not found for output ${i}`)}if(r.entryPoint&&!u.length){const e=m[Xn(a,r.entryPoint)];if(!e){t.debug(`Input ${r.entryPoint} not found for output ${i}`);continue}u.push(e)}const c={name:i,filepath:n,inputs:u,size:r.bytes,type:Ri(n)};if(h[n]=c,"map"===c.type&&p.push(c),d.push(c),!r.entryPoint)continue;const f=m[Xn(a,w(r.entryPoint))];if(f){if(!o.get(f.name))continue;const e={...c,name:o.get(f.name)||f.name,outputs:[c],size:c.size};l.push(e)}}$.end();const k=t.time("looping through sourcemaps");for(const e of p){const n=h[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}k.end();const x={inputs:{report:m,meta:y},outputs:{report:h,meta:b}},E=/(<runtime>|https:|file:|data:|#)/g,S=e=>!X(e)&&!e.match(E),I=(e,n,o={})=>{if(!S(e))return o;const r=n.report[e];if(!r)return t.debug(`Could not find report's ${e}`),o;if(o[r.filepath])return o;o[r.filepath]=r;const i=n.meta[e];if(!i)return t.debug(`Could not find metafile's ${e}`),o;if(!i.imports||!i.imports.length)return o;for(const t of i.imports){const i=t.path.match(/^\.\.?\//),d=i?u.dirname(e):a,l=Xn(d,t.path);if(t.external){if(S(t.path)){const e=i?l:t.path,n=x.inputs.report[e]||{filepath:e,name:Li(s,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in r&&(n.dependents.add(r),r.dependencies.add(n)),"inputs"in r&&!r.inputs.includes(n)&&r.inputs.push(n),c.includes(n)||c.push(n),x.inputs.report[e]=n,o[n.filepath]=n}}else I(l,n,o)}return o},D=t.time("looping through entries");for(const e of l){const t={},n={};for(const n of e.inputs)I(n.filepath,x.inputs,t);for(const t of e.outputs)I(t.filepath,x.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),f.push(e)}D.end();const A=t.time("aggregate dependencies and dependents");for(const e of c){if("external"===e.type)continue;const n=x.inputs.meta[e.filepath];if(n)for(const o of n.imports){if(!S(o.path))continue;const n=o.path.match(/^\.?\.\//),r=n?u.dirname(e.filepath):a,i=Xn(r,o.path);let s;if(o.external){const e=n?i:o.path;s=x.inputs.report[e]}else s=x.inputs.report[i];s?(e.dependencies.add(s),s.dependents.add(e)):t.debug(`Could not find input file of ${o.path} imported from ${e.name}`)}else t.debug(`Could not find metafile's ${e.name}`)}A.end(),e.build.outputs=d,e.build.inputs=c,e.build.entries=f,i.end(),await e.asyncHook("buildReport",e.build)}))}}),qi=(e,t)=>{const n=t.time("module parsing",{start:!1}),o=t.time("build report",{start:!1}),r=t.time("filling entries",{start:!1}),i=t.time("filling inputs and outputs",{start:!1}),a=t.time("completing dependencies and dependents",{start:!1}),u=t.time("filling dependencies and dependents",{start:!1}),c=t.time("filling sourcemaps inputs",{start:!1}),d=new Map,l=new Map,p=new Map,f=new Map;return{buildStart(){f.clear(),d.clear(),l.clear(),p.clear()},onLog(t,n){"warn"===t&&e.build.warnings.push(n.message||n.toString())},renderError(t){t&&e.build.errors.push(t.message)},moduleParsed(e){n.resume();const t=zi(e.id),o=f.get(t)||{dependencies:new Set,dependents:new Set},r=Fi(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),i=Fi(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of i)o.dependents.add(e);for(const e of r)o.dependencies.add(e);f.set(t,o),n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,m){o.resume();const h=n.dir?Xn(e.buildRoot,n.dir):e.bundler.outDir,g=new Set,y=new Set,b=new Map;a.resume();for(const[e,{dependencies:t,dependents:n}]of f){for(const n of t){const t=zi(n),o=f.get(t)||{dependencies:new Set,dependents:new Set};o.dependents.has(e)||(o.dependents.add(e),f.set(t,o))}for(const t of n){const n=zi(t),o=f.get(n)||{dependencies:new Set,dependents:new Set};o.dependencies.has(e)||(o.dependencies.add(e),f.set(n,o))}}a.end(),i.resume();for(const[e,n]of Object.entries(m)){const o=Xn(h,e),r="code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),i=l.get(o)||{name:e,filepath:o,inputs:[],size:r,type:Ri(e)};if("map"===i.type&&y.add(i),"modules"in n)for(const[e,t]of Object.entries(n.modules)){if(zi(e)!==e)continue;let n=t.originalLength;if(!n&&0!==n)try{n=s.statSync(e).size}catch(e){n=t.renderedLength}const o=d.get(e)||{name:Li(h,e),dependencies:new Set,dependents:new Set,filepath:e,size:n,type:Ri(e)};i.inputs.push(o),d.set(o.filepath,o)}if("imports"in n)for(const e of n.imports){const n=zi(e);if(!f.has(n)){b.set(Xn(h,n),i);continue}if(d.has(n)){t.debug(`Input report already there for ${n} from ${i.name}.`);continue}const o=d.get(n)||{name:Li(h,e),dependencies:new Set,dependents:new Set,filepath:n,size:0,type:"external"};i.inputs.push(o),d.set(o.filepath,o)}"isEntry"in n&&n.isEntry&&g.add({...i,name:n.name,size:0,outputs:[i]}),l.set(i.filepath,i)}i.end();for(const[e,n]of b){const o=l.get(e);o?n.inputs.includes(o)||n.inputs.push(o):t.debug(`Could not find the output report for ${e}.`)}u.resume();for(const[e,n]of d){const o=f.get(e);if(o){for(const e of o.dependencies){const o=d.get(e);o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${Li(h,e)} of ${n.name}`)}for(const e of o.dependents){const o=d.get(e);o?n.dependents.add(o):t.debug(`Could not find input for dependent ${Li(h,e)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(u.end(),y.size){c.resume();for(const e of y){const n=e.filepath.replace(/\.map$/,""),o=l.get(n);o?e.inputs.push(o):t.debug(`Could not find output for sourcemap ${e.name}`)}c.end()}const w=(e,n=new Map)=>{if(n.has(e))return n;const o=Li(h,e),r=l.get(e);if(!r)return d.has(o)||t.debug(`Could not find output for ${o}`),n;n.set(e,r);const i=m[Li(h,e)];if(!i)return t.debug(`Could not find asset for ${o}`),n;const s=[];"imports"in i&&s.push(...i.imports),"dynamicImports"in i&&s.push(...i.dynamicImports);for(const e of s)w(Xn(h,e),n);return n};r.resume();for(const e of g){const n=w(e.filepath);e.outputs=Array.from(n.values()),e.inputs=Array.from(new Set(e.outputs.flatMap((e=>e.inputs)))),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),p.has(e.filepath)&&t.debug(`Entry "${e.name}":"${Li(h,e.filepath)}" already reported.`),p.set(e.filepath,e)}r.pause(),o.pause()},async closeBundle(){e.build.inputs=Array.from(d.values()),e.build.outputs=Array.from(l.values()),e.build.entries=Array.from(p.values()),r.end(),o.end(),await e.asyncHook("buildReport",e.build)}}},Vi=(e,t,n)=>o=>{let r=[],i=[],s=[];const a=new Map,u=new Map,c=new Map,d=new Map,l=[],p=new Map,f=n.time("build report",{start:!1}),m=e=>!(!e||e.startsWith("webpack/runtime")||e.startsWith("multi ")||X(e)),h=e=>e.replace(/(^external[^"]+"|"$)/g,""),g=e=>{const t=(e=>{const t=e.identifier();return{identifier:()=>t,dependencies:"dependencies"in e?[...e.dependencies]:[],blocks:"blocks"in e?[...e.blocks]:[],externalType:"externalType"in e?e.externalType:void 0,external:"external"in e?e.external:void 0}})(e),n=(e=>{const t=new Set,n=["rawRequest","resource","request","userRequest"],o=e=>{const n=zi(e);t.add(n),n.startsWith("external ")&&t.add(h(n))};o(e.identifier());for(const t of n){const n=e[t];t&&t in e&&"string"==typeof n&&o(n)}return t})(e);for(const e of n)if(d.has(e)){const n=d.get(e);n.dependencies.push(...t.dependencies||[]),n.blocks.push(...t.blocks||[])}else d.set(e,t)},y=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),y(n,t);if("blocks"in e)for(const n of e.blocks)y(n,t);return t},b=(e,t)=>{if("request"in t&&t.request){const n=zi(t.request);if(d.has(n))return d.get(n);if(e.context){const t=Xn(zi(e.context),n);if(d.has(t))return d.get(t)}}},w=e=>!(!("externalType"in e)||!e.externalType)||(!(!("external"in e)||!e.external)||!!e.identifier?.().startsWith("external "));o.hooks.thisCompilation.tap(t,(o=>{r=[],i=[],s=[],a.clear(),u.clear(),d.clear(),p.clear(),o.hooks.finishModules.tap(t,(t=>{f.resume();const o=n.time("dependency graph"),i=n.time("indexing modules");for(const e of t)g(e);i.end();const s=n.time("building inputs");for(const n of t){const t=n.identifier(),o=Li(e.bundler.outDir,t),i=new Set(y(n).map((e=>{const o=b(n,e);if(!o?.identifier())return!1;const r=o.identifier();return!!m(r)&&(r!==t&&(w(o)?h(r):r))})).filter(Boolean));if(!m(t))continue;const s=p.get(t)||{dependents:new Set,dependencies:new Set};for(const e of i){const n=p.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),s.dependencies.add(e),p.set(e,n)}p.set(t,s);const u=w(n)?{size:0,name:h(o),dependencies:new Set,dependents:new Set,filepath:t,type:"external"}:{size:n.size()||0,name:o,dependencies:new Set,dependents:new Set,filepath:t,type:Ri(t)};r.push(u),a.set(t,u),w(n)&&a.set(h(t),u)}s.end();const u=n.time("assigning dependencies and dependents");for(const e of r){const t=p.get(e.filepath);if(t){for(const o of t.dependencies){const t=a.get(o);t?e.dependencies.add(t):n.debug(`Could not find input of dependency ${o}`)}for(const o of t.dependents){const t=a.get(o);t?e.dependents.add(t):n.debug(`Could not find input of dependent ${o}`)}}else n.debug(`Could not find dependency report for ${e.name}`)}u.end(),o.end(),f.pause()}))})),o.hooks.afterEmit.tapPromise(t,(async t=>{f.resume();const o=t.chunks,d=t.getAssets(),p=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Xn(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of o){const t=p(e),n=(g?.getChunkModules(e)||[]).flatMap((e=>"modules"in e&&Array.isArray(e.modules)?e.modules.map((e=>e.identifier())):e.identifier())).filter(m);for(const e of t){if("map"===Ri(e))continue;const t=c.get(e)||new Set;for(const e of n)t.add(e);c.set(e,t)}}h.end();const y=n.time("building outputs");for(const t of d){const o={size:t.source.size()||0,name:t.name,inputs:[],filepath:Xn(e.bundler.outDir,t.name),type:Ri(t.name)};if(u.set(o.filepath,o),i.push(o),"map"===o.type){l.push(o);continue}const r=c.get(o.filepath);if(r)for(const e of r){const t=a.get(e);t?o.inputs.push(t):n.debug(`Could not find input of ${e}`)}else n.debug(`Could not find modules for ${o.name}`)}y.end();const b=n.time("filling sourcemaps inputs");for(const e of l){const t=u.get(e.filepath.replace(/\.map$/,""));t?e.inputs.push(t):n.debug(`Output not found for sourcemap ${e.name}`)}b.end();const w=n.time("building entries"),v=(e,t=new Set)=>{if(t.has(e))return new Set;t.add(e);const n=new Set(e.chunks);for(const o of e.childrenIterable||[]){const e=v(o,t);for(const t of e)n.add(t)}return n};for(const[o,r]of t.entrypoints){const t=new Map,i=new Map;let a=0;const c=v(r),d=Array.from(c).flatMap(p),l=r.chunks.filter((e=>g.getChunkEntryModulesIterable(e)||!1)).flatMap((e=>Array.from(e.files))).filter((e=>e.includes(o)||r.name&&e.includes(r.name))).find((e=>"js"===Ri(e)));for(const e of d){const o=u.get(e);if(e&&o){if("map"!==o.type&&!t.has(o.name)){t.set(o.name,o);for(const e of o.inputs)i.has(e.filepath)||i.set(e.filepath,e);a+=o.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const f={name:o,filepath:l?Xn(e.bundler.outDir,l):"unknown",size:a,inputs:Array.from(i.values()),outputs:Array.from(t.values()),type:l?Ri(l):"unknown"};s.push(f)}w.end();for(const n of t.errors)e.build.errors.push(n.message);for(const n of t.warnings)e.build.warnings.push(n.message);e.build.inputs=r,e.build.outputs=i,e.build.entries=s,f.end(),await e.asyncHook("buildReport",e.build)}))},Ki="datadog-build-report-plugin",Hi=e=>{const{context:t}=e,n=t.getLogger(Ki);return[{name:Ki,enforce:"post",esbuild:Bi(t,n),rspack:Vi(t,Ki,n),webpack:Vi(t,Ki,n),vite:qi(t,n),rollup:qi(t,n)}]},Wi="datadog-bundler-report-plugin",Ji=(e,t)=>t?u.isAbsolute(t)?t:u.resolve(e,t):"",Gi=e=>{if(!e)return[];return(Array.isArray(e)?e:[e]).map((e=>e.dir?e.dir:e.file?u.dirname(e.file):void 0)).filter(Boolean)},Yi=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=Ji(process.cwd(),t.options.output.path)),e.hook("bundlerReport",e.bundler),t.options.context&&(e.buildRoot=t.options.context),e.hook("buildRoot",e.buildRoot)},Qi=e=>({configResolved(t){e.bundler.rawConfig=t;let n=t.build?.outDir??"dist";const o=t.build?.rollupOptions?.output,r=Gi(o);e.buildRoot=t.root??process.cwd(),o&&r.length&&(n=to(r,process.cwd())),e.bundler.outDir=Ji(e.buildRoot,n),e.hook("buildRoot",e.buildRoot),e.hook("bundlerReport",e.bundler)}}),Zi=e=>{const{context:t}=e,n=t.getLogger(Wi);return[{name:Wi,enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.absWorkingDir&&(t.buildRoot=e.initialOptions.absWorkingDir),e.initialOptions.outdir&&(t.bundler.outDir=Ji(t.buildRoot,e.initialOptions.outdir)),e.initialOptions.outfile&&(t.bundler.outDir=Ji(t.buildRoot,u.dirname(e.initialOptions.outfile))),t.hook("buildRoot",t.buildRoot),t.hook("bundlerReport",t.bundler),e.initialOptions.metafile=!0}},webpack:Yi(t),rspack:Yi(t),vite:Qi(t),rollup:{options(e){let n;if("output"in e){const t=Gi(e.output);n=to(t,process.cwd())}const o=(e=>{const t=new Set;if(e.input){const n=Array.isArray(e.input)?e.input:"object"==typeof e.input?Object.values(e.input):[e.input];for(const e of n){if("string"!=typeof e)throw new Error("Invalid input type");t.add(u.dirname(e))}}return Array.from(t)})(e);if(n){t.bundler.outDir=Xn(process.cwd(),n);const e=to([n,...o],process.cwd());t.buildRoot=e===u.sep?process.cwd():e}else t.buildRoot=to(o,process.cwd()),t.bundler.outDir=u.resolve(process.cwd(),"dist");t.hook("buildRoot",t.buildRoot)},buildStart(e){t.bundler.rawConfig=e},renderStart(e){t.bundler.rawConfig.outputs=t.bundler.rawConfig.outputs||[],t.bundler.rawConfig.outputs.push(e),t.hook("bundlerReport",t.bundler);const o=Gi(e);to(o,process.cwd()).startsWith(t.bundler.outDir)||n.warn("The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.")}}}]},Xi="datadog-custom-hooks-plugin",es=e=>{const{context:t}=e,n=t.getLogger(Xi),o=e=>(o,...r)=>{const i=n.time(`execution | ${o}`,{tags:["type:custom-hook",`hook:${o}`]}),s=[],a=[];for(const n of t.plugins){if(!(o in n))continue;const t=n[o];if("function"==typeof t)try{const i=t(...r);i instanceof Promise&&(e||s.push(`Plugin "${n.name}" returned a promise on the non async hook "${o}".`),a.push(i))}catch(e){s.push(`Plugin "${n.name}" errored on hook "${o}". [${e}]`)}else s.push(`Plugin "${n.name}" has an invalid hook type for "${o}". [${typeof t}]`)}if(s.length>0){for(const e of s)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>i.end()))};return t.hook=o(!1),t.asyncHook=o(!0),[{name:Xi,enforce:"pre"}]};class ts{constructor(e){this.trackedFilenames=new Map;for(const t of e){const e=this.getFilename(t),n=this.trackedFilenames.get(e);n?n.push(t):this.trackedFilenames.set(e,new Array(t))}}displaySource(e){return e.length<=40?e:`[...]${e.slice(-35)}`}matchSourcemap(e,t){const n=Ae(e),o=JSON.parse(n);if(!o.sources)return void t("Missing 'sources' field in sourcemap.");const r=o.sources;if(0===r.length)return void t("Empty 'sources' field in sourcemap.");const i=this.matchSources(r);if(0!==i.length)return i;t(`${r.map(this.displaySource).join(", ")} not in the tracked files.`)}matchSources(e){let t=[];const n=new Set;for(const o of e){const e=this.getFilename(o);if(n.has(e))continue;n.add(e);const r=this.trackedFilenames.get(e);r&&(t=t.concat(r))}return t}rawTrackedFilesList(){let e=[];return this.trackedFilenames.forEach((t=>{e=e.concat(t)})),e}getFilename(e){let t=e.lastIndexOf("/");-1===t?t=0:t++;let n=e.lastIndexOf("?");return(-1===n||n<=t)&&(n=e.length),e.substring(t,n)}}const ns=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await os(e);for(const e of t)if(e.name===n)return re(e.refs.push);return re(t[0].refs.push)},os=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},rs=async e=>e.revparse("HEAD"),is=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),ss=async e=>e.branch(),as=async e=>e.show(["-s","--format=%s"]),us=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),cs="datadog-git-plugin",ds=e=>{const{options:t,context:n}=e,o=n.getLogger(cs),r=o.time("get git information",{start:!1}),i=async e=>{try{const t=await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=S(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return S(t)})(u.dirname(e));if(0===(await t.getRemotes(!0)).length)return o.warn("No git remotes available, skipping git plugin. This is expected for a repository that has not been pushed yet."),void r.end();const i=await(async e=>{const t=[rs(e),ss(e),as(e),us(e),is(e),ns(e)],[n,o,r,i,s,a]=await Promise.all(t),[u,c,d,l,p,f]=i.split(",").map((e=>e.trim()));return{commit:{author:{name:u,email:c,date:d},committer:{name:l,email:p,date:f},message:r.trim(),hash:n},hash:n,branch:o.current,remote:a.trim(),trackedFilesMatcher:new ts(s)}})(t);n.git=i,r.end(),await n.asyncHook("git",n.git)}catch(e){o.error(`Could not get git information: ${e.message}`)}};return[{name:cs,enforce:"pre",buildRoot(e){if(te(t))try{r.resume();const t=eo(e,".git");if(!t)return o.warn("No .git directory found, skipping git plugin."),void r.end();n.queue(i(t))}catch(e){o.error(`Could not get git information: ${e.message}`)}}}]},ls="datadog-injection-plugin",ps=/^https?:\/\//,fs=[".mjs",".mjsx",".js",".ts",".tsx",".jsx"],ms=t.bold.yellow,hs=async(e,t=process.cwd())=>(e=>r.readFile(e,{encoding:"utf-8"}))(Xn(t,e));function gs(e){return e.some((e=>e.injectIntoAllChunks))}const ys=(e,t,n)=>{const o=e.filter((e=>e.position===t&&(!n||n.isEntry||e.injectIntoAllChunks))).map((e=>Es(e.value)?e.value(n):e.value)).filter(Boolean);if(0===o.length)return"";return`// begin injection by Datadog build plugins\n${o.map((e=>`(() => {${e}})();`)).join("\n\n")}\n// end injection by Datadog build plugins`},bs=async(e,t,n=process.cwd())=>{const o=Es(e.value)?await e.value():e.value;try{if("file"===e.type){const e=o;return await(e.match(ps)?(async(e,t=5e3)=>{let n;return Promise.race([Y({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,o)=>{n=setTimeout((()=>{o(new Error("Timeout"))}),t)}))])})(e):hs(e,n))}return o}catch(r){const i=`${e.type} - ${oe(o)}`;return e.fallback?(t.debug(`Fallback for "${i}": ${r.toString()}`),bs(e.fallback,t,n)):(t.warn(`Failed "${i}": ${r.toString()}`),"")}},ws=async(e,t,n,o=process.cwd())=>{const r=t.filter(xs).map((e=>{const t=e.value;return{...e,value:e=>t(e.sourceOrHash)}})),i=t.filter((e=>!xs(e))),s=await Promise.all(i.map((async t=>({...t,value:await bs(t,e,o)})))),a=e=>({...e,position:e.position??Te.BEFORE});n.push(...r.map(a),...s.map(a))},vs=e=>e instanceof Error&&"code"in e,$s=e=>fs.includes(e),ks=(e,t,n)=>{e.warn(`"${ms(t)}" files are not supported (${ms(n)}).`)},xs=e=>"function"==typeof e.value&&1===e.value.length,Es=e=>"function"==typeof e,Ss=s.promises,Is=(e,t,n)=>({setup(o){const{onStart:i,onResolve:a,onLoad:c,onEnd:d,esbuild:l,initialOptions:p}=o,f=[],m=`${t.bundler.name}.${Te.MIDDLE}.${O}.js`,g=s.realpathSync(h.tmpdir()),y=u.resolve(g,m),b=new RegExp(`${m}$`),w=p.inject;p.inject=w?[...w]:[],p.inject.push(y),i((async()=>{f.push(...await Ci(o,t,e)),o.initialOptions.inject=w;try{await(async(e,t)=>{await Ie(u.dirname(e)),await r.writeFile(e,t,{encoding:"utf-8"})})(y,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:b},(async e=>({path:e.path,namespace:ls}))),c({filter:b,namespace:ls},(async()=>({contents:ys(n,Te.MIDDLE)||" ",resolveDir:t.buildRoot,loader:"js"}))),d((async o=>{if(!o.metafile)return void e.warn("Missing metafile from build result.");if(!function(e){return e.some((e=>e.position===Te.BEFORE||e.position===Te.AFTER))}(n))return;const r=[];for(const[i,s]of Object.entries(o.metafile.outputs)){const o=Boolean(s.entryPoint&&f.some((e=>e.resolved.endsWith(s.entryPoint))));if(!o&&!gs(n))continue;const a=Xn(t.buildRoot,i),{base:c,ext:d}=u.parse(a);$s(d)?r.push((async()=>{try{const e=`${a}.map`,t=await Ss.readFile(a,"utf-8"),r=await Ss.readFile(e,"utf-8").catch((()=>!1)),i=u.basename(a),s=ys(n,Te.BEFORE,{sourceOrHash:t,fileName:i,isEntry:o}),c=ys(n,Te.AFTER,{sourceOrHash:t,fileName:i,isEntry:o});if(!s&&!c)return;const d=t.replace(/\n?\/\/# sourceMappingURL=.*$/m,""),p=r?`${d}\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(r).toString("base64")}`:d,f=await l.transform(p,{loader:"default",banner:s,footer:c,sourcemap:r?"external":void 0,sourcefile:i});await Promise.all([Ss.writeFile(a,f.code),r&&f.map?Ss.writeFile(e,f.map):null])}catch(t){if(!vs(t)||"ENOENT"!==t.code)throw t;e.warn(`Could not inject content in ${a}: ${t}`)}})()):ks(e,d,c)}await Promise.all(r)}))}}),Ds=O,As="?inject-proxy",Ps=(e,t)=>({renderChunk(n,o){const{base:r,ext:i}=u.parse(o.fileName);if(!$s(i))return ks(e,i,r),null;const s=ys(t,Te.BEFORE,{sourceOrHash:n,fileName:o.fileName,isEntry:o.isEntry}),a=ys(t,Te.AFTER,{sourceOrHash:n,fileName:o.fileName,isEntry:o.isEntry});if(!s&&!a)return null;const c=new I(n);return s&&c.prepend(`${s}\n`),a&&c.append(`\n${a}`),{code:c.toString(),map:c.generateMap({file:o.fileName,hires:"boundary"})}},async resolveId(e,n,o){if(X(e))return{id:e,moduleSideEffects:!0};if(o.isEntry&&ys(t,Te.MIDDLE)){if(e.endsWith(".html"))return null;const t=await this.resolve(e,n,o);if(!t||t.external)return t;return(await this.load(t)).moduleSideEffects=!0,`${t.id}${As}`}return null},load(e){if(X(e))return ys(t,Te.MIDDLE);if(e.endsWith(As)){const t=e.slice(0,-13),n=this.getModuleInfo(t);let o=`import ${JSON.stringify(Ds)};\nexport * from ${JSON.stringify(t)};`;return n?.hasDefaultExport&&(o+=`export { default } from ${JSON.stringify(t)};`),o}return null}}),js=(e,t,n,o,r)=>i=>{const a=new WeakMap,c=e.sources.ConcatSource,d=n.bundler.name,l=u.resolve(n.buildRoot,"node_modules",".cache","datadog-build-plugins",`${d}.${Te.MIDDLE}.${O}.js`);De(l,"");i.hooks.shutdown.tap(ls,(()=>{var e;e=l,s.rmSync(e,{force:!0,maxRetries:3,recursive:!0})}));const p=async()=>{await ws(t,o,r,n.buildRoot)};i.hooks.beforeRun.tapPromise(ls,p),i.hooks.watchRun.tapPromise(ls,p),i.hooks.compilation.tap(ls,(n=>{const o=e.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;n.hooks.processAssets.tap({name:ls,stage:o},(()=>{for(const e of n.chunks){const o=e.canBeInitial(),i=e.contentHash?.javascript??e.hash;for(const s of e.files){const{base:e,ext:d}=u.parse(s);if(!$s(d)){ks(t,d,e);continue}const l=u.basename(s),p=ys(r,Te.BEFORE,{sourceOrHash:i,fileName:l,isEntry:o}),f=ys(r,Te.AFTER,{sourceOrHash:i,fileName:l,isEntry:o});""===p&&""===f||n.updateAsset(s,(e=>{const t=a.get(e);if(!t||t.banner!==p||t.footer!==f){const t=new c(p,"\n",e,"\n",f);return a.set(e,{source:t,banner:p,footer:f}),t}return t.source}))}}}))}));const f=(e=>{const n={import:[l]},o=e=>{for(const[n,o]of Object.entries(e))"object"==typeof o?(o.import=o.import||[],o.import.unshift(l)):"string"==typeof o?e[n]=[l,o]:Array.isArray(o)?o.unshift(l):t.error("Invalid entry type: "+typeof o)};return e?"function"==typeof e?async()=>{const t=await e();return o(t),t}:"object"!=typeof e?"string"==typeof e?[n,e]:(t.error("Invalid entry type: "+typeof e),e):(o(e),e):{ddHelper:n}})(i.options.entry);i.options.entry=f},Ms=e=>{const{bundler:t,context:n}=e,o=n.getLogger(ls),r=[],i=[];n.inject=e=>{r.push(e)};const s={name:ls,enforce:"post",esbuild:Is(o,n,i),webpack:js(t,o,n,r,i),rspack:js(t,o,n,r,i),rollup:Ps(o,i),vite:{...Ps(o,i),enforce:"pre",transformIndexHtml:{order:"pre",handler:()=>ys(i,Te.MIDDLE)?[{tag:"script",attrs:{type:"module",src:"/@id/__datadog-helper-file"},injectTo:"head-prepend"}]:[]}}};var a;return a=n.bundler.name,["rspack","webpack"].includes(a)?s.load={filter:{id:N},handler:()=>({code:ys(i,Te.MIDDLE)})}:s.buildStart=async()=>{await ws(o,r,i,n.buildRoot)},[s]},Ts="datadog-true-end-plugin",Cs=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},o=async()=>{await t.asyncHook("flush")},r=()=>{t.hook("syncTrueEnd")},i=async()=>{r(),await n(),await o()},s=e=>{e.hooks.shutdown.tapPromise(Ts,i)},a={async writeBundle(){},async closeBundle(){await i()}};return[{name:Ts,enforce:"post",webpack:s,esbuild:{setup(e){e.onEnd((async()=>{await n(),await o()})),e.onDispose((()=>{r()}))}},vite:a,rollup:a,rspack:s}]},Os={[Cr]:ui},Ns=t.bold.red;var Rs="3.2.6-dev.0";const _s=(({bundler:t,version:n})=>{const o=Date.now();return e(((e,r)=>{const i=Date.now(),s=((e={})=>{const t=(e=>{const t=[];return void 0===e||void 0!==e.version&&"string"!=typeof e.version&&t.push("metadata.version must be a string"),t})(e.metadata),n=q("SITE"),o={site:K(n,"DATADOG_SITE/DD_SITE",t)??K(e.auth?.site,"auth.site",t)??F};if(t.length)throw new Error(`Invalid Datadog plugin configuration:\n - ${t.join("\n - ")}`);return Object.defineProperty(o,"apiKey",{value:q("API_KEY")||e.auth?.apiKey,enumerable:!1}),Object.defineProperty(o,"appKey",{value:q("APP_KEY")||e.auth?.appKey,enumerable:!1}),{enableGit:!0,logLevel:"warn",metadata:{},...e,auth:o}})(e);"esbuild"===r.framework&&(r.esbuildHostName=z);const a=process.env.BUILD_PLUGINS_ENV||"production",u=R.includes(a)?a:"development",c=t.rspackVersion||t.version||t.VERSION,d=r.framework,l={bundler:{name:d,version:c},env:u,metadata:s.metadata||{},packageName:`@datadog/${d}-plugin`,version:n},p={errors:[],logs:[],metrics:new Set,queue:[],timings:[],warnings:[]},f=(({start:e,options:t,data:n,stores:o})=>{const r=process.cwd(),i={errors:o.errors,warnings:o.warnings,logs:o.logs,metadata:n.metadata,timings:o.timings,bundler:n.bundler};return{addMetric:()=>{throw new Error("AddMetric function called before it was initialized.")},auth:t.auth,pluginNames:[],bundler:{...i.bundler,outDir:r},build:i,buildRoot:r,env:n.env,getLogger:le(n,o,t.logLevel),asyncHook:()=>{throw new Error("AsyncHook function called before it was initialized.")},hook:()=>{throw new Error("Hook function called before it was initialized.")},inject:()=>{throw new Error("Inject function called before it was initialized.")},plugins:[],queue:()=>{throw new Error("Queue function called before it was initialized.")},sendLog:Q(n),start:e,version:n.version}})({start:o,options:s,data:l,stores:p}),m=f.getLogger("factory"),h=m.time("Plugins initialization",{start:i});f.pluginNames.push(z);const g=[];g.push(["analytics",ji],["async-queue",Ti],["build-report",Hi],["bundler-report",Zi],["custom-hooks",es],["git",ds],["injection",Ms],["true-end",Cs]),s.customPlugins&&g.push(["custom",s.customPlugins]);const y=[["apps",ye,$o],["error-tracking",ko,Bo],["live-debugger",qo,Mr],["metrics",Cr,ci],["output",di,gi],["rum",yi,Ai]];for(const[e,t,n]of y)ge(s,t,m)&&g.push([e,n]);for(const[e,n]of g)f.plugins.push(...me(f,n,e)({bundler:t,context:f,options:s,data:l,stores:p}));return(e=>{const t=[];for(const n of B){const o=V(n);if(o.length>1&&!o.every((e=>process.env[e]===process.env[o[0]]))){const r=o.map((e=>U(e))).join(" and "),i=U(`DATADOG_${n}`);e.warn(`Conflicting keys ${r}, will use ${i}`),t.push(`${r} (using ${i})`)}else if(o.length){const e=o.map((e=>L(e))).join(" and ");t.push(`${e} (same value)`)}}t.length&&e.info(`Overrides from environment:\n - ${t.join("\n - ")}`)})(m),f.pluginNames.push(...f.plugins.map((e=>e.name))),(e=>{const t=new Set(e.filter((t=>e.filter((e=>e===t)).length>1)));if(t.size>0)throw new Error(`Duplicate plugin names: ${Ns(Array.from(t).join(", "))}`)})(f.pluginNames),f.hook("init",f),h.end(),f.plugins}))})({bundler:D,version:Rs}).esbuild,Fs=Rs,zs=Os;export{_s as datadogEsbuildPlugin,zs as helpers,Fs as version};
|
|
1
|
+
import{createUnplugin as e}from"unplugin";import t from"chalk";import n from"async-retry";import{File as o}from"buffer";import r,{mkdtemp as i}from"fs/promises";import s from"fs";import{JsonStreamStringify as a}from"json-stream-stringify";import u from"path";import{Readable as c}from"stream";import{spawn as d}from"child_process";import{randomBytes as l,createHash as p,randomUUID as f}from"crypto";import m from"http";import h,{tmpdir as g}from"os";import*as y from"eslint-scope";import b from"jszip";import{glob as w}from"glob";import v from"pretty-bytes";import $ from"p-queue";import k from"@jridgewell/remapping";import{performance as x}from"perf_hooks";import{instrument as E}from"@datadog/js-instrumentation-wasm";import{simpleGit as S}from"simple-git";import I from"magic-string";import D from"esbuild";import A from"node:url";import P from"node:path";import j from"node:module";const M=A.fileURLToPath(import.meta.url),T=P.dirname(M),C=j.createRequire(import.meta.url),O="__datadog-helper-file",N=new RegExp(O),R=["development","production","test"],_=["datadoghq.com","us3.datadoghq.com","us5.datadoghq.com","datadoghq.eu","ddog-gov.com","us2.ddog-gov.com","ap1.datadoghq.com","ap2.datadoghq.com","datad0g.com"],F=_[0],z="datadog-build-plugins",L=t.bold.green,U=t.bold.yellow,B=["API_KEY","APP_KEY","SOURCEMAP_INTAKE_URL","APPS_INTAKE_URL","APPS_UPLOAD_ASSETS","APPS_VERSION_NAME","APPS_AUTH_METHOD","SITE"],q=e=>process.env[`DATADOG_${e}`]||process.env[`DD_${e}`],V=e=>{const t=[];return process.env[`DD_${e}`]&&t.push(`DD_${e}`),process.env[`DATADOG_${e}`]&&t.push(`DATADOG_${e}`),t},K=(e,t,n)=>{if(void 0!==e)return(e=>_.some((t=>t===e)))(e)?e:void n.push(`${t} "${e}" is not a supported Datadog site. See the site parameters in https://docs.datadoghq.com/getting_started/site/.`)},H=e=>{if(null===e||"object"!=typeof e)return"";const t="title"in e&&"string"==typeof e.title?e.title:void 0,n="detail"in e&&"string"==typeof e.detail?e.detail:void 0;return t&&n?`${t}: ${n}`:t||(n?`detail: ${n}`:"")},W=e=>({"DD-EVP-ORIGIN":`${e.bundler}-build-plugin_${e.plugin}`,"DD-EVP-ORIGIN-VERSION":e.version}),J=async e=>{const{getForm:t,defaultHeaders:n={},zip:o=!0}=e,r=await t(),i=new Request("fake://url",{method:"POST",body:r});return{data:o?i.body.pipeThrough(new CompressionStream("gzip")):i.body,headers:{"Content-Encoding":o?"gzip":"multipart/form-data",...n,...Object.fromEntries(i.headers.entries())}}},G=[400,401,403,404,405,409,413],Y=async e=>{const{auth:t,url:o,method:r="GET",getData:i,type:s="text"}=e,a={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return n((async(e,n)=>{let a;try{const e={method:r,duplex:"half"};let n={"X-Datadog-Origin":"build-plugins"};if(t&&"accessToken"in t?t.accessToken&&(n.Authorization=`Bearer ${t.accessToken}`):(t?.apiKey&&(n["DD-API-KEY"]=t.apiKey),t?.appKey&&(n["DD-APPLICATION-KEY"]=t.appKey)),"function"==typeof i){const{data:t,headers:o}=await i();e.body=t,n={...n,...o}}a=await fetch(o,{...e,headers:n})}catch(t){return e(t),{}}if(!a.ok){let t=`HTTP ${a.status} ${a.statusText}`;try{const e=(e=>{try{const t=JSON.parse(e);if(null!==t&&"object"==typeof t)if("errors"in t&&Array.isArray(t.errors)){const e=t.errors.map(H).filter((e=>e.length>0)).join("\n");if(e)return e}else{const e=H(t);if(e)return e}}catch{}return e})(await a.text());e&&(t+=`\n${e}`)}catch{}if(G.includes(a.status))return e(new Error(t)),{};throw new Error(t)}try{let e;return e="json"===s?await a.json():await a.text(),e}catch(t){return e(t),{}}}),a)},Q=e=>({message:t,context:n})=>Y({retries:2,minTimeout:100,url:"https://browser-http-intake.logs.datadoghq.com/v1/input/pub44d5f4eb86e1392037b7501f7adc540e",method:"POST",type:"json",getData:async()=>{const o={ddsource:e.packageName||z,message:t,service:"build-plugins",team:"language-foundations",env:e.env,version:e.version,bundler:{name:e.bundler.name,version:e.bundler.version},metadata:e.metadata,...n};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}}),Z=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),X=e=>e.includes(O),ee=e=>{const t={bundler:e.bundler,errors:e.errors,metadata:e.metadata,warnings:e.warnings,logs:e.logs,timings:e.timings,start:e.start,end:e.end,duration:e.duration,writeDuration:e.writeDuration,entries:[],inputs:[],outputs:[]};for(const n of e.entries||[]){const e={...n,inputs:[],outputs:[]};n.inputs&&(e.inputs=n.inputs.map((e=>e.filepath))),n.outputs&&(e.outputs=n.outputs.map((e=>e.filepath))),t.entries.push(e)}for(const n of e.inputs||[]){const e={...n,dependencies:[],dependents:[]};if(n.dependencies)for(const t of n.dependencies)e.dependencies.push(t.filepath);if(n.dependents)for(const t of n.dependents)e.dependents.push(t.filepath);t.inputs.push(e)}for(const n of e.outputs||[]){const e={...n,inputs:[]};n.inputs&&(e.inputs=n.inputs.map((e=>e.filepath))),t.outputs.push(e)}return t},te=e=>{const t=!!e.errorTracking?.sourcemaps,n=e.enableGit??!0;return t&&n},ne=e=>{const t=Math.floor(e/1e3/60/60/24),n=new Date(e-24*t*60*60*1e3),o=n.getUTCHours(),r=n.getUTCMinutes(),i=n.getUTCSeconds(),s=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${o?`${o}h `:""}${r?`${r}m `:""}${i?`${i}s`:""}`.trim();return`${a}${!a||s?` ${s}ms`:""}`.trim()},oe=(e,t=60,n="[...]")=>{if(e.length<=t)return e;const o=Math.max(4,t-n.length),r=Math.min(10,Math.floor(o/2)),i=o-r;return`${e.slice(0,r)}${n}${e.slice(-i)}`},re=(e="")=>{try{if(!e||e.startsWith("git@"))return e;const t=new URL(e),n="/"===t.pathname?"":t.pathname;return`${t.protocol?`${t.protocol}//`:""}${t.host}${n}`}catch{return e}},ie=e=>e.trim().toLowerCase().replace(/[^a-z0-9_:./-]+/g,"_").replace(/^_+|_+$/g,"")||"unknown",se=e=>Object.entries(e).map((([e,n])=>` - ${e}: ${t.bold.green((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if(Array.isArray(e))return e.join(", ");if("object"==typeof e)try{return JSON.stringify(e,null,2)}catch{return String(e)}return e?.toString()??""})(n))}`)).join("\n"),ae={debug:0,info:1,warn:2,error:3,none:4},ue=e=>e.split(">").map(Z).join(">"),ce=(e,n,o,r)=>{const i=ue(e);return(s,a="debug",{forward:u,context:c}={})=>{let d=t.dim,l=console.log;"error"===a?(d=t.red,l=console.error):"warn"===a?(d=t.yellow,l=console.warn):"info"===a&&(d=t.cyan,l=console.log);const p=`[${n.metadata?.name?`${n.metadata.name}|`:""}${a}|${n.bundler.name}|${i}]`,f="string"==typeof s?s:JSON.stringify(s,null,2);if(o.logs.push({bundler:n.bundler.name,pluginName:e,type:a,message:f,time:Date.now()}),"error"===a&&o.errors.push(f),"warn"===a&&o.warnings.push(f),u){const t=async()=>{try{const t=Q(n);await t({message:f,context:{plugin:e,status:a,...c}})}catch(t){ce(e,n,o,r)(`Error forwarding log: ${t}`,"debug")}};o.queue.push(t())}ae[a]>=ae[r]&&l(`${d(p)} ${f}`)}},de=(e,n,o)=>(r,i={})=>{const{level:s="debug",start:a=!0,log:u=!0,tags:c=[]}=i,d={pluginName:e,label:r,spans:[],tags:[...c,`plugin:${e}`,`level:${s}`],logLevel:s,total:0};n.push(d);const l=()=>d.spans.filter((e=>!e.end)),p=n=>{l().length||(!d.spans.length&&u&&o(t.dim(`[${t.cyan(r)}] : start`),"debug"),d.spans.push({start:n||Date.now(),tags:[`plugin:${e}`]}))},f=(e,n=!0)=>{const i=l();if(i?.length){i.length>1&&o(`Timer ${t.cyan(r)} has more than one ongoing span.`,"debug");for(const t of i)t.end=e||Date.now()}else n&&o(`Timer ${t.cyan(r)} cannot be paused, no ongoing span.`,"debug")};if(a){let e;"number"==typeof a&&(e=a),p(e)}return{timer:d,resume:p,end:e=>{f(e,!1);const n=d.spans.reduce(((e,t)=>e+(t.end-t.start)),0);d.total=n,u&&o(`[${t.cyan(r)}] : ${t.cyan(ne(n))}`,s)},pause:f,tag:(e,t={})=>{const{span:n=!1}=t;if(n){const t=l();for(const n of t)n.tags.push(...e)}else d.tags.push(...e)}}},le=(e,t,n="warn")=>o=>{const r=ce(o,e,t,n);return{getLogger:r=>le(e,t,n)(`${ue(o)}>${r}`),time:de(o,t.timings,r),error:(e,t)=>r(e,"error",t),warn:(e,t)=>r(e,"warn",t),info:(e,t)=>r(e,"info",t),debug:(e,t)=>r(e,"debug",t)}},pe=["buildEnd","buildStart","load","resolveId","transform","watchChange","writeBundle","buildRoot","init","buildReport","bundlerReport","git"],fe=(e,t,n,o)=>{const r=n=>function(...r){const i=o.time(`${e} | ${t}`,{log:!1,tags:["type:hook",`hook:${t}`]}),s=n.apply(this,r);return s instanceof Promise?s.finally((()=>{i.end()})):(i.end(),s)};return"object"==typeof n&&null!==n&&"handler"in n?{...n,handler:r(n.handler)}:r(n)},me=(e,t,n)=>{const o=e.getLogger(z);return e=>{const r=o.time(`hook | init ${n}`,{log:!1}),i=t(e).map((e=>((e,t)=>{const n={...e},o=Z(e.name);for(const r of pe){const i=e[r];i&&(n[r]=fe(o,r,i,t))}return n})(e,o))),s=i.map((e=>`plugin:${e.name}`));return r.tag(s),r.end(),i}},he=new Set,ge=(e,t,n)=>{const o=e[t];if(o&&"object"==typeof o&&"enable"in o){const e=o.enable;if("boolean"!=typeof e&&void 0!==e&&(he.has(t)||(he.add(t),n.warn(`\`${t}.enable\` should be a boolean, got ${typeof e}. Non-boolean values are coerced today but will be rejected in the next major.`))),void 0!==e)return!!e}return!!o},ye="apps",be="datadog-apps-plugin",we="api/unstable/app-builder-code/apps",ve="datadog-apps-assets.zip",$e=/\.backend\.(ts|tsx|js|jsx)$/,ke=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],xe=["apiKey","oauth"],Ee=e=>{const t=e[ye]||{},n=(e=>{if(void 0!==e){if(xe.includes(e))return e;throw new Error(`apps.authOverrides.method must be one of: ${xe.join(", ")}`)}})(q("APPS_AUTH_METHOD")||t.authOverrides?.method)||((e=>Boolean((q("API_KEY")||e.auth?.apiKey)&&(q("APP_KEY")||e.auth?.appKey)))(e)?"apiKey":"oauth");return{include:t.include||[],dryRun:t.dryRun??!q("APPS_UPLOAD_ASSETS"),identifier:t.identifier?.trim(),name:t.name?.trim()||e.metadata?.name?.trim(),authOverrides:{method:n}}},Se=async e=>r.rm(e,{force:!0,maxRetries:3,recursive:!0}),Ie=async e=>r.mkdir(e,{recursive:!0}),De=(e,t)=>{var n;n=u.dirname(e),s.mkdirSync(n,{recursive:!0}),s.writeFileSync(e,t,{encoding:"utf-8"})},Ae=e=>s.readFileSync(e,{encoding:"utf-8"}),Pe=e=>{try{return s.existsSync(e)}catch(e){if("ENOENT"===e.code)return!1;throw e}},je=async(e,t)=>{if("function"==typeof s.openAsBlob){const n=await s.openAsBlob(e,{type:t.contentType});return new o([n],t.filename)}{const n=c.toWeb(s.createReadStream(e)),r=await new Response(n).blob();return new o([r],t.filename,{type:t.contentType})}},Me=async e=>{const t={empty:!1,exists:!0};try{const{size:n}=await r.stat(e);0===n&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t};var Te=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Te||{});const Ce=()=>import("oauth4webapi"),Oe=t.cyan.bold,Ne=e=>e.toString("base64url"),Re=e=>{const t=(e=>"datad0g.com"===e?"f4bacdd2-0c8c-49f5-bf3e-a62ba3ec02e6":"e17b9ffa-3daf-4124-ba1b-4ac8c547d506")(e);return{authorizationUrl:`https://app.${e}/oauth2/v1/authorize`,cacheTokens:!0,clientId:t,openBrowser:!0,redirectUri:"http://localhost:8060",timeoutMs:3e5,tokenUrl:`https://api.${e}/oauth2/v1/token`}},_e=e=>({client_id:e}),Fe=e=>({issuer:new URL(e.authorizationUrl).origin,authorization_endpoint:e.authorizationUrl,token_endpoint:e.tokenUrl}),ze=(e,t)=>`${e}:${t.clientId}:${((e,t)=>p("sha256").update([t.clientId,e,t.authorizationUrl,t.tokenUrl].join("|")).digest("hex").slice(0,16))(e,t)}`,Le=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=UTF-8"}),e.end(n)},Ue=(e,t,n=Date.now())=>({accessToken:e.access_token,expiresAt:"number"==typeof e.expires_in?n+1e3*e.expires_in:void 0,expiresIn:e.expires_in,refreshToken:e.refresh_token,scope:e.scope,site:t,tokenType:e.token_type}),Be=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),qe=e=>e instanceof Error?e.message:String(e),Ve=e=>{const t=qe(e).toLowerCase();return"NoEntry"===(e=>Be(e)&&"string"==typeof e.code?e.code:void 0)(e)||t.includes("noentry")||t.includes("no matching entry")||t.includes("not found")},Ke=async(e,t)=>{const{AsyncEntry:n}=await import("@napi-rs/keyring");return new n("datadog-build-plugins:oauth",ze(e,t))},He=(e,t)=>new Error(`Could not ${e} Datadog OAuth token in the OS credential store. ${t instanceof Error?t.message:String(t)}`),We=async(e,t)=>{try{const n=await Ke(e,t),o=await n.getPassword();if(!o)return;const r=JSON.parse(o);return(e=>{if(Be(e)&&1===e.version&&Be(e.token)&&"string"==typeof e.token.accessToken&&"string"==typeof e.token.clientId&&"string"==typeof e.token.site)return e})(r)?.token}catch(e){if(Ve(e))return;throw He("read",e)}},Je=async(e,t,n,o=e.site)=>{if(t.cacheTokens)try{await(async(e,t,n)=>{try{const o=await Ke(e,n),r={version:1,token:t};await o.setPassword(JSON.stringify(r))}catch(e){throw He("save",e)}})(o,((e,t)=>({accessToken:e.accessToken,clientId:t,expiresAt:e.expiresAt,refreshToken:e.refreshToken,scope:e.scope,site:e.site,tokenType:e.tokenType}))(e,t.clientId),t),n.debug("Saved Datadog OAuth token to the OS credential store.")}catch(e){n.warn(`Could not save Datadog OAuth token to the OS credential store; continuing without a persistent cache. ${qe(e)}`)}},Ge=async(e,t,n)=>{if(t.cacheTokens)try{await(async(e,t)=>{try{const n=await Ke(e,t);await n.deletePassword()}catch(e){if(!Ve(e))throw He("delete",e)}})(e,t)}catch(e){n.warn(`Could not delete cached Datadog OAuth token. ${qe(e)}`)}},Ye=async(e,t,n)=>{if(!t.cacheTokens)return;let o;try{o=await We(e,t)}catch(e){n.warn(`Could not read cached Datadog OAuth token; starting browser authorization. ${qe(e)}`)}if(o){if(void 0===(r=o).expiresAt||r.expiresAt>Date.now()+3e5)return n.debug("Using cached Datadog OAuth access token."),(e=>({accessToken:e.accessToken,expiresAt:e.expiresAt,refreshToken:e.refreshToken,scope:e.scope,site:e.site,tokenType:e.tokenType}))(o);var r;if(o.refreshToken)try{n.debug("Refreshing cached Datadog OAuth access token.");const r=await(async(e,t,n)=>{const o=await Ce(),r=Fe(t),i=_e(t.clientId),s=await o.refreshTokenGrantRequest(r,i,o.None(),n),a=await o.processRefreshTokenResponse(r,i,s);return Ue({...a,refresh_token:a.refresh_token||n},e)})(e,t,o.refreshToken);return await Je(r,t,n),r}catch(o){return n.warn(`Cached Datadog OAuth token could not be refreshed; starting browser authorization. ${o instanceof Error?o.message:String(o)}`),void await Ge(e,t,n)}}},Qe=async(e,t,n)=>{const o=await Ce(),r=Fe(t),i=_e(t.clientId),s=Ne(l(32)),a=await(async e=>(await Ce()).calculatePKCECodeChallenge(e))(s),u=Ne(l(32)),c=(e=>{const t=new URL(e.authorizationUrl);return t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("client_id",e.clientId),t.searchParams.set("response_type","code"),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("state",e.state),t})({authorizationUrl:t.authorizationUrl,clientId:t.clientId,codeChallenge:a,redirectUri:t.redirectUri,state:u}),p=(async e=>{const t=new URL(e.redirectUri),n=Number(t.port||80);if("http:"!==t.protocol)throw new Error("OAuth redirect URI must use http for the local OAuth callback.");if(!Number.isInteger(n)||n<=0)throw new Error("OAuth redirect URI must include a valid port.");let o,r=!1;const i=m.createServer();try{return await new Promise(((s,a)=>{const u=e=>{r||(r=!0,e())};i.on("request",((n,o)=>{const r=new URL(n.url||"/",t.origin);if(r.pathname!==t.pathname)return void Le(o,404,"Not found.");let i;try{i=e.oauth.validateAuthResponse(e.authorizationServer,e.client,r,e.state)}catch(e){return Le(o,400,"OAuth authorization failed. You may now close this tab."),void u((()=>a(e instanceof Error?e:new Error(String(e)))))}if(!i.get("code"))return Le(o,400,"Missing OAuth authorization code. You may now close this tab."),void u((()=>a(new Error("Missing OAuth authorization code."))));Le(o,200,"OAuth authorization complete. You may now close this tab."),u((()=>s({callbackParameters:i})))})),i.once("error",(e=>u((()=>a(e))))),o=setTimeout((()=>{u((()=>a(new Error(`Timed out waiting for OAuth callback after ${e.timeoutMs}ms.`))))}),e.timeoutMs);try{const e="localhost"===t.hostname?void 0:t.hostname;i.listen(n,e)}catch(e){u((()=>a(e instanceof Error?e:new Error(String(e)))))}}))}finally{o&&clearTimeout(o),i.listening&&(i.close(),i.closeAllConnections?.(),i.closeIdleConnections?.())}})({authorizationServer:r,client:i,oauth:o,redirectUri:t.redirectUri,state:u,timeoutMs:t.timeoutMs});n.info(`Authorize Datadog Apps upload:\n ${Oe(c.toString())}`),t.openBrowser&&((e,t)=>{const n="darwin"===process.platform?{command:"open",args:[e]}:"win32"===process.platform?{command:"cmd",args:["/c","start","",e]}:{command:"xdg-open",args:[e]};try{const e=d(n.command,n.args,{detached:!0,stdio:"ignore"});e.once("error",(e=>{t.warn(`Could not open browser automatically: ${qe(e)}`)})),e.unref()}catch(e){t.warn(`Could not open browser automatically: ${qe(e)}`)}})(c.toString(),n);return(async e=>{const t=await Ce(),n=Fe(e),o=_e(e.clientId),r=await t.authorizationCodeGrantRequest(n,o,t.None(),e.callbackParameters,e.redirectUri,e.codeVerifier),i=await t.processAuthorizationCodeResponse(n,o,r);return Ue(i,e.site)})({callbackParameters:(await p).callbackParameters,clientId:t.clientId,codeVerifier:s,redirectUri:t.redirectUri,site:e,tokenUrl:t.tokenUrl,authorizationUrl:t.authorizationUrl})},Ze=new Map,Xe=async(e,t)=>{const n=Re(e),o=`${e}:${n.clientId}`;let r=Ze.get(o);return r||(r=(async(e,t,n)=>{const o=await Ye(e,t,n);return o?{persistAfterSuccessfulRequest:!1,token:o}:{persistAfterSuccessfulRequest:!0,token:await Qe(e,t,n)}})(e,n,t).catch((e=>{throw Ze.delete(o),e})),Ze.set(o,r)),r},et='Set apps.authOverrides.method: "oauth" or DD_APPS_AUTH_METHOD=oauth to use OAuth, or set DD_API_KEY and DD_APP_KEY to use API/App key auth.';class tt extends Error{constructor(){super(`Missing authentication. ${et}`),this.statusCode=400,this.name="MissingAuthenticationError"}}const nt=(e,t,n)=>{if("oauth"===e)return e=>(async({auth:e,log:t,...n})=>{const{site:o}=e,{persistAfterSuccessfulRequest:r,token:i}=await Xe(o,t);if(!i.accessToken)throw new Error("OAuth authentication did not return an access token.");const s=await Y({...n,auth:{accessToken:i.accessToken}});return r&&await Je(i,Re(o),t,o),s})({...e,auth:t,log:n});if(t.apiKey&&t.appKey)return e=>Y({...e,auth:{apiKey:t.apiKey,appKey:t.appKey}});throw new tt};function ot(e,t){if(!function(e){return"Program"===e.type}(e))throw new Error(`Expected a Program node from this.parse() for ${t}, got ${e.type}`);return e}function rt(e){return"object"==typeof e&&null!==e&&"Literal"===e.type&&"string"==typeof e.value}function it(e){return"type"===e.importKind||"type"===e.exportKind}function st(e,t){return function(e,t){const n=ot(e,t),o=function(e){const t=new Map;for(const n of e.body)if("FunctionDeclaration"===n.type&&n.id)t.set(n.id.name,{kind:"function"});else if("ClassDeclaration"===n.type&&n.id)t.set(n.id.name,{kind:"class"});else if("VariableDeclaration"===n.type)for(const e of n.declarations)"Identifier"===e.id.type&&t.set(e.id.name,{kind:"variable",init:e.init});else if("ImportDeclaration"===n.type)for(const e of n.specifiers)t.set(e.local.name,{kind:"import"});return t}(n),r=[];for(const e of n.body){if("ExportDefaultDeclaration"===e.type)throw new Error(`Default exports are not supported in .backend.ts files. Use a named export instead: ${t}`);if("ExportAllDeclaration"===e.type)throw new Error(`"export *" is not supported in .backend.ts files. Use explicit named exports instead: ${t}`);if("ExportNamedDeclaration"!==e.type)continue;e.declaration&&r.push(...ct(e.declaration,t).map((e=>({kind:"local",name:e,localName:e}))));const n="string"==typeof e.source?.value?e.source.value:null;for(const i of e.specifiers){if("Identifier"!==i.exported.type)continue;if("default"===i.exported.name)throw new Error(`Default exports are not supported in .backend.ts files. Use a named export instead: ${t}`);const e="Identifier"===i.local.type?i.local.name:"string"==typeof i.local.value?i.local.value:null;e&&(n?r.push({kind:"re-export",name:i.exported.name,localName:e,source:n}):("Identifier"===i.local.type&&dt(e,o,t),r.push({kind:"local",name:i.exported.name,localName:e})))}}return r}(e,t).map((e=>e.name))}const at=new Set(["ArrayExpression","Literal","ObjectExpression","TemplateLiteral"]);function ut(e){return null==e||at.has(e.type)}function ct(e,t){if("FunctionDeclaration"===e.type&&e.id)return[e.id.name];if("ClassDeclaration"===e.type)throw new Error(`Class exports are not supported in .backend.ts files. Only function exports are allowed: ${t}`);if("VariableDeclaration"===e.type)return e.declarations.flatMap((e=>{if("Identifier"!==e.id.type)throw new Error(`Destructured exports are not supported in backend files. Use individual named exports instead: ${t}`);if(ut(e.init))throw new Error(`Non-function export "${e.id.name}" in backend file ${t}. Only function exports are supported — use "export function ${e.id.name}(…) { }" instead.`);return[e.id.name]}));throw new Error(`Unsupported export declaration type "${e.type}" in backend file ${t}. Only function and variable exports are allowed.`)}function dt(e,t,n){const o=t.get(e);if(o){if("class"===o.kind)throw new Error(`Class exports are not supported in .backend.ts files. Only function exports are allowed: ${n}`);if("variable"===o.kind&&ut(o.init))throw new Error(`Non-function export "${e}" in backend file ${n}. Only function exports are supported — use "export function ${e}(…) { }" instead.`)}}function lt(e){const t=e.relativePath.split(u.sep).join("/");return`${p("sha256").update(t).digest("hex")}.${e.name}`}function pt(e){const t=[];for(const{exportName:n,queryName:o}of e)t.push(`export async function ${n}(...args) {`),t.push(` return globalThis.DD_APPS_RUNTIME.executeBackendFunction(${JSON.stringify(o)}, args);`),t.push("}"),t.push("");return t.join("\n")}function ft(e,t,n){const o=[];return o.push(`import { ${e} } from ${JSON.stringify(t)};`),function(e){try{return C.resolve("@datadog/action-catalog/action-execution",{paths:[e]}),!0}catch{return!1}}(n)&&o.push("import { setExecuteActionImplementation } from '@datadog/action-catalog/action-execution';"),o.push(""),o.push('/** @param {import("./context.types").Context} $ */'),o.push("export async function main($) {"),o.push(" globalThis.$ = $;"),o.push(""),o.push(" // Register the $.Actions-based implementation for executeAction"),o.push(" if (typeof setExecuteActionImplementation === 'function') {\n setExecuteActionImplementation(async (actionId, request) => {\n const actionPath = actionId.replace(/^com\\.datadoghq\\./, '');\n const pathParts = actionPath.split('.');\n let actionFn = $.Actions;\n for (const part of pathParts) {\n if (!actionFn) throw new Error('Action not found: ' + actionId);\n actionFn = actionFn[part];\n }\n if (typeof actionFn !== 'function') throw new Error('Action is not a function: ' + actionId);\n return actionFn(request);\n });\n }"),o.push(""),o.push(" const args = $.backendFunctionArgs ?? [];"),o.push(` const result = await ${e}(...args);`),o.push(" return result;"),o.push("}"),o.join("\n")}function mt(e,t,n){const o={state:t},r=e=>{n._?.(e,o),function(e,t){return t[e.type]}(e,n)?.(e,o);for(const t of Object.keys(e))"type"!==t&&i(e[t])},i=e=>{if(Array.isArray(e))for(const t of e)ht(t)&&r(t);else ht(e)&&r(e)};r(e)}function ht(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type}function gt(e){mt(e,null,{_(e){const t=e;t.range||"number"!=typeof t.start||"number"!=typeof t.end||(t.range=[t.start,t.end])}});const t=y.analyze(e,{ecmaVersion:2022,ignoreEval:!0,sourceType:"module"}),n=new Map;for(const e of t.scopes)for(const t of e.references)n.set(t.identifier,t);return{scopeManager:t,referencesByIdentifier:n,moduleScope:vt(t)}}function yt(e,t){return t.referencesByIdentifier.get(e)?.resolved??void 0}function bt(e){return e.defs.some((e=>"ImportBinding"===e.type))}function wt(e,t){return t.moduleScope.set.get(e)}function vt(e){return e.scopes.find((e=>"module"===e.type))??e.globalScope}function $t(e,t,n){const o={scopeAnalysis:t,unsupportedAliases:kt(e,t)},r=[];return mt(e,o,{CallExpression(e,{state:t}){(function(e,t,n){const o=e.callee;if("Identifier"===o.type){if(It(o,t.unsupportedAliases,t.scopeAnalysis))throw jt(n,"action-catalog call aliases");if(It(o,t.scopeAnalysis.actionFunctions,t.scopeAnalysis)){if(e.optional)throw jt(n,"optional action-catalog calls");return!0}return!1}if("MemberExpression"!==o.type)return!1;if(!xt(o,t.scopeAnalysis))return!1;if(e.optional||St(o))throw jt(n,"optional or computed action-catalog namespace calls");return!0})(e,t,n)&&r.push(e)}}),r}function kt(e,t){const n=new Set;return mt(e,t,{VariableDeclarator(e,{state:t}){for(const o of function(e,t){if("Identifier"===e.id.type&&"Identifier"===e.init?.type&&It(e.init,t.actionFunctions,t))return At(e,t,[e.id.name]);if("Identifier"===e.id.type&&"MemberExpression"===e.init?.type&&xt(e.init,t))return At(e,t,[e.id.name]);if("ObjectPattern"!==e.id.type||"Identifier"!==e.init?.type||!It(e.init,t.actionNamespaces,t))return[];const n=e.id.properties.flatMap((e=>"RestElement"===e.type||e.computed?[]:Pt(e.value))).map((e=>e.name));return At(e,t,n)}(e,t))n.add(o)},AssignmentExpression(e,{state:t}){for(const o of function(e,t){if("Identifier"===e.left.type&&"Identifier"===e.right.type&&It(e.right,t.actionFunctions,t))return Dt([e.left],t);if("Identifier"===e.left.type&&"MemberExpression"===e.right.type&&xt(e.right,t))return Dt([e.left],t);if("ObjectPattern"!==e.left.type||"Identifier"!==e.right.type||!It(e.right,t.actionNamespaces,t))return[];const n=e.left.properties.flatMap((e=>"RestElement"===e.type||e.computed?[]:Pt(e.value)));return Dt(n,t)}(e,t))n.add(o)}}),n}function xt(e,t){const n=Et(e);return!!n&&It(n,t.actionNamespaces,t)}function Et(e){return"Identifier"===e.object.type?e.object:"MemberExpression"===e.object.type?Et(e.object):void 0}function St(e){return!(!e.optional&&!e.computed)||"MemberExpression"===e.object.type&&St(e.object)}function It(e,t,n){return function(e,t,n){const o=yt(e,n);return!!o&&t.has(o)}(e,t,n.moduleScope)}function Dt(e,t){return e.flatMap((e=>{const n=yt(e,t.moduleScope);return n?[n]:[]}))}function At(e,t,n){const o=new Set(n);return t.moduleScope.scopeManager.getDeclaredVariables(e).filter((e=>o.has(e.name)))}function Pt(e){switch(e.type){case"Identifier":return[e];case"ObjectPattern":return e.properties.flatMap((e=>"RestElement"===e.type?Pt(e.argument):Pt(e.value)));case"ArrayPattern":return e.elements.flatMap((e=>e?Pt(e):[]));case"RestElement":return Pt(e.argument);case"AssignmentPattern":return Pt(e.left);case"MemberExpression":return[]}}function jt(e,t){return new Error(`Unsupported action-catalog call in ${e}: ${t} could hide a connectionId.`)}const Mt="@datadog/action-catalog";function Tt(e,t,n){const o=e.get(t);if(!o)return zt(t,[],n.name);const r=yt(n,o.scopeAnalysis);return r?function(e,t){return t.defs.some((t=>t.name===e))}(n,r)?Lt(t,[],n.name):Nt({modules:e,visitedExports:new Set},t,r,[]):Lt(t,[],n.name)}function Ct(e,t,n,o){const r=e.modules.get(t);if(!r)return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-module-record",requestKind:"export",exportName:n,message:`Module '${e}' was not collected while resolving export '${n}'.`,hops:t}}(t,o,n);if("default"===n)return _t(t,o,n);const i=`${t}\0${n}`;if(e.visitedExports.has(i))return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"cycle",exportName:n,message:`Resolving export '${n}' from module '${e}' would cycle through the module graph.`,hops:t}}(t,o,n);e.visitedExports.add(i);try{const t=r.exportsByName.get(n);return t?function(e,t,n,o,r){if("unsupported"===o.kind)return function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"unsupported-export",exportName:n,exportReason:o,message:`Export '${n}' from module '${e}' is unsupported: ${o}.`,hops:t}}(t.id,r,n,o.reason);if("re-export"===o.kind)return"default"===o.importedName?_t(t.id,r,n):Ct(e,o.resolvedId,o.importedName,[...r,{kind:"re-export",moduleId:t.id,exportName:n,sourceModuleId:o.resolvedId,sourceExportName:o.importedName}]);return Nt(e,t.id,o.variable,[...r,{kind:"local-export",moduleId:t.id,exportName:n,localName:o.variable.name}])}(e,r,n,t,o):function(e,t,n,o){let r;for(const i of t.starExports){const s=Ct(e,i.resolvedId,n,[...o,{kind:"star-export",moduleId:t.id,exportName:n,sourceModuleId:i.resolvedId}]);if("unsupported"===s.kind){if("missing-export"===s.reason)continue;return s}if(!r||!Ot(r,s)){if(r)return Rt(t.id,o,n);r=s}}return r??function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-export",exportName:n,message:`Module '${e}' does not expose export '${n}'.`,hops:t}}(t.id,o,n)}(e,r,n,o)}finally{e.visitedExports.delete(i)}}function Ot(e,t){return e.moduleId===t.moduleId&&e.variable===t.variable}function Nt(e,t,n,o){const r=e.modules.get(t);if(!r)return zt(t,o,n.name);const i=r.importsByVariable.get(n);if(i)return function(e,t,n,o,r){if("default"===o.kind)return Ft(t,r,n);if("namespace"===o.kind)return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"namespace-import",variableName:n,message:`Variable '${n}' in module '${e}' is an unsupported namespace import.`,hops:t}}(t,r,n);if("default"===o.importedName)return Ft(t,r,n);return Ct(e,o.resolvedId,o.importedName,[...r,{kind:"import",moduleId:t,localName:n,exportName:o.importedName,sourceModuleId:o.resolvedId}])}(e,r.id,n.name,i,o);const s=r.topLevelBindingsByVariable.get(n);return s?"const"===s.kind?{kind:"local",moduleId:r.id,variable:n,binding:s,hops:o}:"mutable"===s.kind?function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"mutable-binding",variableName:n,declarationKind:o,message:`Variable '${n}' in module '${e}' is declared with mutable '${o}'.`,hops:t}}(r.id,o,n.name,s.declarationKind):function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"unsupported-binding",variableName:n,bindingReason:o,message:`Variable '${n}' in module '${e}' has unsupported binding: ${o}.`,hops:t}}(r.id,o,n.name,s.reason):function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-static-binding",variableName:n,message:`Variable '${n}' in module '${e}' does not have a recorded top-level static binding.`,hops:t}}(r.id,o,n.name)}function Rt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"ambiguous-star-export",exportName:n,message:`Module '${e}' exposes ambiguous star exports for '${n}'.`,hops:t}}function _t(e,t,n){return{kind:"unsupported",moduleId:e,reason:"default-export",exportName:n,message:`Export '${n}' from module '${e}' resolves through an unsupported default export.`,hops:t}}function Ft(e,t,n){return{kind:"unsupported",moduleId:e,reason:"default-import",variableName:n,message:`Variable '${n}' in module '${e}' is an unsupported default import.`,hops:t}}function zt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-module-record",requestKind:"variable",variableName:n,message:`Module '${e}' was not collected while resolving variable '${n}'.`,hops:t}}function Lt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"unresolved-identifier",variableName:n,message:`Identifier '${n}' in module '${e}' is not a resolvable reference.`,hops:t}}function Ut(e,t,n){const o=Zt(n);switch(o.type){case"Literal":return function(e,t){if("string"==typeof t.value)return{kind:"resolved",moduleId:e,value:t.value};return function(e,t){return{kind:"unsupported",moduleId:e,reason:"non-string-literal",valueType:t,message:`Literal value type '${t}' in module '${e}' is not a string.`}}(e,typeof t.value)}(t,o);case"TemplateLiteral":return function(e,t){if(t.expressions.length>0)return function(e){return{kind:"unsupported",moduleId:e,reason:"dynamic-template-literal",message:`Dynamic template literals in module '${e}' cannot be resolved to static strings.`}}(e);return{kind:"resolved",moduleId:e,value:t.quasis.map((e=>e.value.cooked??e.value.raw)).join("")}}(t,o);case"Identifier":return function(e,t,n){const o=Tt(e.modules,t,n);if("unsupported"===o.kind)return un(o,n.name);if(!o.binding.expression)return cn(o.moduleId,o.variable.name);if(e.seenVariables.has(o.variable))return nn(o.moduleId,o.variable.name);e.seenVariables.add(o.variable);try{return Ut(e,o.moduleId,o.binding.expression)}finally{e.seenVariables.delete(o.variable)}}(e,t,o);case"MemberExpression":return function(e,t,n){const o=Bt(e,t,n);if("unsupported"===o.kind)return o;return Ut(e,o.moduleId,o.expression)}(e,t,o);default:return function(e,t){return{kind:"unsupported",moduleId:e,reason:"unsupported-expression",expressionType:t,message:`Expression type '${t}' in module '${e}' cannot be resolved to a static string.`}}(t,o.type)}}function Bt(e,t,n){if(n.optional)return function(e){return{kind:"unsupported",moduleId:e,reason:"optional-member-expression",message:`Optional member expressions in module '${e}' cannot be resolved to static strings.`}}(t);if(n.computed)return function(e){return{kind:"unsupported",moduleId:e,reason:"computed-member-expression",message:`Computed member expressions in module '${e}' cannot be resolved to static strings.`}}(t);if("Identifier"!==n.property.type)return function(e,t){return{kind:"unsupported",moduleId:e,reason:"non-static-member-property",propertyType:t,message:`Member property type '${t}' in module '${e}' is not statically named.`}}(t,n.property.type);const o=qt(e,t,n.object);return"unsupported"===o.kind?o:function(e,t,n){let o;for(const r of t.properties){if("SpreadElement"===r.type)return an(e);if(r.computed)return tn(e);if(Qt(r)===n){if(o)return on(e,n);if("init"!==r.kind)return en(e,n);if(!Vt(r))return sn(e,n,r.value.type);o=r}}if(!o)return function(e,t){return{kind:"unsupported",moduleId:e,reason:"missing-object-property",propertyName:t,message:`Static object in module '${e}' does not have property '${t}'.`}}(e,n);return{kind:"resolved",moduleId:e,expression:o.value}}(o.moduleId,o.expression,n.property.name)}function qt(e,t,n){if("Super"===n.type)return rn(t,n.type);const o=Zt(n);if("ObjectExpression"===o.type)return{kind:"resolved",moduleId:t,expression:o};if("MemberExpression"===o.type){const n=Bt(e,t,o);return"unsupported"===n.kind?n:qt(e,n.moduleId,n.expression)}if("Identifier"!==o.type)return rn(t,o.type);const r=Tt(e.modules,t,o);if("unsupported"===r.kind)return un(r,o.name);if(!r.binding.expression)return cn(r.moduleId,r.variable.name);if(e.mutatedImportedObjectVariables.has(r.variable))return function(e,t){return{kind:"unsupported",moduleId:e,reason:"imported-object-mutation",variableName:t,message:`Imported object '${t}' from module '${e}' is mutated in the module graph.`}}(r.moduleId,r.variable.name);if(e.seenVariables.has(r.variable))return nn(r.moduleId,r.variable.name);e.seenVariables.add(r.variable);try{return qt(e,r.moduleId,r.binding.expression)}finally{e.seenVariables.delete(r.variable)}}function Vt(e){const{value:t}=e;return"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&"RestElement"!==t.type&&"AssignmentPattern"!==t.type}function Kt(e){const t=new Set;for(const n of e.values())mt(n.ast,{modules:e,mutatedVariables:t,record:n},{AssignmentExpression(e,{state:t}){Wt(e.left,t)},UpdateExpression(e,{state:t}){Wt(e.argument,t)},UnaryExpression(e,{state:t}){"delete"===e.operator&&Wt(e.argument,t)},ForInStatement(e,{state:t}){Ht(e.left,t)},ForOfStatement(e,{state:t}){Ht(e.left,t)}});return t}function Ht(e,t){"VariableDeclaration"!==e.type&&Wt(e,t)}function Wt(e,t){if("Identifier"!==e.type)if("MemberExpression"!==e.type)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"RestElement"!==e.type?"AssignmentPattern"===e.type&&Wt(e.left,t):Wt(e.argument,t);else for(const n of e.elements)n&&Wt(n,t);else for(const n of e.properties)Wt("RestElement"===n.type?n.argument:n.value,t);else{const n=Yt(e);n&&Jt(n,t)}else Jt(e,t)}function Jt(e,t){const n=Gt(t,e,new Set);n&&t.mutatedVariables.add(n)}function Gt(e,t,n){const o=yt(t,e.record.scopeAnalysis);if(!o||n.has(o))return;if(n.add(o),bt(o)){const n=Tt(e.modules,e.record.id,t);return"local"===n.kind?n.variable:void 0}const r=function(e){for(const t of e.defs){const e=t.node;if("VariableDeclarator"===e.type&&e.init)return e.init}return}(o);if(!r)return;const i=function(e){const t=Zt(e);if("Identifier"===t.type)return t;if("MemberExpression"===t.type)return Yt(t);return}(r);return i?Gt(e,i,n):void 0}function Yt(e){return"Identifier"===e.type?e:"MemberExpression"===e.type?Yt(e.object):void 0}function Qt(e){return"Identifier"===e.key.type?e.key.name:"Literal"===e.key.type&&"string"==typeof e.key.value?e.key.value:void 0}function Zt(e){let t=e;for(;Xt(t);)t=t.expression;return t}function Xt(e){const t=e.type;return("TSAsExpression"===t||"TSSatisfiesExpression"===t||"TSNonNullExpression"===t||"TSTypeAssertion"===t)&&!!e.expression}function en(e,t){return{kind:"unsupported",moduleId:e,reason:"accessor-object-property",propertyName:t,message:`Static object property '${t}' in module '${e}' is an accessor.`}}function tn(e){return{kind:"unsupported",moduleId:e,reason:"computed-object-property",message:`Computed object properties in module '${e}' cannot be resolved to static strings.`}}function nn(e,t){return{kind:"unsupported",moduleId:e,reason:"cycle",variableName:t,message:`Resolving variable '${t}' in module '${e}' would cycle through static string values.`}}function on(e,t){return{kind:"unsupported",moduleId:e,reason:"duplicate-object-property",propertyName:t,message:`Static object in module '${e}' has duplicate property '${t}'.`}}function rn(e,t){return{kind:"unsupported",moduleId:e,reason:"non-object-member-value",expressionType:t,message:`Expression type '${t}' in module '${e}' is not a static object value.`}}function sn(e,t,n){return{kind:"unsupported",moduleId:e,reason:"unsupported-object-property-value",propertyName:t,valueType:n,message:`Static object property '${t}' in module '${e}' has unsupported value type '${n}'.`}}function an(e){return{kind:"unsupported",moduleId:e,reason:"object-spread",message:`Object spreads in module '${e}' cannot be resolved to static strings.`}}function un(e,t){return{kind:"unsupported",moduleId:e.moduleId,reason:"static-definition-unsupported",variableName:t,definition:e,message:`Variable '${t}' could not be resolved to a static definition: ${e.message}`}}function cn(e,t){return{kind:"unsupported",moduleId:e,reason:"uninitialized-const",variableName:t,message:`Const variable '${t}' in module '${e}' does not have an initializer.`}}const dn=new Set(["node_modules",".yarn"]);function ln(e,t,n,o=[]){if(!Pn(e,t))return null;const r=ot(n,e),i=gt(r),s=function(e,t){const n=function(e){return e.body.flatMap((e=>("ImportDeclaration"===e.type||"ExportNamedDeclaration"===e.type||"ExportAllDeclaration"===e.type)&&e.source&&rt(e.source)?[e.source.value]:[]))}(e);return t.map(((e,t)=>({source:n[t]??e,resolvedId:e})))}(r,o);return{id:e,ast:r,scopeAnalysis:i,staticDependencies:s,unsupportedDependencies:Dn(r),importsByVariable:pn(r,i,s),exportsByName:fn(r,i,s),starExports:gn(r,s),topLevelBindingsByVariable:yn(r,i)}}function pn(e,t,n){const o=new Map;for(const r of e.body){if("ImportDeclaration"!==r.type||!rt(r.source))continue;const e=In(n,r.source.value);for(const n of r.specifiers){const[r]=t.scopeManager.getDeclaredVariables(n);r&&("ImportSpecifier"!==n.type?o.set(r,{kind:"ImportDefaultSpecifier"===n.type?"default":"namespace",resolvedId:e}):o.set(r,{kind:"named",importedName:En(n.imported),resolvedId:e}))}}return o}function fn(e,t,n){const o=new Map;for(const r of e.body)"ExportNamedDeclaration"!==r.type?"ExportDefaultDeclaration"!==r.type?"ExportAllDeclaration"===r.type&&hn(r,n,o):o.set("default",{kind:"unsupported",reason:"default export"}):mn(r,t,n,o);return o}function mn(e,t,n,o){if(e.declaration)!function(e,t,n){if(!e)return;if("VariableDeclaration"===e.type){for(const o of e.declarations){const e=t.scopeManager.getDeclaredVariables(o);if("Identifier"!==o.id.type){for(const t of e)n.set(t.name,{kind:"unsupported",reason:"binding pattern export"});continue}const[r]=e;r&&n.set(o.id.name,{kind:"local",variable:r})}return}if(("FunctionDeclaration"===e.type||"ClassDeclaration"===e.type)&&e.id){const[o]=t.scopeManager.getDeclaredVariables(e);o&&n.set(e.id.name,{kind:"local",variable:o})}}(e.declaration,t,o);else if(e.source&&rt(e.source)){const t=In(n,e.source.value);for(const n of e.specifiers){if("ExportSpecifier"!==n.type)continue;const e=En(n.exported);"default"!==e?o.set(e,{kind:"re-export",importedName:En(n.local),resolvedId:t}):o.set(e,{kind:"unsupported",reason:"default re-export",resolvedId:t})}}else for(const n of e.specifiers){if("ExportSpecifier"!==n.type)continue;const e=En(n.exported);if("default"===e){o.set(e,{kind:"unsupported",reason:"default export"});continue}const r=wt(En(n.local),t);o.set(e,r?{kind:"local",variable:r}:{kind:"unsupported",reason:"unresolved local export"})}}function hn(e,t,n){const o=Sn(e);o&&rt(e.source)&&n.set(o,{kind:"unsupported",reason:"namespace re-export",resolvedId:In(t,e.source.value)})}function gn(e,t){return e.body.flatMap((e=>"ExportAllDeclaration"!==e.type||Sn(e)||!rt(e.source)?[]:[{resolvedId:In(t,e.source.value)}]))}function yn(e,t){const n=new Map;for(const o of e.body)bn(o,t,n);return function(e,t,n){mt(e,{scopeAnalysis:t,bindings:n},{AssignmentExpression(e,{state:t}){$n(e.left,t.scopeAnalysis,t.bindings)},UpdateExpression(e,{state:t}){$n(e.argument,t.scopeAnalysis,t.bindings)},UnaryExpression(e,{state:t}){"delete"===e.operator&&$n(e.argument,t.scopeAnalysis,t.bindings)},ForInStatement(e,{state:t}){vn(e.left,t.scopeAnalysis,t.bindings)},ForOfStatement(e,{state:t}){vn(e.left,t.scopeAnalysis,t.bindings)}})}(e,t,n),n}function bn(e,t,n){if("VariableDeclaration"===e.type)return void wn(e,t,n);if("ExportNamedDeclaration"===e.type&&"VariableDeclaration"===e.declaration?.type)return void wn(e.declaration,t,n);const o="ExportNamedDeclaration"===e.type||"ExportDefaultDeclaration"===e.type?e.declaration:e;if(o&&("FunctionDeclaration"===o.type||"ClassDeclaration"===o.type)&&o.id){const[e]=t.scopeManager.getDeclaredVariables(o);e&&n.set(e,{kind:"unsupported",reason:`${o.type} binding`})}}function wn(e,t,n){for(const o of e.declarations){const r=t.scopeManager.getDeclaredVariables(o);if("Identifier"!==o.id.type){for(const e of r)n.set(e,{kind:"unsupported",reason:"binding pattern"});continue}const[i]=r;i&&("const"===e.kind?n.set(i,{kind:"const",expression:o.init??null}):n.set(i,{kind:"mutable",declarationKind:e.kind}))}}function vn(e,t,n){"VariableDeclaration"!==e.type&&$n(e,t,n)}function $n(e,t,n){if("Identifier"!==e.type)if("MemberExpression"!==e.type)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"RestElement"!==e.type?"AssignmentPattern"===e.type&&$n(e.left,t,n):$n(e.argument,t,n);else for(const o of e.elements)o&&$n(o,t,n);else for(const o of e.properties)$n("RestElement"===o.type?o.argument:o.value,t,n);else{const o=xn(e);o&&kn(o,t,n,"mutated object binding")}else kn(e,t,n,"reassigned binding")}function kn(e,t,n,o){const r=yt(e,t);if(!r||bt(r)||!n.has(r))return;const i=n.get(r);"mutable"!==i?.kind&&n.set(r,{kind:"unsupported",reason:o})}function xn(e){return"Identifier"===e.type?e:"MemberExpression"===e.type?xn(e.object):void 0}function En(e){return"Identifier"===e.type?e.name:String(e.value)}function Sn(e){const t=e.exported;return t?En(t):void 0}function In(e,t){return e.find((e=>e.source===t))?.resolvedId??t}function Dn(e){const t=[];return mt(e,t,{ImportExpression(e,{state:t}){const n=function(e){return Mn(e.source,"non-literal dynamic import")}(e);An(n)&&t.push({specifier:n,kind:"dynamic-import"})},CallExpression(e,{state:t}){if(function(e){return"Import"===e.callee.type}(e)){const n=function(e){return Mn(e.arguments[0],"non-literal dynamic import")}(e);An(n)&&t.push({specifier:n,kind:"dynamic-import"})}else(function(e){if("Identifier"!==e.callee.type||"require"!==e.callee.name)return!1;const[t]=e.arguments;return!t||!rt(t)||Tn(t.value)})(e)&&t.push({specifier:jn(e),kind:"require"})}}),t}function An(e){return"non-literal dynamic import"===e||Tn(e)}function Pn(e,t){if(!ke.some((t=>e.endsWith(t))))return!1;const n=u.relative(u.resolve(t),e);return!n.startsWith("..")&&!u.isAbsolute(n)&&!n.split(u.sep).some((e=>dn.has(e)))}function jn(e){return Mn(e.arguments[0],"local require")}function Mn(e,t){return rt(e)?e.value:t}function Tn(e){return e.startsWith(".")||e.startsWith("/")}function Cn(e,t){return new Error(`Unsupported local module graph for ${e}: ${t} could hide an action-catalog connectionId.`)}function On(e,t,n){const o=new Set;return function(e,t,n,o){const r=[e],i=new Set;for(;r.length>0;){const s=r.shift();if(i.has(s))continue;i.add(s);const a=t.get(s);if(!a)throw Cn(e,`missing module record for ${s}`);o({entryId:e,moduleId:s,record:a});for(const t of a.unsupportedDependencies)throw Cn(e,`${t.kind} ${t.specifier}`);for(const o of a.staticDependencies){const i=o.resolvedId;if(Pn(i,n)){if(!t.has(i))throw Cn(e,`uncollected local import ${i} from ${a.id}`);r.push(i)}}}}(e,t,n,(({record:e})=>{const n=function(e){const t=new Set,n=new Set;for(const r of e.body)if("ImportDeclaration"===r.type&&"string"==typeof(o=r.source.value)&&(o===Mt||o.startsWith(`${Mt}/`))&&!it(r))for(const e of r.specifiers)it(e)||("ImportNamespaceSpecifier"===e.type?n.add(e.local.name):t.add(e.local.name));var o;return{functions:t,namespaces:n}}(e.ast),r=function(e,t){const n=new Set,o=new Set;for(const r of e.scopeManager.scopes)for(const e of r.variables)bt(e)&&(t.functions.has(e.name)&&n.add(e),t.namespaces.has(e.name)&&o.add(e));return{moduleScope:e,actionFunctions:n,actionNamespaces:o}}(e.scopeAnalysis,n);for(const n of $t(e.ast,r,e.id)){const r=Nn(n,t,e);r&&o.add(r)}})),[...o].sort()}function Nn(e,t,n){const[o]=e.arguments;if(!o||"ObjectExpression"!==o.type)throw Fn(n.id,"non-object action-catalog call arguments");const r=function(e,t){let n;for(const o of e.properties){if("SpreadElement"===o.type)throw Fn(t,"spread object arguments");if(o.computed)throw Fn(t,"computed object property keys");if(_n(o)){if(n)throw Fn(t,"multiple connectionId properties");if("init"!==o.kind)throw Fn(t,"accessor connectionId properties");if(!Rn(o))throw Fn(t,"destructuring pattern in connectionId value");n=o}}return n}(o,n.id);if(!r)return;const i=function(e,t,n){return Ut({modules:e,mutatedImportedObjectVariables:Kt(e),seenVariables:new Set},t,n)}(t,n.id,r.value);if("resolved"===i.kind)return i.value;throw s=n.id,a=`static string resolution ${function(e){return"static-definition-unsupported"===e.reason?`${e.reason}/${e.definition.reason}`:e.reason}(i)}: ${i.message}`,new Error(`Unsupported action-catalog connectionId in ${s}: ${a}.`);var s,a}function Rn(e){const{value:t}=e;return"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&"RestElement"!==t.type&&"AssignmentPattern"!==t.type}function _n(e){return"connectionId"===function(e){if("Identifier"===e.key.type)return e.key.name;if("Literal"===e.key.type&&"string"==typeof e.key.value)return e.key.value;return}(e)}function Fn(e,t){return new Error(`Unsupported action-catalog call in ${e}: ${t} could hide a connectionId.`)}const zn=/^(?:\0|virtual:)/;function Ln(e){const t=new Map;return{plugin:{name:"dd-backend-module-graph-collector",moduleParsed(n){const o=Un(n.id);if(r=o,zn.test(r))return;var r;const i=ln(o,e,n.ast,function(e){return e.importedIdResolutions?.map((({id:e})=>e))??[...e.importedIds]}(n).map(Un));i&&t.set(i.id,i)}},getModuleRecords:()=>t}}function Un(e){return e.split("?")[0]}function Bn(e,t){const n=Ln(t);return{plugin:n.plugin,getAllowedConnectionIds:()=>On(e,n.getModuleRecords(),t)}}function qn(e,t){return{name:e,enforce:"pre",resolveId:e=>t[e]?{id:e,moduleSideEffects:!0}:null,load:e=>t[e]?t[e]:null}}function Vn(e,t,n=[]){return{configFile:!1,root:e,logLevel:"silent",build:{minify:!1,target:"esnext",rollupOptions:{output:{format:"es",exports:"named",inlineDynamicImports:!0},preserveEntrySignatures:"exports-only",treeshake:!1,onwarn(e,t){"MODULE_LEVEL_DIRECTIVE"!==e.code&&t(e)}}},resolve:{extensions:[...ke,".json"]},plugins:[qn("dd-backend-resolve",t),...n]}}function Kn(e){return`${e.relativePath}/${e.name}`}async function Hn(e,t,n,o){const r=Kn(t),i=`virtual:dd-backend-dev:${r}`,s=function(e,t,n){return ft(e,t,n??process.cwd())}(t.name,t.absolutePath,n),a=Bn(t.absolutePath,n);o.debug(`Bundling backend function "${r}" from ${t.absolutePath}`);const u=Vn(n,{[i]:s},[a.plugin]),c=await e({...u,build:{...u.build,write:!1,rollupOptions:{...u.build.rollupOptions,input:i,output:u.build.rollupOptions.output}}}),d=Array.isArray(c)?c[0]:c;if(!("output"in d))throw new Error(`Unexpected vite.build result for "${r}"`);const l="chunk"===d.output[0].type?d.output[0].code:"",p={...t,allowedConnectionIds:a.getAllowedConnectionIds()};return o.debug(`Bundled "${r}" (${l.length} bytes)`),{func:p,code:l}}async function Wn(e,t,n,o,r,i){const s=`https://api.${o.site}/api/v2/app-builder/queries/preview-async`,a=Kn(t);i.debug(`Calling Datadog API: ${s}`);const u=JSON.stringify({data:{type:"queries",attributes:{query:{id:f(),name:a,type:"action",properties:{spec:{fqn:"com.datadoghq.datatransformation.jsFunctionWithActions",inputs:{script:e,allowedConnectionIds:t.allowedConnectionIds,context:{backendFunctionArgs:n}}},onlyTriggerManually:!0}},template_params:{}}}}),c=await r({url:s,method:"POST",type:"json",getData:()=>({data:u,headers:{"Content-Type":"application/json"}})}),d=c.data?.id;if(!d)throw new Error("No receipt ID returned from Datadog API");return i.debug(`Query execution started with receipt: ${d}`),async function(e,t,n,o){const r=`https://api.${t.site}/api/v2/app-builder/queries/execution-long-polling/${e}`,i=10;for(let e=0;e<i;e++){o.debug(`Long-poll attempt ${e+1}/${i}...`);const t=await n({url:r,type:"json"});if(t.errors?.length){const e=t.errors.map((e=>e.detail||e.title)).join("; ");throw new Error(`Query execution failed: ${e}`)}const s=t.data?.attributes;if(o.debug(`Long-poll response, done: ${s?.done}`),s?.done){if(!s.outputs)throw new Error("Query execution completed without outputs");return s.outputs}}throw new Error("Query execution timed out")}(d,o,r,i)}function Jn(e,t,n){e.statusCode=t,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify({success:!1,error:n}))}class Gn extends Error{constructor(e,t){super(t),this.statusCode=e}}async function Yn(e,t,n){const{functionName:o,args:r=[]}=await function(e){return new Promise(((t,n)=>{let o="";e.on("data",(e=>{o+=e.toString()})),e.on("end",(()=>{try{t(JSON.parse(o))}catch{n(new Error("Invalid JSON body"))}})),e.on("error",n)}))}(e);if(!o||"string"!=typeof o)throw new Gn(400,"Missing or invalid functionName");const i=t.get(o);if(!i)throw new Gn(404,`Backend function "${o}" not found`);return{...await n(i),args:r}}function Qn(e,t,n,o,r,i){const s=t=>Hn(e,t,r,i),a=t();return a.length>0&&i.info(`Dev server middleware active for ${a.length} backend function(s): ${a.map((e=>e.name)).join(", ")}`),o||i.warn(`Auth credentials not configured. The /__dd/executeAction endpoint will be unavailable. ${et}`),(e,r,a)=>{if("POST"!==e.method)return void a();const u=(c=t(),new Map(c.map((e=>[lt(e),e]))));var c;if("/__dd/debugBundle"===e.url)(async function(e,t,n,o){try{const{code:r}=await Yn(e,n,o);t.statusCode=200,t.setHeader("Content-Type","text/plain"),t.end(r)}catch(e){Jn(t,e instanceof Gn?e.statusCode:500,e instanceof Error?e.message:"Internal server error")}})(e,r,u,s).catch((()=>{Jn(r,500,"Unexpected error")}));else if("/__dd/executeAction"===e.url){if(!o)return void Jn(r,400,`Auth credentials not configured. ${et}`);(async function(e,t,n,o,r,i,s){try{const{func:a,code:u,args:c}=await Yn(e,n,o),d=Kn(a);s.debug(`Executing action: ${d} with args`);const l=await Wn(u,a,c,r,i,s);t.statusCode=200,t.setHeader("Content-Type","application/json"),t.end(JSON.stringify({success:!0,result:l}))}catch(e){const n=e instanceof Gn?e.statusCode:500,o=e instanceof Error?e.message:"Internal server error";s.debug(`Error handling executeAction: ${o}`),Jn(t,n,o)}})(e,r,u,s,n,o,i).catch((()=>{Jn(r,500,"Unexpected error")}))}else a()}}const Zn=async(e,t)=>{const n=(await Promise.all(e.map((e=>w(e,{absolute:!0,cwd:t,nodir:!0}))))).flat(),o=Array.from(new Set(n)).map((e=>u.relative(t,e))),r=(e=>{if(0===e.length)return"";const t=e[0].split(u.sep);let n="";for(let o=0;o<t.length-1;o++){const r=t.slice(0,o+1).join(u.sep);if(!e.every((e=>e.startsWith(`${r}${u.sep}`))))break;n=r}return n})(o);return o.map(((e,t)=>{const o=r?e.slice(r.length+1):e;return{absolutePath:n[t],relativePath:o.split(u.sep).join("/")}}))},Xn=(e,t)=>X(t)?O:t.startsWith(e)||u.isAbsolute(t)?t:u.resolve(e,t),eo=(e,t)=>{let n,o=Xn(process.cwd(),e);for(;!n;){const e=u.resolve(o,t);if(Pe(e)&&(n=e),o=o.split(u.sep).slice(0,-1).join(u.sep),[u.sep,""].includes(o))break}return n},to=(e,t)=>{const n=[...e].map((e=>Xn(t||process.cwd(),e).split(u.sep))),o=n.length?Math.min(...n.map((e=>e.length))):0,r=[];for(let e=0;e<o;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;r.push(t)}return r.length>0&&r.join(u.sep)||u.sep},no=t.bold.red,oo=t.bold.yellow,ro=e=>{const t=eo(e,"package.json");if(t)try{const e=Ae(t);return JSON.parse(e)}catch(e){return}},io=(e,t,n)=>{if(n?.name&&n?.identifier)return{identifier:n?.identifier,name:n.name};const o=ro(e);o||t.warn(oo("No package.json found to infer the app name."));const r=n?.name||o?.name?.trim();r||t.error(no("Unable to determine the app name to compute the app identifier."));const i=((e,t)=>{const n=e||(e=>{if(e&&e.repository)return"string"==typeof e.repository?e.repository:"url"in e.repository?e.repository.url:void 0})(t);if(!n)return;const o=re(n.trim());return o?o.replace(/\.git$/,""):void 0})(n?.url,o);i||t.error(no("Unable to determine the git remote to compute the app identifier."));const s=n?.identifier||((e,t)=>{if(!e||!t)return;const n=`${e}:${t}`;return p("sha256").update(n).digest("hex").slice(0,32)})(i,r);return s&&r||t.error(no("Unable to compute the app identifier.")),{identifier:s,name:r}},so=t.green.bold,ao=t.yellow.bold,uo=t.cyan.bold,co=t.bold,lo=(e,t={},n)=>async()=>{const o=await je(e,{contentType:"application/zip",filename:ve});return J({getForm:()=>{const e=new FormData;e.append("name",n),e.append("bundle",o,ve);const t=q("APPS_VERSION_NAME")?.trim();return t&&e.append("version",t),e},defaultHeaders:t,zip:!1})},po=async(e,t,n)=>{const o=[],r=[],i=t.doAuthenticatedRequest;if(!t.identifier)return o.push(new Error("No app identifier provided")),{errors:o,warnings:r};const s=(a=t.site,u=t.identifier,q("APPS_INTAKE_URL")||`https://api.${a}/${we}/${u}/upload`);var a,u;const d=W({bundler:t.bundlerName,plugin:"apps",version:t.version}),l=se({identifier:t.identifier,intakeUrl:s,defaultHeaders:`\n${JSON.stringify(d,null,2)}`}),p=`an archive of:\n - ${so(e.assets.length.toString())} files\n - ${so(v(e.size))}\n\nWith the configuration:\n${l}`;if(t.dryRun)return n.error(`\n${uo("Dry run enabled")}\n\nSkipping assets upload.\nWould have uploaded ${p}`),{errors:o,warnings:r};try{const o=await i({url:s,method:"POST",type:"json",getData:lo(e.archivePath,d,t.name),onRetry:(e,t)=>{const o=`Failed to upload archive (attempt ${ao(`${t}/5`)}): ${e.message}`;r.push(o),n.warn(o)}});if(n.debug(`Uploaded ${p}\n`),o.app_builder_id){const e=`https://app.${t.site}/app-builder/apps/${o.app_builder_id}`;n.info(`Your application is available at:\n ${uo(e)}`)}if(o.version_id){const e=((e,t)=>`https://api.${e}/${we}/${t}/release/live`)(t.site,t.identifier);await i({url:e,method:"PUT",type:"json",getData:async()=>({data:c.from(JSON.stringify({version_id:o.version_id})),headers:{"Content-Type":"application/json",...d}}),onRetry:(e,t)=>{const o=`Failed to release version (attempt ${ao(`${t}/5`)}): ${e.message}`;r.push(o),n.warn(o)}}),n.info(`Published uploaded version ${co(o.version_id)} to live.`)}}catch(e){const t=e instanceof Error?e:new Error(String(e));o.push(t)}return{errors:o,warnings:r}},fo=t.yellow.bold,mo=t.red.bold,ho="manifest.json";async function go(e){const t=await r.mkdtemp(u.join(h.tmpdir(),"dd-apps-manifest-")),n=u.join(t,ho);try{await r.writeFile(n,JSON.stringify(function(e){const t={};for(const n of e)t[lt(n)]={allowedConnectionIds:[...n.allowedConnectionIds]};return{backend:{functions:t}}}(e),null,2))}catch(e){throw await Se(t),e}return{manifestAsset:{absolutePath:n,relativePath:ho},cleanup:()=>Se(t)}}const yo=async({backendOutputs:e,backendFunctions:t,context:n,doAuthenticatedRequest:o,options:i})=>{const a=n.getLogger(be),{auth:c,buildRoot:d,bundler:{name:l,outDir:p},git:f,version:m}=n,g=a.time("handle assets");let y,w,v;try{const n=a.time("resolve identifier"),{name:g,identifier:v}=io(d,a,{url:f?.remote,name:i.name,identifier:i.identifier});if(!v||!g)throw new Error("Missing apps identification.\nEither:\n - pass an 'options.apps.identifier' and 'options.apps.name' to your plugin's configuration.\n - have a 'name' and a 'repository' in your 'package.json'.\n - have a valid remote url on your git project.\n");n.end();const $=u.relative(d,p),k=[...i.include,`${$}/**/*`],x=await Zn(k,d);if(!x.length)return void a.debug("No assets to upload.");const E=new Set(e.values()),S=x.filter((e=>!E.has(e.absolutePath))).map((e=>({...e,relativePath:`frontend/${e.relativePath}`})));for(const[t,n]of e)S.push({absolutePath:n,relativePath:`backend/${t}.js`});const{manifestAsset:I,cleanup:D}=await go(t);w=D,S.push(I);const A=a.time("archive assets"),P=await(async e=>{const t=await r.mkdtemp(u.join(h.tmpdir(),"dd-apps-")),n=u.join(t,ve),o=new b;for(const t of e)o.file(t.relativePath,s.createReadStream(t.absolutePath),{binary:!0,compression:"DEFLATE",compressionOptions:{level:9}});await new Promise(((e,t)=>{const r=s.createWriteStream(n),i=o.generateNodeStream({type:"nodebuffer",streamFiles:!0,compression:"DEFLATE",compressionOptions:{level:9}});i.on("error",t),r.on("error",t),r.on("close",e),i.pipe(r)}));const{size:i}=await r.stat(n);return{archivePath:n,size:i,assets:e}})(S);A.end(),y=u.dirname(P.archivePath);const j=a.time("upload assets"),{errors:M,warnings:T}=await po(P,{bundlerName:l,doAuthenticatedRequest:o,dryRun:i.dryRun,identifier:v,name:g,site:c.site,version:m},a);if(j.end(),T.length>0&&a.warn(`${fo("Warnings while uploading assets:")}\n - ${T.join("\n - ")}`),M.length>0){const e=M.map((e=>e.cause||e.stack||e.message||e)).join("\n - ");throw new Error(` - ${e}`)}}catch(e){v=e,a.error(`${mo("Failed to upload assets:")}\n${e?.message||e}`)}if(y&&await Se(y),w&&await w(),g.end(),v)throw v};const bo=u.join(T,"./apps-runtime.mjs"),wo=async()=>{throw new Error("Dry run should not perform authenticated requests.")},vo=({bundler:e,context:t,options:n})=>{const o=t.getLogger(be),{auth:r,buildRoot:s}=t;t.inject({type:"file",position:Te.MIDDLE,value:bo});const{setBackendFunctions:a,getBackendFunctions:c}=function(){const e=new Map;return{setBackendFunctions(t,n){e.set(t,n)},getBackendFunctions:()=>Array.from(e.values()).flat()}}();return{transform:{filter:{id:{include:[$e],exclude:[/node_modules/,/[/\\]dist[/\\]/]}},handler(e,t){const n=st(this.parse(e),t);if(0===n.length)return o.warn(`Backend file ${t} has no exported functions. Did you forget to add a named export?`),a(t,[]),{code:"",map:null};const{functions:r,proxyCode:i}=function(e,t,n){const o=u.relative(n,t).replace($e,""),r=[],i=[];for(const n of e){const e={relativePath:o,name:n,absolutePath:t,allowedConnectionIds:[]};r.push(e),i.push({exportName:n,queryName:lt(e)})}return{functions:r,proxyCode:pt(i)}}(n,t,s);return a(t,r),o.debug(`Generated proxy for ${t} with ${r.length} export(s)`),{code:i,map:null}}},async closeBundle(){let a,d=new Map,l=c();if(l.length>0){const t=await async function(e,t,n,o){const r=await i(u.join(g(),"dd-apps-backend-")),s=new Map,a=new Map;o.debug(`Building ${t.length} backend function(s) via vite.build()`);for(const i of t){const t=lt(i),c=`\0dd-backend:${t}`,d=ft(i.name,i.absolutePath,n),l=Bn(i.absolutePath,n),p=Vn(n,{[c]:d},[l.plugin]),f=await e({...p,build:{...p.build,write:!0,outDir:r,emptyOutDir:!1,rollupOptions:{...p.build.rollupOptions,input:{[t]:c},output:{...p.build.rollupOptions.output,entryFileNames:"[name].js"}}}}),m=Array.isArray(f)?f[0]:f;if("output"in m)for(const e of m.output){if("chunk"!==e.type||!e.isEntry)continue;const n=u.resolve(r,e.fileName);s.set(t,n),o.debug(`Backend function "${t}" output: ${n}`)}a.set(i.absolutePath,l.getAllowedConnectionIds())}return{outDir:r,outputs:s,functions:t.map((e=>({...e,allowedConnectionIds:a.get(e.absolutePath)})))}}(e.build,l,s,o);a=t.outDir,d=t.outputs,l=t.functions}try{const e=n.dryRun?wo:nt(n.authOverrides.method,r,o);await yo({backendOutputs:d,backendFunctions:l,context:t,doAuthenticatedRequest:e,options:n})}finally{a&&await Se(a)}},configureServer(t){let i;try{i=nt(n.authOverrides.method,r,o)}catch(e){if(!(e instanceof tt))throw e}t.middlewares.use(Qn(e.build,c,r,i,s,o))}}},$o=({options:e,context:t,bundler:n})=>{const o=t.getLogger(be),r=Ee(e);return"vite"!==t.bundler.name?(o.warn(`The apps plugin only supports Vite; skipping under '${t.bundler.name}'.`),[]):[{name:be,enforce:"post",vite:vo({bundler:n,context:t,options:r})}]},ko="errorTracking",xo="datadog-error-tracking-plugin",Eo=(e,n,o)=>{if(".map"!==u.extname(o))throw new Error(`The file ${t.green.bold(o)} is not a sourcemap.`);const r=o.replace(/\.map$/,""),i=u.relative(n,r),s=((e,t)=>{if(e.startsWith("/"))return u.join(e,t);try{const n=e.replace(/\/*$/,"/"),o=new URL(n),r=t.replace(/^[\\/]*/,"");return new URL(r,o).href}catch{return`${e}${t}`}})(e,i);return{minifiedFilePath:r,minifiedUrl:s,relativePath:i}},So=/[/]+|[\\]+/g,Io=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,Do=(e,t)=>{const n=e.replace(Io,"").split(So),o=t.replace(Io,"").split(So),r=n.join("/");let i="";for(let e=0;e<o.length;e+=1){const t=o.slice(-e).join("/");r.startsWith(t)&&(i=t)}return i},Ao=async(e,t,n,o)=>{const r=await(async(e,t)=>{const[n,o]=await Promise.all([Me(e.minifiedFilePath),Me(e.sourcemapFilePath)]);return{file:n,sourcemap:o,repeatedPrefix:Do(e.relativePath,t)}})(e,n),i=[],s=[],a=new Map([["event",{type:"string",options:{contentType:"application/json",filename:"event"},value:JSON.stringify({...t,minified_url:e.minifiedUrl})}],["source_map",{type:"file",path:e.sourcemapFilePath,options:{filename:"source_map",contentType:"application/json"}}],["minified_file",{type:"file",path:e.minifiedFilePath,options:{filename:"minified_file",contentType:"application/javascript"}}]]);if(o)try{a.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:o.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{s.push(`${u.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:o.hash,repository_url:o.remote}],version:1})})}catch(t){s.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return r.file.empty&&i.push(`Minified file is empty: ${e.minifiedFilePath}`),r.file.exists||i.push(`Minified file not found: ${e.minifiedFilePath}`),r.sourcemap.empty&&i.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),r.sourcemap.exists||i.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),r.repeatedPrefix&&s.push(`The minified file path contains a repeated pattern with the minified path prefix: ${r.repeatedPrefix}`),{content:a,errors:i,warnings:s}},Po=e=>{const t=e.message.match(/HTTP (\d{3})/);return t?`status_code:${t[1]}`:"status_code:unknown"},jo=e=>{const t=Po(e);return"status_code:unknown"!==t?`error_type:http_${t.replace("status_code:","")}`:`error_type:${ie(e.name||"unknown")}`},Mo=(e,t,n)=>{const o=((e,t)=>`${e}|${t.join("|")}`)(t,n),r=e.metrics.get(o);r?r.value++:e.metrics.set(o,{name:t,value:1,tags:n})},To=(e,t,n)=>{Mo(e,"retry",[...e.baseTags,`attempt:${n}`,Po(t),jo(t)])},Co=(e,t)=>{Mo(e,"failure",[...e.baseTags,Po(t),jo(t)])},Oo=(e,t)=>{if(!t.sendMetrics)return;if(!e.metrics.size)return;const n=(e=>{const t=Math.floor(Date.now()/1e3);return Array.from(e.metrics.values()).map((e=>({metric:`sourcemaps.upload.${e.name}`,type:"count",points:[[t,e.value]],tags:e.tags})))})(e);for(const e of n)t.addMetric(e)},No=t.green.bold,Ro=t.yellow.bold,_o=t.red.bold,Fo=(e,t={})=>async()=>J({getForm:async()=>{const t=new FormData;for(const[n,o]of e.content){const e="file"===o.type?await je(o.path,o.options):new Blob([o.value],{type:o.options.contentType});t.append(n,e,o.options.filename)}return t},defaultHeaders:t,zip:!0}),zo=async(e,t,n,o)=>{const r=[],i=[];if(!n.apiKey)return r.push({error:new Error("No authentication token provided")}),{errors:r,warnings:i};if(0===e.length)return i.push("No sourcemaps to upload"),{errors:r,warnings:i};const s=o.time("Queue uploads"),a=new($.default?$.default:$)({concurrency:t.maxConcurrency}),u=(c=n.site,q("SOURCEMAP_INTAKE_URL")||`https://sourcemap-intake.${c}/api/v2/srcmap`);var c;const d=W({bundler:n.bundlerName,plugin:"sourcemaps",version:n.version}),l=(e=>({metrics:new Map,baseTags:[`service:${e.service}`]}))(t),p=se({...t,intakeUrl:u,outDir:n.outDir,defaultHeaders:`\n${JSON.stringify(d,null,2)}`}),f=`\nUploading ${No(e.length.toString())} sourcemaps with configuration:\n${p}`;o.debug(f);const m=[];for(const s of e){const e={sourcemap:s.content.get("source_map")?.path.replace(n.outDir,"."),file:s.content.get("minified_file")?.path.replace(n.outDir,".")};m.push(a.add((async()=>{try{await Y({auth:{apiKey:n.apiKey},url:u,method:"POST",getData:Fo(s,d),onRetry:(t,n)=>{To(l,t,n);const r=`Failed to upload ${Ro(e.sourcemap)} | ${Ro(e.file)}:\n ${t.message}\nRetrying ${n}/5`;i.push(r),o.debug(r)}})}catch(n){if(Co(l,n),r.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}s.end(),o.debug(`Queued ${No(e.length.toString())} uploads.`);try{await Promise.all(m),await a.onIdle()}finally{Oo(l,n)}return{warnings:i,errors:r}},Lo=async(e,t,n)=>{const o=n.time("get sourcemaps files"),r=((e,t)=>{if(!t.outputs||0===t.outputs.length)throw new Error("No output files found.");return t.outputs.filter((e=>e.filepath.endsWith(".map"))).map((e=>e.filepath)).map((n=>({...Eo(e.minifiedPathPrefix,t.outDir,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,{outDir:t.outDir,outputs:t.outputs});o.end();const i=n.time("send sourcemaps");await(async(e,t,n,o)=>{const r=Date.now(),i=t.minifiedPathPrefix,s={git_repository_url:n.git?.remote,git_commit_sha:n.git?.hash,plugin_version:n.version,project_path:n.outDir,service:t.service,type:"js_sourcemap",version:t.releaseVersion},a=o.time("Compute payloads"),u=await Promise.all(e.map((e=>Ao(e,s,i,n.git))));a.end();const c=u.map((e=>e.errors)).flat(),d=u.map((e=>e.warnings)).flat();if(d.length>0&&o.warn(`Warnings while preparing payloads:\n - ${d.join("\n - ")}`),c.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${c.join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e);return}const l=o.time("Upload sourcemaps"),{errors:p,warnings:f}=await zo(u,t,{apiKey:n.apiKey,bundlerName:n.bundlerName,version:n.version,outDir:n.outDir,site:n.site,sendMetrics:n.sendMetrics,addMetric:n.addMetric},o);if(l.end(),o.debug(`Done uploading ${No(`${e.length-p.length}/${e.length}`)} sourcemaps in ${No(ne(Date.now()-r))}.`),p.length>0){const e=`Failed to upload some sourcemaps:\n - ${p.map((({metadata:e,error:t})=>{const n=t.cause||t.stack||t.message;return e?`${_o(e.file)} | ${_o(e.sourcemap)} :\n${n}`:n})).join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e)}f.length>0&&o.warn(`Warnings while uploading sourcemaps:\n - ${f.join("\n - ")}`)})(r,e.sourcemaps,{addMetric:t.addMetric,apiKey:t.apiKey,bundlerName:t.bundlerName,git:t.git,outDir:t.outDir,sendMetrics:t.sendMetrics,site:t.site,version:t.version},n),i.end()},Uo=e=>{const n=t.bold.red,o=e[ko]||{},r={errors:[]};if(o.sourcemaps){const t=o.sourcemaps,i=t.releaseVersion||e.metadata?.version;i||r.errors.push(`${n("sourcemaps.releaseVersion")} is required (set it directly or via ${n("metadata.version")}).`),t.releaseVersion&&e.metadata?.version&&t.releaseVersion!==e.metadata.version&&r.errors.push(`${n("sourcemaps.releaseVersion")} must match ${n("metadata.version")} when both are configured.`),t.service||r.errors.push(`${n("sourcemaps.service")} is required.`),t.minifiedPathPrefix||r.errors.push(`${n("sourcemaps.minifiedPathPrefix")} is required.`),t.minifiedPathPrefix&&!(e=>{let t;try{t=new URL(e).host}catch{}return!(!t&&!e.startsWith("/"))})(t.minifiedPathPrefix)&&r.errors.push(`${n("sourcemaps.minifiedPathPrefix")} must be a valid URL or start with '/'.`),i&&(r.config={bailOnError:!1,dryRun:!1,maxConcurrency:20,...t,releaseVersion:i})}return r},Bo=({options:e,context:t})=>{const n=t.getLogger(xo),o=n.time("validate options"),r=((e,t)=>{const n=[],o=Uo(e);if(n.push(...o.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${xo}.`);return{...e[ko],sourcemaps:o.config}})(e,n);o.end();const i=ge(e,"metrics",n);let s,a,u=!1;const c=async()=>{if(!r.sourcemaps||u)return;u=!0;const e=n.time("sourcemaps process");await Lo(r,{apiKey:t.auth.apiKey,bundlerName:t.bundler.name,git:s,addMetric:t.addMetric,outDir:t.bundler.outDir,outputs:a?.outputs||[],sendMetrics:i,site:t.auth.site,version:t.version},n),e.end()};return[{name:xo,enforce:"post",async git(e){s=e,a&&await c()},async buildReport(t){a=t,!s&&te(e)||await c()},async asyncTrueEnd(){u||await c()}}]},qo="liveDebugger",Vo="datadog-live-debugger-plugin",Ko="if(typeof globalThis.$dd_probes==='undefined'){globalThis.$dd_probes=function(){}}",Ho="__DD_LIVE_DEBUGGER_BUILD__",Wo=e=>void 0===e?Ko:`${Ko};if(typeof globalThis.${Ho}==='undefined'){globalThis.${Ho}={version:${JSON.stringify(e)}}}`;function Jo(e){return"function"==typeof e?e:e.default}function Go(e,t,n,o,r){const i=u.relative(t,e).replace(/\\/g,"/"),s=Yo(n,r);if(s)return`${i};${s}`;const a=function(e){const t=e.node.loc?.start.line??0,n=e.node.loc?.start.column??0;return`${t}:${n}`}(n);return`${i};<anonymous>@${a}:${o}`}function Yo(e,t){const n=e.node,o=e.parent;return"id"in n&&t.isIdentifier(n.id)?n.id.name:t.isObjectMethod(n)||t.isClassMethod(n)||t.isClassPrivateMethod(n)?Xo(n.key,t):t.isVariableDeclarator(o)&&t.isIdentifier(o.id)?o.id.name:t.isAssignmentExpression(o)?function(e,t){if(t.isIdentifier(e))return e.name;if(t.isMemberExpression(e)||t.isOptionalMemberExpression(e)){const n=Qo(e.object,t),o=Zo(e.property,e.computed,t);if(n&&o)return`${n}.${o}`}return null}(o.left,t):t.isObjectProperty(o)||t.isClassProperty(o)||t.isClassPrivateProperty(o)?Xo(o.key,t):null}function Qo(e,t){if(t.isIdentifier(e))return e.name;if(t.isThisExpression(e))return"this";if(t.isMemberExpression(e)||t.isOptionalMemberExpression(e)){const n=Qo(e.object,t),o=Zo(e.property,e.computed,t);if(n&&o)return`${n}.${o}`}return null}function Zo(e,t,n){return n.isPrivateName(e)&&n.isIdentifier(e.id)?`#${e.id.name}`:t?null:n.isIdentifier(e)?e.name:null}function Xo(e,t){return t.isIdentifier(e)?e.name:t.isStringLiteral(e)||t.isNumericLiteral(e)||t.isBigIntLiteral(e)?String(e.value):t.isPrivateName(e)&&t.isIdentifier(e.id)?`#${e.id.name}`:null}function er(e,t){if(e.node.leadingComments)for(const n of e.node.leadingComments)if(n.value.includes(t))return!0;return!1}function tr(e,t){const n=[];if(t.isBlockStatement(e.body)){const o=e.params.flatMap((e=>ar(e,t))),r=new Set(o),i="id"in e&&t.isIdentifier(e.id)?e.id.name:"";for(const o of e.body.body)if(t.isVariableDeclaration(o)){const e=o.end;if(null==e)continue;for(const s of o.declarations)for(const o of ar(s.id,t))r.has(o)||o===i||n.push({name:o,declarationEnd:e,temporalDeadZones:[]})}}const o=n.length>25?n.slice(0,25):n;if(t.isBlockStatement(e.body)){const n=o.map((({name:e})=>e)),r=new Set(n),i=function(e,t,n){const o=new Map;for(const r of e.body)nr(r,t,o,n);return o}(e.body,r,t);for(const e of o)e.temporalDeadZones=i.get(e.name)??[]}return o}function nr(e,t,n,o){o.isFunctionDeclaration(e)||o.isClassDeclaration(e)||(o.isBlockStatement(e)?or(e,t,n,o):o.isIfStatement(e)?(nr(e.consequent,t,n,o),e.alternate&&nr(e.alternate,t,n,o)):o.isForStatement(e)||o.isForInStatement(e)||o.isForOfStatement(e)||o.isWhileStatement(e)||o.isDoWhileStatement(e)?nr(e.body,t,n,o):o.isSwitchStatement(e)?function(e,t,n,o){for(const r of e.cases){rr(r.consequent,e.start,t,n,o);for(const e of r.consequent)nr(e,t,n,o)}}(e,t,n,o):o.isTryStatement(e)?(or(e.block,t,n,o),e.handler&&or(e.handler.body,t,n,o),e.finalizer&&or(e.finalizer,t,n,o)):(o.isLabeledStatement(e)||o.isWithStatement(e))&&nr(e.body,t,n,o))}function or(e,t,n,o){rr(e.body,e.start,t,n,o);for(const r of e.body)nr(r,t,n,o)}function rr(e,t,n,o,r){if(null!=t)for(const i of e)r.isVariableDeclaration(i)&&"var"!==i.kind?ir(i,t,n,o,r):r.isClassDeclaration(i)&&i.id&&sr(i.id.name,t,i.end,n,o)}function ir(e,t,n,o,r){for(const i of e.declarations)for(const s of ar(i.id,r))sr(s,t,e.end,n,o)}function sr(e,t,n,o,r){if(null==n||!o.has(e))return;const i=r.get(e)??[];i.push({start:t,end:n}),r.set(e,i)}function ar(e,t){return t.isIdentifier(e)?[e.name]:t.isRestElement(e)?t.isIdentifier(e.argument)?[e.argument.name]:ar(e.argument,t):t.isAssignmentPattern(e)?ar(e.left,t):t.isObjectPattern(e)?e.properties.flatMap((e=>t.isRestElement(e)?ar(e.argument,t):ar(e.value,t))):t.isArrayPattern(e)?e.elements.flatMap((e=>e?ar(e,t):[])):t.isTSParameterProperty(e)&&t.isIdentifier(e.parameter)?[e.parameter.name]:[]}const ur=["@babel/parser","@babel/traverse","@babel/types","magic-string"];let cr,dr,lr,pr,fr=!1;function mr(e){try{return function(e){switch(e){case"@babel/parser":return C("@babel/parser");case"@babel/traverse":return C("@babel/traverse");case"@babel/types":return C("@babel/types");case"magic-string":return C("magic-string");default:throw new Error(`Unknown peer dependency: ${e}`)}}(e)}catch(e){throw function(e){if(!function(e){if(!(e instanceof Error))return!1;const t=e.code;if("MODULE_NOT_FOUND"!==t&&"ERR_MODULE_NOT_FOUND"!==t)return!1;return ur.some((t=>e.message.includes(t)))}(e))return e instanceof Error?e:new Error(String(e));const t=ur.find((t=>e.message.includes(t))),n=t??ur.join(", ");return new Error(`Datadog Live Debugger could not load "${n}". It is an optional peer dependency that must be installed in your project when the \`liveDebugger\` plugin is enabled. Install the peer dependencies with: \`npm install --save-dev ${ur.join(" ")}\` (or the yarn/pnpm/bun equivalent). Underlying error: ${e.message}`)}(e)}}const hr=/\bfunction\b|=>|\bclass\b|\)\s*\{/;function gr(e){const{code:t,filePath:n,buildRoot:o,honorSkipComments:r,functionTypes:i,namedOnly:s}=e;let a=0,u=0,c=0,d=0,l=0;if(function(e){return/['"][^'"]*(?:@css-module:|\?worker\b|\?sprite\b|dynamic!)[^'"]*['"]/.test(e)}(t))return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:1,skippedUnsupportedCount:d,totalFunctions:l};if(!hr.test(t))return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l};fr||(cr=mr("@babel/parser").parse,dr=Jo(mr("@babel/traverse")),lr=mr("@babel/types"),pr=Jo(mr("magic-string")),fr=!0);const p=cr(t,{sourceType:"unambiguous",plugins:["jsx","typescript"],sourceFilename:n}),f=[],m=new Map,h=new Set,g=new Map,y=new Map;let b=0;if(dr(p,{Function(e){l++;const t=function(e,t){if(t.isClassMethod(e.node)&&"constructor"===e.node.kind&&xr(e,t))return e.node;return}(e,lr);if(t&&(m.set(t,t.body.start),g.set(t,function(e,t){const n=[];for(const o of e)wr(o,n,t);return n}(t.body.body,lr))),!function(e,t){const n=e.node;return!(n.generator||t.isClassMethod(n)&&"constructor"===n.kind)}(e,lr))return void d++;if(r&&function(e,t,n){let o=e;for(;o;){if(er(o,t))return!0;if(n.isStatement(o.node)||n.isExportDeclaration(o.node)){if(o.parentPath&&n.isExportDeclaration(o.parentPath.node))return er(o.parentPath,t);break}o=o.parentPath}return!1}(e,"@dd-no-instrumentation",lr))return void c++;if(i&&!i.includes(function(e,t){if(t.isFunctionDeclaration(e))return"functionDeclaration";if(t.isArrowFunctionExpression(e))return"arrowFunction";if(t.isObjectMethod(e))return"objectMethod";if(t.isClassPrivateMethod(e))return"classPrivateMethod";if(t.isClassMethod(e))return"classMethod";return"functionExpression"}(e.node,lr)))return void d++;if(s&&!Yo(e,lr))return void d++;let p=0;if(!Yo(e,lr)){const t=e.parentPath?.node;t&&(p=y.get(t)||0,y.set(t,p+1))}const w=Go(n,o,e,p,lr);try{const t=e.node,n=b++,o=`$dd_p${n}`,r=function(e,t){const n=[];for(const o of e.params)for(const e of ar(o,t))"this"!==e&&n.push(e);return n.length>25?n.slice(0,25):n}(t,lr),i=tr(t,lr),s=lr.isArrowFunctionExpression(t)&&!lr.isBlockStatement(t.body),a=s&&lr.isSequenceExpression(t.body),c=function(e,t){if(t.isFunction(e.node)&&!t.isArrowFunctionExpression(e.node))return;let n=e.parentPath;for(;n;){const e=n.node;if(t.isClassMethod(e)&&"constructor"===e.kind){if(!xr(n,t))return;return{node:e,parent:n.parent,parentPath:n.parentPath}}if(t.isFunction(e)){if(t.isArrowFunctionExpression(e)){n=n.parentPath;continue}return}n=n.parentPath}return}(e,lr),d=null!=c;c&&(h.add(c.node),m.set(c.node,c.node.body.start));const l=[],p=s||!lr.isBlockStatement(t.body)||!Ir(t.body.body,lr);let g;if(!s&&lr.isBlockStatement(t.body)&&Sr(t.body.body,l,lr),!s&&lr.isBlockStatement(t.body)&&t.body.directives.length>0){g=t.body.directives[t.body.directives.length-1].end}f.push({bodyStart:t.body.start,bodyEnd:t.body.end,functionEnd:t.end,isExpressionBody:s,hasSequenceExpressionBody:a,aliasesExpressionBodySuperCall:d&&s&&kr(t.body,lr),needsTrailingReturn:p,useThisAlias:d,bodyParenStart:s&&"number"==typeof t.body.extra?.parenStart?t.body.extra.parenStart:void 0,directivesEnd:g,functionId:w,probeVarName:o,probeIdx:String(n),entryVars:r,localVars:i,returns:l}),u++}catch(e){a++}}}),0===u)return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l};const w=new pr(t),v=function(e){const t=new Set;for(const n of e)n.aliasesExpressionBodySuperCall&&t.add($r({start:n.bodyStart,end:n.bodyEnd}));return t}(f),$=function(e,t,n,o){const r=[];for(const i of e){const e=t.get(i);null!=e&&r.push({bodyStart:e,superCalls:(n.get(i)??[]).filter((e=>!o.has($r(e))))})}return r}(h,m,g,v);for(let e=f.length-1;e>=0;e--)yr(w,t,f[e]);for(const e of $)br(w,t,e);return{code:w.toString(),map:w.generateMap({source:n,hires:!0}),failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l}}function yr(e,t,n){const{probeVarName:o,probeIdx:r,functionId:i,entryVars:s,localVars:a,returns:u,bodyStart:c,bodyEnd:d,functionEnd:l,isExpressionBody:p,hasSequenceExpressionBody:f,aliasesExpressionBodySuperCall:m,useThisAlias:h,bodyParenStart:g,directivesEnd:y}=n,b=`$dd_rv${r}`,w=h?"$dd_t":"this",v=s.join(", "),$=""!==v,k=`{${v}}`,x=$?`, ${k}`:"";const E=`const ${o} = $dd_probes('${i.replace(/['\\\n\r\u2028\u2029]/g,(e=>{switch(e){case"'":return"\\'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}}))}');`,S=`if (${o}) $dd_entry(${o}, ${w}${x});`,I=`catch(e) { if (${o}) $dd_throw(${o}, e, ${w}${x}); throw e; }`;if(p){if(null!=g){const n=function(e,t,n){const o=[];for(let r=t;r<n;r++)"("===e[r]&&o.push(r);return o}(t,g,c),o=function(e,t,n){const o=[];for(let r=n-1;r>=t;r--)")"===e[r]&&o.push(r);return o}(t,d,l),r=Math.min(n.length,o.length);for(let t=0;t<r;t++){const r=n[t],i=o[t];e.remove(r,r+1),e.remove(i,i+1)}}const n=["{",E,"try {",S,m?`const ${b} = ($dd_t = `:`const ${b} = `].filter(Boolean).join("\n");let r=f?");":";";m&&(r=f?"));":");");const i=[r,`if (${o}) $dd_return(${o}, ${b}, ${w}${Er(k,$,a,d)});`,`return ${b};`,`} ${I}`,"}"].join("\n");if(d-c>=2){const o=f?`${n}(${t[c]}`:n+t[c];e.update(c,c+1,o),e.appendRight(d,i)}else e.update(c,d,n+t.slice(c,d)+i)}else{const r=[E,"try {",`let ${b};`,S].filter(Boolean).join("\n");for(const t of u){const n=Er(k,$,a,t.start);if(null!=t.argStart&&null!=t.argEnd){const r=t.hasSequenceExpressionArgument?`(${b} = (`:`(${b} = `,i=t.hasSequenceExpressionArgument?")":"";e.appendLeft(t.argStart,r),e.appendRight(t.argEnd,`${i}, ${o} ? $dd_return(${o}, ${b}, ${w}${n}) : ${b})`)}else e.appendLeft(t.start,`if (${o}) $dd_return(${o}, undefined, ${w}${n}); `)}if(null!=y){const n=y-1;e.update(n,y,`${t[n]}\n${r}`)}else e.update(c,c+1,`${t[c]}${r}`);const i=Er(k,$,a,d),s=`\n${n.needsTrailingReturn?`if (${o}) $dd_return(${o}, undefined, ${w}${i});\n`:""}} ${I}\n`;e.update(d-1,d,`${s}${t[d-1]}`)}}function br(e,t,n){e.update(n.bodyStart,n.bodyStart+1,`${t[n.bodyStart]}let $dd_t;`);for(const t of n.superCalls)e.appendLeft(t.start,"($dd_t = "),e.appendLeft(t.end,")")}function wr(e,t,n){kr(e,n)&&t.push({start:e.start,end:e.end});const o=Object.values(e);for(const e of o)if(Array.isArray(e))for(const o of e)vr(o,t,n);else vr(e,t,n)}function vr(e,t,n){n.isNode(e)&&(n.isFunction(e)&&!n.isArrowFunctionExpression(e)||wr(e,t,n))}function $r(e){return`${e.start}:${e.end}`}function kr(e,t){return t.isCallExpression(e)&&t.isSuper(e.callee)}function xr(e,t){const n=e.parentPath?.parentPath;if(!n)return!1;const o=n.node;return(t.isClassDeclaration(o)||t.isClassExpression(o))&&null!=o.superClass}function Er(e,t,n,o){const r=function(e,t){const n=e.filter((({declarationEnd:e,temporalDeadZones:n})=>e<=t&&!function(e,t){return e.some((({start:e,end:n})=>e<=t&&t<n))}(n,t))).map((({name:e})=>e));if(0===n.length)return;return`{${n.join(", ")}}`}(n,o);return t&&r?`, ${e}, ${r}`:t?`, ${e}`:r?`, undefined, ${r}`:""}function Sr(e,t,n){for(const o of e)if(n.isReturnStatement(o))t.push({start:o.start,end:o.end,argStart:o.argument?.start??void 0,argEnd:o.argument?.end??void 0,hasSequenceExpressionArgument:n.isSequenceExpression(o.argument)});else if(!n.isFunctionDeclaration(o)&&!n.isClassDeclaration(o))if(n.isBlockStatement(o))Sr(o.body,t,n);else if(n.isIfStatement(o))Sr([o.consequent],t,n),o.alternate&&Sr([o.alternate],t,n);else if(n.isForStatement(o)||n.isForInStatement(o)||n.isForOfStatement(o)||n.isWhileStatement(o)||n.isDoWhileStatement(o))Sr([o.body],t,n);else if(n.isSwitchStatement(o))for(const e of o.cases)Sr(e.consequent,t,n);else n.isTryStatement(o)?(Sr(o.block.body,t,n),o.handler&&Sr(o.handler.body.body,t,n),o.finalizer&&Sr(o.finalizer.body,t,n)):(n.isLabeledStatement(o)||n.isWithStatement(o))&&Sr([o.body],t,n)}function Ir(e,t){if(0===e.length)return!1;const n=e[e.length-1];if(t.isReturnStatement(n))return!0;if(t.isIfStatement(n)&&n.alternate){const e=t.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent],o=t.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];return Ir(e,t)&&Ir(o,t)}return!1}const Dr=["functionDeclaration","functionExpression","arrowFunction","objectMethod","classMethod","classPrivateMethod"],Ar=t.bold.red,Pr=Number(process.env.DD_LD_LIMIT)||1/0,jr=(e,t)=>{const n=t.getLogger(Vo);let o=0,r=0,i=0,s=0,a=0,u=0,c=0,d=0;return{name:Vo,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(l,p){if(e.include.length>0){if(!e.include.some((e=>"string"==typeof e?p.includes(e):e.test(p))))return{code:l}}for(const t of e.exclude){if("string"==typeof t?p.includes(t):t.test(p))return{code:l}}if(d>=Pr)return{code:l};try{const f=gr({code:l,filePath:p,buildRoot:t.buildRoot,honorSkipComments:e.honorSkipComments,functionTypes:e.functionTypes,namedOnly:e.namedOnly});if(o+=f.instrumentedCount,c+=f.totalFunctions,r+=f.failedCount,i+=f.skippedByCommentCount,s+=f.skippedFileCount,a+=f.skippedUnsupportedCount,f.totalFunctions>0&&d++,0===f.instrumentedCount)return{code:l};u++;const m=function(e){const t=e.getNativeBuildContext?.();return t?.inputSourceMap}(this),h=f.map&&m?function(e,t,n,o){try{return k(e,((e,n)=>1===n.depth?t:null))}catch(t){return o.error(`Failed to compose source map for ${n}: ${t}`,{forward:!0}),e}}(f.map,m,p,n):f.map;return{code:f.code,map:h}}catch(e){return n.error(`Instrumentation Error in ${p}: ${e}`,{forward:!0}),{code:l}}}},buildEnd:()=>{c>0&&n.info(`Live Debugger: ${o}/${c} functions instrumented across ${u}/${d} files`,{forward:!0,context:{failedCount:r,skippedByCommentCount:i,skippedFileCount:s,skippedUnsupportedCount:a,totalFilesWithFunctions:d,instrumentedCount:o,totalFunctions:c,transformedFileCount:u}})}}},Mr=({options:e,context:t})=>{const n=((e,t)=>{const n=e[qo]||{},o=e.metadata?.version,r=[];if(void 0!==n.include)if(Array.isArray(n.include)){for(const e of n.include)if("string"!=typeof e&&!(e instanceof RegExp)){r.push(`${Ar("include")} patterns must be strings or RegExp`);break}}else r.push(`${Ar("include")} must be an array of strings or RegExp`);if(void 0!==n.exclude)if(Array.isArray(n.exclude)){for(const e of n.exclude)if("string"!=typeof e&&!(e instanceof RegExp)){r.push(`${Ar("exclude")} patterns must be strings or RegExp`);break}}else r.push(`${Ar("exclude")} must be an array of strings or RegExp`);if(void 0!==n.honorSkipComments&&"boolean"!=typeof n.honorSkipComments&&r.push(`${Ar("honorSkipComments")} must be a boolean`),void 0!==n.functionTypes)if(Array.isArray(n.functionTypes)){for(const e of n.functionTypes)if(!Dr.includes(e)){r.push(`${Ar("functionTypes")} contains invalid value "${e}". Valid values: ${Dr.join(", ")}`);break}}else r.push(`${Ar("functionTypes")} must be an array of FunctionKind values`);if(void 0!==n.namedOnly&&"boolean"!=typeof n.namedOnly&&r.push(`${Ar("namedOnly")} must be a boolean`),r.length)throw t.error(`\n - ${r.join("\n - ")}`),new Error(`Invalid configuration for ${Vo}.`);return{version:o,include:n.include||[/\.[jt]sx?$/],exclude:n.exclude||[/\/node_modules\//,/\.min\.js$/,/\/pyodide-lib\//,/^vite\//,/\0/,/commonjsHelpers\.js$/,/__vite-browser-external/,/@datadog\/browser-/,/browser-sdk\/packages\//],honorSkipComments:n.honorSkipComments??!0,functionTypes:n.functionTypes,namedOnly:n.namedOnly??!1}})(e,t.getLogger(Vo));return t.inject({type:"code",position:Te.BEFORE,injectIntoAllChunks:!0,value:Wo(n.version)}),[jr(n,t)]};const Tr=[e=>/modules\.tree\.(count|size)$/.test(e.metric)?null:e,e=>e.tags.some((e=>/^assetName:.*\.map$/.test(e)||/^moduleName:\/node_modules/.test(e)))?null:e,e=>{const t={size:1e5,count:10,duration:1e3};/^sourcemaps\.upload\.(failure|retry)$/.test(e.metric)&&(t.count=0),/(entries|loaders|warnings|errors)\.count$/.test(e.metric)&&(t.count=0),/(modules\.(dependencies|dependents)$)/.test(e.metric)&&(t.count=30),/modules\.tree\.count$/.test(e.metric)&&(t.count=150),/modules\.tree\.size$/.test(e.metric)&&(t.size=15e5),/entries\.size$/.test(e.metric)&&(t.size=0),/entries\.modules\.count$/.test(e.metric)&&(t.count=0);return(e.points.length?e.points.reduce(((e,t)=>e+t[1]),0)/e.points.length:0)>t[e.type]?e:null}],Cr="metrics",Or="datadog-metrics-plugin",Nr=e=>Math.floor((e||Date.now())/1e3),Rr=(e,t)=>{const n=[`bundler:${ie(e.bundler.name)}`,`plugin_version:${ie(e.version)}`,`site:${ie(e.auth.site)}`];return e.build.metadata.name&&n.push(`build_name:${ie(e.build.metadata.name)}`),e.build.metadata.version&&n.push(`build_version:${ie(e.build.metadata.version)}`),[...n,...t]},_r=(e,t,n)=>({...e,tags:[...e.tags,...t],metric:n?`${n}.${e.metric}`:e.metric}),Fr=(e,t,n,o,r)=>{const i=new Set;for(const t of e){let e={...t,toSend:!0};if(n?.length)for(const t of n){const n=t({metric:e.metric,type:e.type,points:e.points,tags:e.tags});n?e={...n,toSend:e.toSend}:e.toSend=!1}i.add(_r(e,o,r))}const s=Array.from(i).filter((e=>e.toSend)).length;return i.add(_r({metric:"metrics.count",type:"count",points:[[t,s+1]],tags:[],toSend:!0},o,r)),i},zr=(e="")=>e.endsWith("/")?e:`${e}/`,Lr=(e,t)=>{let n=e;return e.split(zr(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},Ur=(e,t)=>e.split("!").pop().replace(zr(t),"./"),Br=(e,t,n)=>{let o=e.name||e.userRequest;return o||(o=((e,t)=>{let n=e.userRequest;if(!n){let o;o=t.moduleGraph&&"function"==typeof t.moduleGraph.getIssuer?t.moduleGraph.getIssuer(e):e.issuer,n=o?.userRequest,n||(n=e._identifier?.split("!").pop())}return n||"unknown"})(e,t)),Ur(o||"no-name",n)},qr=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),Vr=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),Kr=t.bold.red,Hr=t.bold.cyan,Wr=e=>(t,n)=>{let o,r;return"function"==typeof e?(o=e(t),r=e(n)):(o=t[e],r=n[e]),o>r?-1:o<r?1:0},Jr=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(Wr("duration"));const o={name:`${e} duration`,values:n.map((e=>({name:e.name,value:ne(e.duration)}))),top:!0};n.sort(Wr("increment"));return[o,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},Gr=(e,t,n)=>{const o=[];var r;n&&(o.push(...Jr("Loader",n.loaders)),o.push(...Jr("Tapable",n.tapables)),o.push(...Jr("Module",n.modules))),o.push(...(e=>{const t={name:"Module total dependents",values:[],top:!0},n={name:"Module total dependencies",values:[],top:!0},o={name:"Module size",values:[],top:!0},r={name:"Module aggregated size",values:[],top:!0},i=new Set,s=ee(e.build),a=new Map,u=new Map,c=new Map;for(const e of s.inputs||[]){if("map"===e.type)continue;const t=new Set(e.dependencies),n=new Set(e.dependents);for(const n of t)c.has(n)||c.set(n,new Set),c.get(n).add(e.filepath);for(const t of n)u.has(t)||u.set(t,new Set),u.get(t).add(e.filepath);if(u.has(e.filepath)){const n=u.get(e.filepath);for(const e of n)t.add(e)}if(c.has(e.filepath)){const t=c.get(e.filepath);for(const e of t)n.add(e)}u.set(e.filepath,t),c.set(e.filepath,n),a.set(e.filepath,{name:e.name,size:e.size,dependencies:t,dependents:n})}for(const[e,t]of a){const n=u.get(e)||new Set,o=c.get(e)||new Set;let r=t.size;for(const e of n)r+=a.get(e)?.size||0;i.add({name:t.name,size:t.size,aggregatedSize:r,dependents:o,dependencies:n})}if(!i.size)return[t,n,o];const d=Array.from(i);return d.sort(Wr((e=>e.dependents.size))),t.values=d.map((e=>({name:e.name,value:e.dependents.size.toString()}))),d.sort(Wr((e=>e.dependencies.size))),n.values=d.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),d.sort(Wr("size")),o.values=d.map((e=>({name:e.name,value:v(e.size)}))),d.sort(Wr("aggregatedSize")),r.values=d.map((e=>({name:e.name,value:v(e.aggregatedSize||e.size)}))),[t,n,o,r]})(e)),o.push(...(r=e,[{name:"Asset size",values:(r.build.outputs||[]).filter((e=>"map"!==e.type)).sort(Wr((e=>e.size))).map((e=>({name:e.name,value:v(e.size)}))),top:!0},{name:"Entry aggregated size",values:(r.build.entries||[]).sort(Wr((e=>e.size))).map((e=>({name:e.name,value:v(e.size)}))),top:!0},{name:"Entry number of modules",values:(r.build.entries||[]).sort(Wr((e=>e.size))).map((e=>({name:e.name,value:e.inputs.length.toString()})))||[],top:!0}])),o.push(...(e=>{const t={name:"General Numbers",values:[],top:!1},n=e.build.inputs?e.build.inputs.length:0,o=e.build.outputs?e.build.outputs.length:0,r=e.build.warnings.length,i=e.build.errors.length,s=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:ne(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:ne(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:ne(e.build.writeDuration)}),t.values.push({name:"Number of modules",value:n.toString()},{name:"Number of assets",value:o.toString()},{name:"Number of entries",value:s.toString()},{name:"Number of warnings",value:r.toString()},{name:"Number of errors",value:i.toString()}),[t]})(e));const i=(e=>{let t="";for(const t of e){t.top&&t.values.length>=5&&(t.values=t.values.slice(0,5),t.name=`Top 5 ${t.name}`);for(const e of t.values)e.name=oe(e.name,60)}const n=Math.max(...e.map((e=>e.name.length))),o=Math.max(...e.flatMap((e=>e.values.map((e=>e.name.length))))),r=Math.max(...e.flatMap((e=>e.values.map((e=>e.value.length))))),i=Math.max(n+4,o+r+4);for(const n of e){if(0===n.values.length)continue;const e=i-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=r-e.value.length;t+=` [${Kr(e.value)}] ${" ".repeat(n)}${Hr(e.name)}\n`}}return t})(o);t.info(i)},Yr="api/v1/series",Qr=t.bold.green,Zr=(e,t,n)=>{if(!t.apiKey)return void n.info("Won't send metrics to Datadog: missing API Key.");if(!e.size)return void n.debug("No metrics to send.");const o=Array.from(e).filter((e=>e.toSend)).map((e=>({...e,toSend:void 0}))),r=new Map;for(const e of o)r.has(e.metric)||r.set(e.metric,0),r.set(e.metric,r.get(e.metric)+1);const i=Array.from(r.entries()).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${o.length} metrics with configuration:\n - intake: ${Qr(`https://api.${t.site}/${Yr}`)}\n\nMetrics:\n - ${i.join("\n - ")}`),Y({method:"POST",url:`https://api.${t.site}/${Yr}?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:o})})}).catch((e=>{n.error(`Error sending metrics ${e}`)}))},Xr=["onStart","onLoad","onResolve","onEnd"],ei=new Map,ti=new Map,ni=new Map,oi=(e,t,n)=>{const o=Object.assign({},e);for(const r of Xr)o[r]=async(o,i)=>{const s=ti.get(t)||{name:t,increment:0,duration:0,events:{}};s.events[r]=s.events[r]||{name:r,values:[]};const a="onLoad"===r;return(0,e[r])(o,(async(...e)=>{const o=Ur(e[0].path,n),u=ni.get(o)||{name:o,increment:0,duration:0,events:{}};u.events[r]=u.events[r]||{name:r,values:[]};const c=x.now();try{return await i(...e)}finally{const n=x.now(),i=n-c,d={start:c,end:n,duration:i,context:Vr(e)};if(s.events[r].values.push(d),s.duration+=i,s.increment+=1,ti.set(t,s),u.events[r].values.push(d),u.duration+=i,u.increment+=1,ni.set(o,u),a){const e=ei.get(t)||{name:t,increment:0,duration:0,events:{}};e.events[r]=e.events[r]||{name:r,values:[]},e.events[r].values.push(d),e.duration+=i,e.increment+=1,ei.set(t,e)}}}))};return o},ri=(e,t)=>({setup:n=>{n.initialOptions.metafile=!0;const o=t.time("wrapping plugins");((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const o of n){const n=o.setup;o.setup=async r=>{const i=oi(r,o.name,t);await n({...i,initialOptions:{...i.initialOptions,plugins:e}})}}}})(n,e.buildRoot),o.end(),n.onEnd((async n=>{if(!n.metafile)return void t.warn("Missing metafile, can't proceed with modules data.");const o=t.time("getting plugins results"),{plugins:r,loaders:i,modules:s}={plugins:ti,modules:ni,loaders:ei};o.end(),await e.asyncHook("timings",{tapables:r,loaders:i,modules:s})}))}});class ii{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=Br(e,t,this.cwd),o=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(qr))(e);o.length||o.push("no-loader"),this.started[n]={module:Lr(n),timings:{start:x.now(),duration:0,end:0},loaders:o}}doneModule(e,t){const n=Br(e,t,this.cwd),o=this.started[n];o&&(o.timings.end=x.now(),o.timings.duration=o.timings.end-o.timings.start,this.finished.push(o),delete this.started[n])}getResults(){const e=new Map,t=new Map;for(const n of this.finished){const o=n.timings.end-n.timings.start,r=t.get(n.module)||{name:n.module,increment:0,duration:0,events:{}},i=n.loaders.join(",");r.events[i]=r.events[i]||{name:i,values:[]},r.events[i].values.push(n.timings),r.increment+=1,r.duration+=o,t.set(n.module,r);for(const t of n.loaders){const n=e.get(t)||{name:t,increment:0,duration:0,events:{}};n.increment+=1,n.duration+=o,e.set(t,n)}}return{loaders:e,modules:t}}}class si{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,o,r,i){const s=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};s.events[n]||(s.events[n]={name:n,values:[]}),s.events[n].values.push({start:r,end:i,duration:i-r,context:o,type:e}),s.duration+=i-r,s.increment+=1,this.timings.set(t,s)}getResults(){const e=this.timings;for(const[t,n]of this.timings){const o=n;o.duration=Object.values(n.events).map((e=>e.values.reduce(((e,t)=>e+t.end-t.start),0))).reduce(((e,t)=>e+t),0),e.set(t,o)}return{monitoredTaps:this.monitoredTaps,tapables:this.tapables,hooks:this.hooks,timings:e}}getPromiseTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=t.apply(this,r),a=()=>{this.saveResult(e,n,o,Vr(r),i,x.now())};return s.then(a,a),s}}getAsyncTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=r.pop();return t.apply(this,[...r,(...t)=>(this.saveResult(e,n,o,Vr(r),i,x.now()),s(...t))])}}getDefaultTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=t.apply(this,r);return this.saveResult(e,n,o,Vr(r),i,x.now()),s}}getTapPatch(e,t,n,o){switch(e){case"promise":return this.getPromiseTapPatch(e,t,n,o);case"async":return this.getAsyncTapPatch(e,t,n,o);default:return this.getDefaultTapPatch(e,t,n,o)}}newTap(e,t,n,o){return(r,i)=>{const s="string"==typeof(a=r)?a:a.name;var a;const u=`${t}-${s}`;if(this.monitoredTaps[u])return n.call(o,r,i);this.monitoredTaps[u]=!0;const c=this.getTapPatch(e,i,s,t);return n.call(o,r,c)}}replaceTaps(e,t){t.tap=this.newTap("default",e,t.tap,t),t.tapAsync=this.newTap("async",e,t.tapAsync,t),t.tapPromise=this.newTap("promise",e,t.tapPromise,t)}patchHook(e,t,n){n._fakeHook||e.includes(Or)||(this.hooks[e]||(this.hooks[e]=[]),this.hooks[e].includes(t)||(this.hooks[e].push(t),this.replaceTaps(t,n)))}patchHooks(e){const t=e.constructor.name,n=Object.keys(e.hooks).filter((e=>!this.ignoredHooks.includes(e)&&!this.hooks[t]?.includes(e)));for(const o of n)this.patchHook(t,o,e.hooks[o])}checkNewHooks(){for(const e of this.tapables)this.patchHooks(e)}throughHooks(e){this.tapables.includes(e)||this.tapables.push(e),this.patchHooks(e)}}const ai=e=>async t=>{const n=e.getLogger(Or),o={name:Or},r=new si(e.buildRoot),i=new ii(e.buildRoot),s=n.time("parse compiler hooks");r.throughHooks(t),s.end(),t.hooks.thisCompilation.tap(o,(e=>{const t=n.time("parse compilation hooks");r.throughHooks(e),t.end(),e.hooks.buildModule.tap(o,(t=>{i.startModule(t,e)})),e.hooks.succeedModule.tap(o,(t=>{i.doneModule(t,e)})),e.hooks.failedModule&&e.hooks.failedModule.tap(o,(t=>{i.doneModule(t,e)}))})),t.hooks.afterEmit.tapPromise(o,(async()=>{const{timings:t}=r.getResults(),{loaders:n,modules:o}=i.getResults();await e.asyncHook("timings",{tapables:t,loaders:n,modules:o})}))},ui={filters:Tr},ci=({options:e,context:t,stores:n})=>{const o=t.getLogger(Or);let r=0;((e,t)=>{e.addMetric=e=>{t.metrics.add(e)}})(t,n);const i=((e,t)=>{const n=e[Cr],o=Nr(n?.timestamp);let r=!1===n?.enableDefaultPrefix?"":`build.${t}`;return n?.prefix&&(r+=r?`.${n.prefix}`:n.prefix),{enableDefaultPrefix:!0,enableTracing:!1,filters:Tr,tags:[],...e[Cr],timestamp:o,prefix:r.toLowerCase().replace(/(^\.*|\.*$)/g,"")}})(e,t.bundler.name),s=[],a={name:Or,enforce:"pre",esbuild:ri(t,o),webpack:ai(t),rspack:ai(t)},u=o.time("build",{start:!1}),c=i.enableTracing&&["esbuild","webpack","rspack"].includes(t.bundler.name);let d,l;const p=async()=>{if(!n.metrics.size)return;const e=o.time("aggregating collected metrics"),r=(()=>{const e=new Set(n.metrics);n.metrics.clear();const o=Rr(t,i.tags);return Fr(e,i.timestamp,i.filters,o,i.prefix)})();await t.asyncHook("metrics",r),e.end();const s=o.time("sending collected metrics to Datadog");await Zr(r,{apiKey:t.auth.apiKey,site:t.auth.site},o),s.end()},f=async()=>{t.build.end=Date.now(),t.build.duration=t.build.end-t.build.start,t.build.writeDuration=t.build.end-r;const e=o.time("aggregating metrics"),n=i.timestamp,s=o.time("aggregate universal metrics"),a=((e,t)=>{const n=new Set,o=e.inputs||[],r=e.outputs||[],i=e.entries||[],s=e.warnings.length,a=e.errors.length,u=e.duration,c=new Map,d=new Map,l=new Map;for(const e of i){for(const t of e.inputs)c.has(t.filepath)||c.set(t.filepath,[]),c.get(t.filepath).push(e.name);for(const t of e.outputs){const n=t.filepath.replace(/\.map$/,"");l.has(n)||l.set(n,[]),l.get(n).push(e.name)}}for(const e of r)for(const t of e.inputs)d.has(t.filepath)||d.set(t.filepath,[]),d.get(t.filepath).push(e.name);n.add({metric:"assets.count",type:"count",points:[[t,r.length]],tags:[]}).add({metric:"entries.count",type:"count",points:[[t,i.length]],tags:[]}).add({metric:"errors.count",type:"count",points:[[t,a]],tags:[]}).add({metric:"modules.count",type:"count",points:[[t,o.length]],tags:[]}).add({metric:"warnings.count",type:"count",points:[[t,s]],tags:[]}),u&&n.add({metric:"compilation.duration",type:"duration",points:[[t,u]],tags:[]});for(const e of o){const o=[`moduleName:${e.name}`,`moduleType:${e.type}`];c.has(e.filepath)&&o.push(...c.get(e.filepath).map((e=>`entryName:${e}`))),d.has(e.filepath)&&o.push(...d.get(e.filepath).map((e=>`assetName:${e}`))),n.add({metric:"modules.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"modules.dependencies",type:"count",points:[[t,e.dependencies.size]],tags:o}).add({metric:"modules.dependents",type:"count",points:[[t,e.dependents.size]],tags:o})}for(const e of r){const o=[`assetName:${e.name}`,`assetType:${e.type}`],r=e.filepath.replace(/\.map$/,"");l.has(r)&&o.push(...l.get(r).map((e=>`entryName:${e}`))),n.add({metric:"assets.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"assets.modules.count",type:"count",points:[[t,e.inputs.length]],tags:o})}for(const e of i){const o=[`entryName:${e.name}`];n.add({metric:"entries.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"entries.modules.count",type:"count",points:[[t,e.inputs.length]],tags:o}).add({metric:"entries.assets.count",type:"count",points:[[t,e.outputs.length]],tags:o})}return n})(l,n);s.end();const u=o.time("aggregate plugins metrics"),c=((e,t)=>{const n=new Set;if(!e)return n;n.add({metric:"plugins.count",type:"count",points:[[t,e.size]],tags:[]});for(const o of e.values()){let e=0,r=0;for(const i of Object.values(o.events)){let s=0;r+=i.values.length;for(const t of i.values){const n=t.end-t.start;s+=n,e+=n}n.add({metric:"plugins.hooks.duration",type:"duration",points:[[t,s]],tags:[`pluginName:${o.name}`,`hookName:${i.name}`]}).add({metric:"plugins.hooks.increment",type:"count",points:[[t,i.values.length]],tags:[`pluginName:${o.name}`,`hookName:${i.name}`]})}n.add({metric:"plugins.duration",type:"duration",points:[[t,e]],tags:[`pluginName:${o.name}`]}).add({metric:"plugins.increment",type:"count",points:[[t,r]],tags:[`pluginName:${o.name}`]})}return n})(d?.tapables,n);u.end();const p=o.time("aggregate loaders metrics"),f=((e,t)=>{const n=new Set;if(!e)return n;n.add({metric:"loaders.count",type:"count",points:[[t,e.size]],tags:[]});for(const o of e.values())n.add({metric:"loaders.duration",type:"duration",points:[[t,o.duration]],tags:[`loaderName:${o.name}`]}).add({metric:"loaders.increment",type:"count",points:[[t,o.increment]],tags:[`loaderName:${o.name}`]});return n})(d?.loaders,n);p.end();const m=new Set([...a,...c,...f]),h=Rr(t,i.tags),g=Fr(m,n,i.filters,h,i.prefix);await t.asyncHook("metrics",g),e.end();const y=o.time("outputing report");Gr(t,o,d),y.end();const b=o.time("sending metrics to Datadog");await Zr(g,{apiKey:t.auth.apiKey,site:t.auth.site},o),b.end()},m={name:"datadog-universal-metrics-plugin",enforce:"post",buildStart(){u.resume(),t.build.start=t.build.start||Date.now(),e[Cr]?.timestamp||(i.timestamp=Nr(t.build.start))},buildEnd(){u.end(),r=Date.now()},async timings(e){d=e,l&&await f()},async buildReport(e){l=e,!d&&c||await f()},async flush(){await p()}};return i.enableTracing&&s.push(a),s.push(m),s},di="output",li="datadog-output-plugin",pi=(e,t)=>"string"==typeof t?t.replace(/(\.json)?$/,".json"):!0===t?`${e}.json`:t,fi=e=>{const t=void 0===e;return{build:pi("build",e?.build??t),bundler:pi("bundler",e?.bundler??t),dependencies:pi("dependencies",e?.dependencies??t),errors:pi("errors",e?.errors??t),logs:pi("logs",e?.logs??t),metrics:pi("metrics",e?.metrics??t),timings:pi("timings",e?.timings??t),warnings:pi("warnings",e?.warnings??t)}},mi=(e,t)=>n=>{n.hooks.done.tap("bundler-outputs",(n=>{t((()=>{const t=e.time("stats serialization"),o=n.toJson({all:!1,assets:!0,children:!0,chunks:!0,chunkGroupAuxiliary:!0,chunkGroupChildren:!0,chunkGroups:!0,chunkRelations:!0,entrypoints:!0,errors:!0,ids:!0,modules:!0,nestedModules:!0,relatedAssets:!0,warnings:!0,reasons:!1,chunkModules:!1});return t.end(),o}))}))},hi=e=>{const t=new Set;return{buildStart(){t.clear()},writeBundle(e,n){t.add(n)},closeBundle(){e((()=>Array.from(t)))}}},gi=({options:e,context:t})=>{const n=t.getLogger(li),o=(e=>({path:"./",...e[di],files:fi(e[di]?.files)}))(e),r=(e,r)=>{const i=o.files[e];if(!r||!1===i)return;t.queue((async()=>{const e=n.time(`output ${i}`),c=((e,t,n)=>{const o=u.isAbsolute(t)?t:u.resolve(e,t);return u.resolve(o,n)})(t.bundler.outDir,o.path,i);let d;try{const e="function"==typeof r?await r():r;await(async(e,t)=>{await Ie(u.dirname(e));const n=s.createWriteStream(e),o=new a(t,void 0,2),r=new Promise(((e,t)=>{o.on("end",(()=>{e()})),o.on("error",(e=>{t(e)}))}));return o.pipe(n),r})(c,e)}catch(e){d=e}d?n.error(`Failed writing ${i}: ${d}`):n.debug(`Wrote "./${u.relative(t.buildRoot,c)}"`),e.end()})())};return[{name:li,buildReport(e){const t=n.time("serialize report"),o=ee(e);t.end(),r("build",{bundler:o.bundler,metadata:o.metadata,start:o.start,end:o.end,duration:o.duration,writeDuration:o.writeDuration,entries:o.entries,outputs:o.outputs}),r("logs",o.logs),r("timings",o.timings),r("dependencies",o.inputs),r("errors",o.errors),r("warnings",o.warnings)},metrics(e){r("metrics",(()=>Array.from(e)))},esbuild:{setup(e){e.onEnd((e=>{r("bundler",e.metafile)}))}},rspack:mi(n,(e=>{r("bundler",e)})),rollup:hi((e=>{r("bundler",e)})),vite:hi((e=>{r("bundler",e)})),webpack:mi(n,(e=>{r("bundler",e)}))}]},yi="rum",bi="datadog-rum-plugin",wi=["8","9","a","b"],vi=(e,t)=>{const n={service:e.service,version:e.version};return e.debugId&&(n.ddDebugId=t?(e=>{const t=p("sha256").update(e).digest("hex").slice(0,32),n=`${t.slice(0,12)}4${t.slice(13)}`,o=n.charCodeAt(16)%4,r=`${n.slice(0,16)}${wi[o]}${n.slice(17)}`;return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")})(t):f()),`(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(n)},${JSON.stringify("DD_SOURCE_CODE_CONTEXT")});`},$i="datadog-rum-privacy-plugin";const ki=(e,t)=>{const n=t.getLogger($i),o=function(e,t){const n={privacy:{addToDictionaryHelper:{expression:{code:e}}}};return["esbuild","webpack","rspack"].includes(t)&&(n.output={...n.output,inlineSourceMap:!1,embedCodeInSourceMap:!0}),n}(e.helperCodeExpression,t.bundler.name);let r=0,i=0;return{name:$i,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(e,t){try{const n=function(e){if("rspack"===e?.framework||"webpack"===e?.framework)switch(typeof e.inputSourceMap){case"undefined":return;case"string":return e.inputSourceMap;default:return JSON.stringify(e.inputSourceMap)}}(this.getNativeBuildContext?.()),s=E({id:t,code:e,map:n},o);return 0===s.privacyDictionarySize?{code:e}:(r+=s.privacyDictionarySize,i++,s)}catch(t){return n.error(`Instrumentation Error: ${t}`,{forward:!0}),{code:e}}}},buildEnd:()=>{n.debug(`Privacy dictionary will include ${r} entries across ${i} files`,{forward:!0,context:{dictionaryEntryCount:r,fileCount:i}})}}},xi=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,Ei=(e,t)=>{const n=e.sdk;if(n.clientToken)return xi(e);if(!t.auth.apiKey||!t.auth.appKey)throw new Error('Missing "auth.apiKey" and/or "auth.appKey" to fetch "rum.sdk.clientToken".');return async()=>{let o;try{const e=await Y({url:`https://api.${t.auth.site}/api/v2/rum/applications/${n.applicationId}`,type:"json",auth:t.auth});o=e.data?.attributes?.client_token}catch(e){throw new Error(`Could not fetch the clientToken: ${e.message}`)}if(!o)throw new Error("Missing clientToken in the API response.");return xi({...e,sdk:{clientToken:o,...n}})}},Si=e=>{const n=t.bold.red,o=e[yi]||{},r={errors:[]};if(!o.sdk)return r;o.sdk.applicationId||r.errors.push(`Missing ${n("applicationId")} in the SDK configuration.`),e.auth.apiKey&&e.auth.appKey||o.sdk.clientToken||r.errors.push(`Missing ${n('"auth.apiKey"')} and/or ${n('"auth.appKey"')} to fetch missing client token.`);const i={applicationId:"unknown_application_id",allowUntrustedEvents:!1,compressIntakeRequests:!1,defaultPrivacyLevel:"mask",enablePrivacyForActionName:!1,sessionReplaySampleRate:0,sessionSampleRate:100,silentMultipleInit:!1,site:e.auth.site||"datadoghq.com",startSessionReplayRecordingManually:!1,storeContextsAcrossPages:!1,telemetrySampleRate:20,traceSampleRate:100,trackingConsent:"granted",trackLongTasks:!1,trackResources:!1,trackUserInteractions:!1,trackViewsManually:!1};return r.config={...i,...o.sdk},r},Ii=e=>{const t=e[yi]||{},n={errors:[]};if(t.privacy){const e={exclude:[/\/node_modules\//,/\.preval\./,/^[!@#$%^&*()=+~`-]/],include:[/\.(?:c|m)?(?:j|t)sx?$/],addToDictionaryFunctionName:"$",helperCodeExpression:"/*__PURE__*/((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()"};n.config={...e,...t.privacy}}return n},Di=e=>{const n=t.bold.red,o=e[yi]||{},r={errors:[]};if(!o.sourceCodeContext)return r;const i=o.sourceCodeContext;return i?.debugId||i?.service&&"string"==typeof i.service||r.errors.push(`Missing ${n('"rum.sourceCodeContext.service"')}.`),r.config={...i,version:i.version||e.metadata?.version},r},Ai=({options:e,context:t})=>{const n=((e,t)=>{const n=[],o=Si(e),r=Ii(e),i=Di(e);if(n.push(...o.errors),n.push(...r.errors),n.push(...i.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${bi}.`);const s={...e[yi],sdk:void 0,privacy:void 0,sourceCodeContext:void 0};return o.config&&(s.sdk=o.config),r.config&&(s.privacy=r.config,t.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(s.privacy,((e,t)=>t instanceof RegExp?t.toString():t))}`,{forward:!0})),i.config&&(s.sourceCodeContext=i.config),s})(e,t.getLogger(bi)),o=[],r=n.sourceCodeContext;if(r&&t.inject({type:"code",position:Te.BEFORE,injectIntoAllChunks:!0,value:e=>vi(r,e)}),n.sdk&&(t.inject({type:"file",position:Te.MIDDLE,value:u.join(T,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Te.MIDDLE,value:Ei(n,t)})),n.privacy){t.inject({type:"file",position:Te.BEFORE,value:u.join(T,"./privacy-helpers.js")});const e=ki(n.privacy,t);o.push(e)}return o},Pi="datadog-analytics-plugin",ji=({context:e})=>{const t=e.getLogger(Pi);return[{name:Pi,async buildStart(){"production"===e.env&&e.queue((async()=>{try{await e.sendLog({message:"Build started",context:{plugins:e.pluginNames}})}catch(e){t.debug(`Could not submit data to Datadog: ${e}`)}})())}}]},Mi="datadog-async-queue-plugin",Ti=e=>{const{context:t,stores:n}=e,o=t.getLogger(Mi),r=[];return t.queue=e=>{const t=e.catch((e=>{r.push(e.message||e.toString())}));n.queue.push(t)},[{name:Mi,asyncTrueEnd:async()=>{await Promise.all(n.queue),r.length>0&&o.error(`Error occurred while processing async queue:\n ${r.join("\n ")}`)}}]},Ci=async(e,t,n)=>{const o=[],r=e.initialOptions.entryPoints,i=[],s=[];if(Array.isArray(r))for(const e of r){const t=e&&"object"==typeof e?e.in:e;i.push({path:t})}else r&&"object"==typeof r&&i.push(...Object.entries(r).map((([e,t])=>({name:e,path:t}))));const a=i.flatMap((e=>{return(t=e.path,t.includes("*")?w.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,r])=>{const i=await e.resolve(r,{kind:"entry-point",resolveDir:t.buildRoot});i.errors.length&&s.push(...i.errors.map((e=>e.text))),i.path&&o.push({name:n.name,resolved:i.path,original:n.path})}));for(const e of s)n.error(e);return await Promise.all(a),o},Oi=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,Ni=/(\?|%3F|\|)+/gi,Ri=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=zi(e),Oi.lastIndex=0,Oi.exec(t)?.[1]||"unknown");var t},_i=["unknown","commonjsHelpers.js",`vite${u.sep}preload-helper.js`],Fi=(e,t,n)=>{const o=new Set;for(const n of e){const e=zi(n);X(n)||e===t||_i.includes(e)||o.add(e)}return o},zi=e=>e.split("!").pop().split(Ni).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/\\]+/,""),Li=(e,t)=>X(t)?O:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):((e,t)=>{const n=t.split(u.sep),o=e.split(u.sep).filter(((e,t)=>e===n[t])).join(u.sep);return e.replace(o,"")})(t.split("!").pop(),e).split("node_modules").pop().split(Ni).shift().replace(/^((\.\.?)?[/\\])+/g,""),Ui=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Xn(t,e),n]))),Bi=(e,t)=>({setup(n){const o=new Map;let r=[];const i=t.time("build report",{start:!1});n.onStart((async()=>{o.clear(),r=[],i.resume();const s=t.time("process entries");r.push(...await Ci(n,e,t));for(const t of r){const n=Li(e.bundler.outDir,t.resolved);t.name?o.set(n,t.name):o.set(n,n)}s.end(),i.pause()})),n.onEnd((async n=>{i.resume();const r=t.time("collecting errors and warnings"),s=e.bundler.outDir,a=e.buildRoot;for(const t of n.errors)e.build.errors.push(t.text);for(const t of n.warnings)e.build.warnings.push(t.text);if(r.end(),!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const c=[],d=[],l=[],p=[],f=[],m={},h={},g=t.time("indexing metafile data"),y=Ui(n.metafile.inputs,a),b=Ui(n.metafile.outputs,a);g.end();const w=e=>{if(!X(e))return e;const t=y[Xn(a,e)];if(!t)return e;const n=t.imports.find((e=>!X(e.path)));return n?n.path:e},v=t.time("looping through inputs");for(const[e,t]of Object.entries(n.metafile.inputs)){if(X(e))continue;const n=Xn(a,e),o={name:Li(s,e),filepath:n,dependents:new Set,dependencies:new Set,size:t.bytes,type:Ri(e)};m[n]=o,c.push(o)}v.end();const $=t.time("looping through outputs");for(const[e,r]of Object.entries(n.metafile.outputs)){const n=Xn(a,e),i=Li(s,n),u=[];for(const e of Object.keys(r.inputs)){if(X(e))continue;const n=m[Xn(a,e)];n?u.push(n):t.debug(`Input ${e} not found for output ${i}`)}if(r.entryPoint&&!u.length){const e=m[Xn(a,r.entryPoint)];if(!e){t.debug(`Input ${r.entryPoint} not found for output ${i}`);continue}u.push(e)}const c={name:i,filepath:n,inputs:u,size:r.bytes,type:Ri(n)};if(h[n]=c,"map"===c.type&&p.push(c),d.push(c),!r.entryPoint)continue;const f=m[Xn(a,w(r.entryPoint))];if(f){if(!o.get(f.name))continue;const e={...c,name:o.get(f.name)||f.name,outputs:[c],size:c.size};l.push(e)}}$.end();const k=t.time("looping through sourcemaps");for(const e of p){const n=h[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}k.end();const x={inputs:{report:m,meta:y},outputs:{report:h,meta:b}},E=/(<runtime>|https:|file:|data:|#)/g,S=e=>!X(e)&&!e.match(E),I=(e,n,o={})=>{if(!S(e))return o;const r=n.report[e];if(!r)return t.debug(`Could not find report's ${e}`),o;if(o[r.filepath])return o;o[r.filepath]=r;const i=n.meta[e];if(!i)return t.debug(`Could not find metafile's ${e}`),o;if(!i.imports||!i.imports.length)return o;for(const t of i.imports){const i=t.path.match(/^\.\.?\//),d=i?u.dirname(e):a,l=Xn(d,t.path);if(t.external){if(S(t.path)){const e=i?l:t.path,n=x.inputs.report[e]||{filepath:e,name:Li(s,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in r&&(n.dependents.add(r),r.dependencies.add(n)),"inputs"in r&&!r.inputs.includes(n)&&r.inputs.push(n),c.includes(n)||c.push(n),x.inputs.report[e]=n,o[n.filepath]=n}}else I(l,n,o)}return o},D=t.time("looping through entries");for(const e of l){const t={},n={};for(const n of e.inputs)I(n.filepath,x.inputs,t);for(const t of e.outputs)I(t.filepath,x.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),f.push(e)}D.end();const A=t.time("aggregate dependencies and dependents");for(const e of c){if("external"===e.type)continue;const n=x.inputs.meta[e.filepath];if(n)for(const o of n.imports){if(!S(o.path))continue;const n=o.path.match(/^\.?\.\//),r=n?u.dirname(e.filepath):a,i=Xn(r,o.path);let s;if(o.external){const e=n?i:o.path;s=x.inputs.report[e]}else s=x.inputs.report[i];s?(e.dependencies.add(s),s.dependents.add(e)):t.debug(`Could not find input file of ${o.path} imported from ${e.name}`)}else t.debug(`Could not find metafile's ${e.name}`)}A.end(),e.build.outputs=d,e.build.inputs=c,e.build.entries=f,i.end(),await e.asyncHook("buildReport",e.build)}))}}),qi=(e,t)=>{const n=t.time("module parsing",{start:!1}),o=t.time("build report",{start:!1}),r=t.time("filling entries",{start:!1}),i=t.time("filling inputs and outputs",{start:!1}),a=t.time("completing dependencies and dependents",{start:!1}),u=t.time("filling dependencies and dependents",{start:!1}),c=t.time("filling sourcemaps inputs",{start:!1}),d=new Map,l=new Map,p=new Map,f=new Map;return{buildStart(){f.clear(),d.clear(),l.clear(),p.clear()},onLog(t,n){"warn"===t&&e.build.warnings.push(n.message||n.toString())},renderError(t){t&&e.build.errors.push(t.message)},moduleParsed(e){n.resume();const t=zi(e.id),o=f.get(t)||{dependencies:new Set,dependents:new Set},r=Fi(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),i=Fi(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of i)o.dependents.add(e);for(const e of r)o.dependencies.add(e);f.set(t,o),n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,m){o.resume();const h=n.dir?Xn(e.buildRoot,n.dir):e.bundler.outDir,g=new Set,y=new Set,b=new Map;a.resume();for(const[e,{dependencies:t,dependents:n}]of f){for(const n of t){const t=zi(n),o=f.get(t)||{dependencies:new Set,dependents:new Set};o.dependents.has(e)||(o.dependents.add(e),f.set(t,o))}for(const t of n){const n=zi(t),o=f.get(n)||{dependencies:new Set,dependents:new Set};o.dependencies.has(e)||(o.dependencies.add(e),f.set(n,o))}}a.end(),i.resume();for(const[e,n]of Object.entries(m)){const o=Xn(h,e),r="code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),i=l.get(o)||{name:e,filepath:o,inputs:[],size:r,type:Ri(e)};if("map"===i.type&&y.add(i),"modules"in n)for(const[e,t]of Object.entries(n.modules)){if(zi(e)!==e)continue;let n=t.originalLength;if(!n&&0!==n)try{n=s.statSync(e).size}catch(e){n=t.renderedLength}const o=d.get(e)||{name:Li(h,e),dependencies:new Set,dependents:new Set,filepath:e,size:n,type:Ri(e)};i.inputs.push(o),d.set(o.filepath,o)}if("imports"in n)for(const e of n.imports){const n=zi(e);if(!f.has(n)){b.set(Xn(h,n),i);continue}if(d.has(n)){t.debug(`Input report already there for ${n} from ${i.name}.`);continue}const o=d.get(n)||{name:Li(h,e),dependencies:new Set,dependents:new Set,filepath:n,size:0,type:"external"};i.inputs.push(o),d.set(o.filepath,o)}"isEntry"in n&&n.isEntry&&g.add({...i,name:n.name,size:0,outputs:[i]}),l.set(i.filepath,i)}i.end();for(const[e,n]of b){const o=l.get(e);o?n.inputs.includes(o)||n.inputs.push(o):t.debug(`Could not find the output report for ${e}.`)}u.resume();for(const[e,n]of d){const o=f.get(e);if(o){for(const e of o.dependencies){const o=d.get(e);o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${Li(h,e)} of ${n.name}`)}for(const e of o.dependents){const o=d.get(e);o?n.dependents.add(o):t.debug(`Could not find input for dependent ${Li(h,e)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(u.end(),y.size){c.resume();for(const e of y){const n=e.filepath.replace(/\.map$/,""),o=l.get(n);o?e.inputs.push(o):t.debug(`Could not find output for sourcemap ${e.name}`)}c.end()}const w=(e,n=new Map)=>{if(n.has(e))return n;const o=Li(h,e),r=l.get(e);if(!r)return d.has(o)||t.debug(`Could not find output for ${o}`),n;n.set(e,r);const i=m[Li(h,e)];if(!i)return t.debug(`Could not find asset for ${o}`),n;const s=[];"imports"in i&&s.push(...i.imports),"dynamicImports"in i&&s.push(...i.dynamicImports);for(const e of s)w(Xn(h,e),n);return n};r.resume();for(const e of g){const n=w(e.filepath);e.outputs=Array.from(n.values()),e.inputs=Array.from(new Set(e.outputs.flatMap((e=>e.inputs)))),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),p.has(e.filepath)&&t.debug(`Entry "${e.name}":"${Li(h,e.filepath)}" already reported.`),p.set(e.filepath,e)}r.pause(),o.pause()},async closeBundle(){e.build.inputs=Array.from(d.values()),e.build.outputs=Array.from(l.values()),e.build.entries=Array.from(p.values()),r.end(),o.end(),await e.asyncHook("buildReport",e.build)}}},Vi=(e,t,n)=>o=>{let r=[],i=[],s=[];const a=new Map,u=new Map,c=new Map,d=new Map,l=[],p=new Map,f=n.time("build report",{start:!1}),m=e=>!(!e||e.startsWith("webpack/runtime")||e.startsWith("multi ")||X(e)),h=e=>e.replace(/(^external[^"]+"|"$)/g,""),g=e=>{const t=(e=>{const t=e.identifier();return{identifier:()=>t,dependencies:"dependencies"in e?[...e.dependencies]:[],blocks:"blocks"in e?[...e.blocks]:[],externalType:"externalType"in e?e.externalType:void 0,external:"external"in e?e.external:void 0}})(e),n=(e=>{const t=new Set,n=["rawRequest","resource","request","userRequest"],o=e=>{const n=zi(e);t.add(n),n.startsWith("external ")&&t.add(h(n))};o(e.identifier());for(const t of n){const n=e[t];t&&t in e&&"string"==typeof n&&o(n)}return t})(e);for(const e of n)if(d.has(e)){const n=d.get(e);n.dependencies.push(...t.dependencies||[]),n.blocks.push(...t.blocks||[])}else d.set(e,t)},y=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),y(n,t);if("blocks"in e)for(const n of e.blocks)y(n,t);return t},b=(e,t)=>{if("request"in t&&t.request){const n=zi(t.request);if(d.has(n))return d.get(n);if(e.context){const t=Xn(zi(e.context),n);if(d.has(t))return d.get(t)}}},w=e=>!(!("externalType"in e)||!e.externalType)||(!(!("external"in e)||!e.external)||!!e.identifier?.().startsWith("external "));o.hooks.thisCompilation.tap(t,(o=>{r=[],i=[],s=[],a.clear(),u.clear(),d.clear(),p.clear(),o.hooks.finishModules.tap(t,(t=>{f.resume();const o=n.time("dependency graph"),i=n.time("indexing modules");for(const e of t)g(e);i.end();const s=n.time("building inputs");for(const n of t){const t=n.identifier(),o=Li(e.bundler.outDir,t),i=new Set(y(n).map((e=>{const o=b(n,e);if(!o?.identifier())return!1;const r=o.identifier();return!!m(r)&&(r!==t&&(w(o)?h(r):r))})).filter(Boolean));if(!m(t))continue;const s=p.get(t)||{dependents:new Set,dependencies:new Set};for(const e of i){const n=p.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),s.dependencies.add(e),p.set(e,n)}p.set(t,s);const u=w(n)?{size:0,name:h(o),dependencies:new Set,dependents:new Set,filepath:t,type:"external"}:{size:n.size()||0,name:o,dependencies:new Set,dependents:new Set,filepath:t,type:Ri(t)};r.push(u),a.set(t,u),w(n)&&a.set(h(t),u)}s.end();const u=n.time("assigning dependencies and dependents");for(const e of r){const t=p.get(e.filepath);if(t){for(const o of t.dependencies){const t=a.get(o);t?e.dependencies.add(t):n.debug(`Could not find input of dependency ${o}`)}for(const o of t.dependents){const t=a.get(o);t?e.dependents.add(t):n.debug(`Could not find input of dependent ${o}`)}}else n.debug(`Could not find dependency report for ${e.name}`)}u.end(),o.end(),f.pause()}))})),o.hooks.afterEmit.tapPromise(t,(async t=>{f.resume();const o=t.chunks,d=t.getAssets(),p=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Xn(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of o){const t=p(e),n=(g?.getChunkModules(e)||[]).flatMap((e=>"modules"in e&&Array.isArray(e.modules)?e.modules.map((e=>e.identifier())):e.identifier())).filter(m);for(const e of t){if("map"===Ri(e))continue;const t=c.get(e)||new Set;for(const e of n)t.add(e);c.set(e,t)}}h.end();const y=n.time("building outputs");for(const t of d){const o={size:t.source.size()||0,name:t.name,inputs:[],filepath:Xn(e.bundler.outDir,t.name),type:Ri(t.name)};if(u.set(o.filepath,o),i.push(o),"map"===o.type){l.push(o);continue}const r=c.get(o.filepath);if(r)for(const e of r){const t=a.get(e);t?o.inputs.push(t):n.debug(`Could not find input of ${e}`)}else n.debug(`Could not find modules for ${o.name}`)}y.end();const b=n.time("filling sourcemaps inputs");for(const e of l){const t=u.get(e.filepath.replace(/\.map$/,""));t?e.inputs.push(t):n.debug(`Output not found for sourcemap ${e.name}`)}b.end();const w=n.time("building entries"),v=(e,t=new Set)=>{if(t.has(e))return new Set;t.add(e);const n=new Set(e.chunks);for(const o of e.childrenIterable||[]){const e=v(o,t);for(const t of e)n.add(t)}return n};for(const[o,r]of t.entrypoints){const t=new Map,i=new Map;let a=0;const c=v(r),d=Array.from(c).flatMap(p),l=r.chunks.filter((e=>g.getChunkEntryModulesIterable(e)||!1)).flatMap((e=>Array.from(e.files))).filter((e=>e.includes(o)||r.name&&e.includes(r.name))).find((e=>"js"===Ri(e)));for(const e of d){const o=u.get(e);if(e&&o){if("map"!==o.type&&!t.has(o.name)){t.set(o.name,o);for(const e of o.inputs)i.has(e.filepath)||i.set(e.filepath,e);a+=o.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const f={name:o,filepath:l?Xn(e.bundler.outDir,l):"unknown",size:a,inputs:Array.from(i.values()),outputs:Array.from(t.values()),type:l?Ri(l):"unknown"};s.push(f)}w.end();for(const n of t.errors)e.build.errors.push(n.message);for(const n of t.warnings)e.build.warnings.push(n.message);e.build.inputs=r,e.build.outputs=i,e.build.entries=s,f.end(),await e.asyncHook("buildReport",e.build)}))},Ki="datadog-build-report-plugin",Hi=e=>{const{context:t}=e,n=t.getLogger(Ki);return[{name:Ki,enforce:"post",esbuild:Bi(t,n),rspack:Vi(t,Ki,n),webpack:Vi(t,Ki,n),vite:qi(t,n),rollup:qi(t,n)}]},Wi="datadog-bundler-report-plugin",Ji=(e,t)=>t?u.isAbsolute(t)?t:u.resolve(e,t):"",Gi=e=>{if(!e)return[];return(Array.isArray(e)?e:[e]).map((e=>e.dir?e.dir:e.file?u.dirname(e.file):void 0)).filter(Boolean)},Yi=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=Ji(process.cwd(),t.options.output.path)),e.hook("bundlerReport",e.bundler),t.options.context&&(e.buildRoot=t.options.context),e.hook("buildRoot",e.buildRoot)},Qi=e=>({configResolved(t){e.bundler.rawConfig=t;let n=t.build?.outDir??"dist";const o=t.build?.rollupOptions?.output,r=Gi(o);e.buildRoot=t.root??process.cwd(),o&&r.length&&(n=to(r,process.cwd())),e.bundler.outDir=Ji(e.buildRoot,n),e.hook("buildRoot",e.buildRoot),e.hook("bundlerReport",e.bundler)}}),Zi=e=>{const{context:t}=e,n=t.getLogger(Wi);return[{name:Wi,enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.absWorkingDir&&(t.buildRoot=e.initialOptions.absWorkingDir),e.initialOptions.outdir&&(t.bundler.outDir=Ji(t.buildRoot,e.initialOptions.outdir)),e.initialOptions.outfile&&(t.bundler.outDir=Ji(t.buildRoot,u.dirname(e.initialOptions.outfile))),t.hook("buildRoot",t.buildRoot),t.hook("bundlerReport",t.bundler),e.initialOptions.metafile=!0}},webpack:Yi(t),rspack:Yi(t),vite:Qi(t),rollup:{options(e){let n;if("output"in e){const t=Gi(e.output);n=to(t,process.cwd())}const o=(e=>{const t=new Set;if(e.input){const n=Array.isArray(e.input)?e.input:"object"==typeof e.input?Object.values(e.input):[e.input];for(const e of n){if("string"!=typeof e)throw new Error("Invalid input type");t.add(u.dirname(e))}}return Array.from(t)})(e);if(n){t.bundler.outDir=Xn(process.cwd(),n);const e=to([n,...o],process.cwd());t.buildRoot=e===u.sep?process.cwd():e}else t.buildRoot=to(o,process.cwd()),t.bundler.outDir=u.resolve(process.cwd(),"dist");t.hook("buildRoot",t.buildRoot)},buildStart(e){t.bundler.rawConfig=e},renderStart(e){t.bundler.rawConfig.outputs=t.bundler.rawConfig.outputs||[],t.bundler.rawConfig.outputs.push(e),t.hook("bundlerReport",t.bundler);const o=Gi(e);to(o,process.cwd()).startsWith(t.bundler.outDir)||n.warn("The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.")}}}]},Xi="datadog-custom-hooks-plugin",es=e=>{const{context:t}=e,n=t.getLogger(Xi),o=e=>(o,...r)=>{const i=n.time(`execution | ${o}`,{tags:["type:custom-hook",`hook:${o}`]}),s=[],a=[];for(const n of t.plugins){if(!(o in n))continue;const t=n[o];if("function"==typeof t)try{const i=t(...r);i instanceof Promise&&(e||s.push(`Plugin "${n.name}" returned a promise on the non async hook "${o}".`),a.push(i))}catch(e){s.push(`Plugin "${n.name}" errored on hook "${o}". [${e}]`)}else s.push(`Plugin "${n.name}" has an invalid hook type for "${o}". [${typeof t}]`)}if(s.length>0){for(const e of s)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>i.end()))};return t.hook=o(!1),t.asyncHook=o(!0),[{name:Xi,enforce:"pre"}]};class ts{constructor(e){this.trackedFilenames=new Map;for(const t of e){const e=this.getFilename(t),n=this.trackedFilenames.get(e);n?n.push(t):this.trackedFilenames.set(e,new Array(t))}}displaySource(e){return e.length<=40?e:`[...]${e.slice(-35)}`}matchSourcemap(e,t){const n=Ae(e),o=JSON.parse(n);if(!o.sources)return void t("Missing 'sources' field in sourcemap.");const r=o.sources;if(0===r.length)return void t("Empty 'sources' field in sourcemap.");const i=this.matchSources(r);if(0!==i.length)return i;t(`${r.map(this.displaySource).join(", ")} not in the tracked files.`)}matchSources(e){let t=[];const n=new Set;for(const o of e){const e=this.getFilename(o);if(n.has(e))continue;n.add(e);const r=this.trackedFilenames.get(e);r&&(t=t.concat(r))}return t}rawTrackedFilesList(){let e=[];return this.trackedFilenames.forEach((t=>{e=e.concat(t)})),e}getFilename(e){let t=e.lastIndexOf("/");-1===t?t=0:t++;let n=e.lastIndexOf("?");return(-1===n||n<=t)&&(n=e.length),e.substring(t,n)}}const ns=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await os(e);for(const e of t)if(e.name===n)return re(e.refs.push);return re(t[0].refs.push)},os=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},rs=async e=>e.revparse("HEAD"),is=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),ss=async e=>e.branch(),as=async e=>e.show(["-s","--format=%s"]),us=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),cs="datadog-git-plugin",ds=e=>{const{options:t,context:n}=e,o=n.getLogger(cs),r=o.time("get git information",{start:!1}),i=async e=>{try{const t=await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=S(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return S(t)})(u.dirname(e));if(0===(await t.getRemotes(!0)).length)return o.warn("No git remotes available, skipping git plugin. This is expected for a repository that has not been pushed yet."),void r.end();const i=await(async e=>{const t=[rs(e),ss(e),as(e),us(e),is(e),ns(e)],[n,o,r,i,s,a]=await Promise.all(t),[u,c,d,l,p,f]=i.split(",").map((e=>e.trim()));return{commit:{author:{name:u,email:c,date:d},committer:{name:l,email:p,date:f},message:r.trim(),hash:n},hash:n,branch:o.current,remote:a.trim(),trackedFilesMatcher:new ts(s)}})(t);n.git=i,r.end(),await n.asyncHook("git",n.git)}catch(e){o.error(`Could not get git information: ${e.message}`)}};return[{name:cs,enforce:"pre",buildRoot(e){if(te(t))try{r.resume();const t=eo(e,".git");if(!t)return o.warn("No .git directory found, skipping git plugin."),void r.end();n.queue(i(t))}catch(e){o.error(`Could not get git information: ${e.message}`)}}}]},ls="datadog-injection-plugin",ps=/^https?:\/\//,fs=[".mjs",".mjsx",".js",".ts",".tsx",".jsx"],ms=t.bold.yellow,hs=async(e,t=process.cwd())=>(e=>r.readFile(e,{encoding:"utf-8"}))(Xn(t,e));function gs(e){return e.some((e=>e.injectIntoAllChunks))}const ys=(e,t,n)=>{const o=e.filter((e=>e.position===t&&(!n||n.isEntry||e.injectIntoAllChunks))).map((e=>Es(e.value)?e.value(n):e.value)).filter(Boolean);if(0===o.length)return"";return`// begin injection by Datadog build plugins\n${o.map((e=>`(() => {${e}})();`)).join("\n\n")}\n// end injection by Datadog build plugins`},bs=async(e,t,n=process.cwd())=>{const o=Es(e.value)?await e.value():e.value;try{if("file"===e.type){const e=o;return await(e.match(ps)?(async(e,t=5e3)=>{let n;return Promise.race([Y({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,o)=>{n=setTimeout((()=>{o(new Error("Timeout"))}),t)}))])})(e):hs(e,n))}return o}catch(r){const i=`${e.type} - ${oe(o)}`;return e.fallback?(t.debug(`Fallback for "${i}": ${r.toString()}`),bs(e.fallback,t,n)):(t.warn(`Failed "${i}": ${r.toString()}`),"")}},ws=async(e,t,n,o=process.cwd())=>{const r=t.filter(xs).map((e=>{const t=e.value;return{...e,value:e=>t(e.sourceOrHash)}})),i=t.filter((e=>!xs(e))),s=await Promise.all(i.map((async t=>({...t,value:await bs(t,e,o)})))),a=e=>({...e,position:e.position??Te.BEFORE});n.push(...r.map(a),...s.map(a))},vs=e=>e instanceof Error&&"code"in e,$s=e=>fs.includes(e),ks=(e,t,n)=>{e.warn(`"${ms(t)}" files are not supported (${ms(n)}).`)},xs=e=>"function"==typeof e.value&&1===e.value.length,Es=e=>"function"==typeof e,Ss=s.promises,Is=(e,t,n)=>({setup(o){const{onStart:i,onResolve:a,onLoad:c,onEnd:d,esbuild:l,initialOptions:p}=o,f=[],m=`${t.bundler.name}.${Te.MIDDLE}.${O}.js`,g=s.realpathSync(h.tmpdir()),y=u.resolve(g,m),b=new RegExp(`${m}$`),w=p.inject;p.inject=w?[...w]:[],p.inject.push(y),i((async()=>{f.push(...await Ci(o,t,e)),o.initialOptions.inject=w;try{await(async(e,t)=>{await Ie(u.dirname(e)),await r.writeFile(e,t,{encoding:"utf-8"})})(y,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:b},(async e=>({path:e.path,namespace:ls}))),c({filter:b,namespace:ls},(async()=>({contents:ys(n,Te.MIDDLE)||" ",resolveDir:t.buildRoot,loader:"js"}))),d((async o=>{if(!o.metafile)return void e.warn("Missing metafile from build result.");if(!function(e){return e.some((e=>e.position===Te.BEFORE||e.position===Te.AFTER))}(n))return;const r=[];for(const[i,s]of Object.entries(o.metafile.outputs)){const o=Boolean(s.entryPoint&&f.some((e=>e.resolved.endsWith(s.entryPoint))));if(!o&&!gs(n))continue;const a=Xn(t.buildRoot,i),{base:c,ext:d}=u.parse(a);$s(d)?r.push((async()=>{try{const e=`${a}.map`,t=await Ss.readFile(a,"utf-8"),r=await Ss.readFile(e,"utf-8").catch((()=>!1)),i=u.basename(a),s=ys(n,Te.BEFORE,{sourceOrHash:t,fileName:i,isEntry:o}),c=ys(n,Te.AFTER,{sourceOrHash:t,fileName:i,isEntry:o});if(!s&&!c)return;const d=t.replace(/\n?\/\/# sourceMappingURL=.*$/m,""),p=r?`${d}\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(r).toString("base64")}`:d,f=await l.transform(p,{loader:"default",banner:s,footer:c,sourcemap:r?"external":void 0,sourcefile:i});await Promise.all([Ss.writeFile(a,f.code),r&&f.map?Ss.writeFile(e,f.map):null])}catch(t){if(!vs(t)||"ENOENT"!==t.code)throw t;e.warn(`Could not inject content in ${a}: ${t}`)}})()):ks(e,d,c)}await Promise.all(r)}))}}),Ds=O,As="?inject-proxy",Ps=(e,t)=>({renderChunk(n,o){const{base:r,ext:i}=u.parse(o.fileName);if(!$s(i))return ks(e,i,r),null;const s=ys(t,Te.BEFORE,{sourceOrHash:n,fileName:o.fileName,isEntry:o.isEntry}),a=ys(t,Te.AFTER,{sourceOrHash:n,fileName:o.fileName,isEntry:o.isEntry});if(!s&&!a)return null;const c=new I(n);return s&&c.prepend(`${s}\n`),a&&c.append(`\n${a}`),{code:c.toString(),map:c.generateMap({file:o.fileName,hires:"boundary"})}},async resolveId(e,n,o){if(X(e))return{id:e,moduleSideEffects:!0};if(o.isEntry&&ys(t,Te.MIDDLE)){if(e.endsWith(".html"))return null;const t=await this.resolve(e,n,o);if(!t||t.external)return t;return(await this.load(t)).moduleSideEffects=!0,`${t.id}${As}`}return null},load(e){if(X(e))return ys(t,Te.MIDDLE);if(e.endsWith(As)){const t=e.slice(0,-13),n=this.getModuleInfo(t);let o=`import ${JSON.stringify(Ds)};\nexport * from ${JSON.stringify(t)};`;return n?.hasDefaultExport&&(o+=`export { default } from ${JSON.stringify(t)};`),o}return null}}),js=(e,t,n,o,r)=>i=>{const a=new WeakMap,c=e.sources.ConcatSource,d=n.bundler.name,l=u.resolve(n.buildRoot,"node_modules",".cache","datadog-build-plugins",`${d}.${Te.MIDDLE}.${O}.js`);De(l,"");i.hooks.shutdown.tap(ls,(()=>{var e;e=l,s.rmSync(e,{force:!0,maxRetries:3,recursive:!0})}));const p=async()=>{await ws(t,o,r,n.buildRoot)};i.hooks.beforeRun.tapPromise(ls,p),i.hooks.watchRun.tapPromise(ls,p),i.hooks.compilation.tap(ls,(n=>{const o=e.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;n.hooks.processAssets.tap({name:ls,stage:o},(()=>{for(const e of n.chunks){const o=e.canBeInitial(),i=e.contentHash?.javascript??e.hash;for(const s of e.files){const{base:e,ext:d}=u.parse(s);if(!$s(d)){ks(t,d,e);continue}const l=u.basename(s),p=ys(r,Te.BEFORE,{sourceOrHash:i,fileName:l,isEntry:o}),f=ys(r,Te.AFTER,{sourceOrHash:i,fileName:l,isEntry:o});""===p&&""===f||n.updateAsset(s,(e=>{const t=a.get(e);if(!t||t.banner!==p||t.footer!==f){const t=new c(p,"\n",e,"\n",f);return a.set(e,{source:t,banner:p,footer:f}),t}return t.source}))}}}))}));const f=(e=>{const n={import:[l]},o=e=>{for(const[n,o]of Object.entries(e))"object"==typeof o?(o.import=o.import||[],o.import.unshift(l)):"string"==typeof o?e[n]=[l,o]:Array.isArray(o)?o.unshift(l):t.error("Invalid entry type: "+typeof o)};return e?"function"==typeof e?async()=>{const t=await e();return o(t),t}:"object"!=typeof e?"string"==typeof e?[n,e]:(t.error("Invalid entry type: "+typeof e),e):(o(e),e):{ddHelper:n}})(i.options.entry);i.options.entry=f},Ms=e=>{const{bundler:t,context:n}=e,o=n.getLogger(ls),r=[],i=[];n.inject=e=>{r.push(e)};const s={name:ls,enforce:"post",esbuild:Is(o,n,i),webpack:js(t,o,n,r,i),rspack:js(t,o,n,r,i),rollup:Ps(o,i),vite:{...Ps(o,i),enforce:"pre",transformIndexHtml:{order:"pre",handler:()=>ys(i,Te.MIDDLE)?[{tag:"script",attrs:{type:"module",src:"/@id/__datadog-helper-file"},injectTo:"head-prepend"}]:[]}}};var a;return a=n.bundler.name,["rspack","webpack"].includes(a)?s.load={filter:{id:N},handler:()=>({code:ys(i,Te.MIDDLE)})}:s.buildStart=async()=>{await ws(o,r,i,n.buildRoot)},[s]},Ts="datadog-true-end-plugin",Cs=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},o=async()=>{await t.asyncHook("flush")},r=()=>{t.hook("syncTrueEnd")},i=async()=>{r(),await n(),await o()},s=e=>{e.hooks.shutdown.tapPromise(Ts,i)},a={async writeBundle(){},async closeBundle(){await i()}};return[{name:Ts,enforce:"post",webpack:s,esbuild:{setup(e){e.onEnd((async()=>{await n(),await o()})),e.onDispose((()=>{r()}))}},vite:a,rollup:a,rspack:s}]},Os={[Cr]:ui},Ns=t.bold.red;var Rs="3.2.6-dev.1";const _s=(({bundler:t,version:n})=>{const o=Date.now();return e(((e,r)=>{const i=Date.now(),s=((e={})=>{const t=(e=>{const t=[];return void 0===e||void 0!==e.version&&"string"!=typeof e.version&&t.push("metadata.version must be a string"),t})(e.metadata),n=q("SITE"),o={site:K(n,"DATADOG_SITE/DD_SITE",t)??K(e.auth?.site,"auth.site",t)??F};if(t.length)throw new Error(`Invalid Datadog plugin configuration:\n - ${t.join("\n - ")}`);return Object.defineProperty(o,"apiKey",{value:q("API_KEY")||e.auth?.apiKey,enumerable:!1}),Object.defineProperty(o,"appKey",{value:q("APP_KEY")||e.auth?.appKey,enumerable:!1}),{enableGit:!0,logLevel:"warn",metadata:{},...e,auth:o}})(e);"esbuild"===r.framework&&(r.esbuildHostName=z);const a=process.env.BUILD_PLUGINS_ENV||"production",u=R.includes(a)?a:"development",c=t.rspackVersion||t.version||t.VERSION,d=r.framework,l={bundler:{name:d,version:c},env:u,metadata:s.metadata||{},packageName:`@datadog/${d}-plugin`,version:n},p={errors:[],logs:[],metrics:new Set,queue:[],timings:[],warnings:[]},f=(({start:e,options:t,data:n,stores:o})=>{const r=process.cwd(),i={errors:o.errors,warnings:o.warnings,logs:o.logs,metadata:n.metadata,timings:o.timings,bundler:n.bundler};return{addMetric:()=>{throw new Error("AddMetric function called before it was initialized.")},auth:t.auth,pluginNames:[],bundler:{...i.bundler,outDir:r},build:i,buildRoot:r,env:n.env,getLogger:le(n,o,t.logLevel),asyncHook:()=>{throw new Error("AsyncHook function called before it was initialized.")},hook:()=>{throw new Error("Hook function called before it was initialized.")},inject:()=>{throw new Error("Inject function called before it was initialized.")},plugins:[],queue:()=>{throw new Error("Queue function called before it was initialized.")},sendLog:Q(n),start:e,version:n.version}})({start:o,options:s,data:l,stores:p}),m=f.getLogger("factory"),h=m.time("Plugins initialization",{start:i});f.pluginNames.push(z);const g=[];g.push(["analytics",ji],["async-queue",Ti],["build-report",Hi],["bundler-report",Zi],["custom-hooks",es],["git",ds],["injection",Ms],["true-end",Cs]),s.customPlugins&&g.push(["custom",s.customPlugins]);const y=[["apps",ye,$o],["error-tracking",ko,Bo],["live-debugger",qo,Mr],["metrics",Cr,ci],["output",di,gi],["rum",yi,Ai]];for(const[e,t,n]of y)ge(s,t,m)&&g.push([e,n]);for(const[e,n]of g)f.plugins.push(...me(f,n,e)({bundler:t,context:f,options:s,data:l,stores:p}));return(e=>{const t=[];for(const n of B){const o=V(n);if(o.length>1&&!o.every((e=>process.env[e]===process.env[o[0]]))){const r=o.map((e=>U(e))).join(" and "),i=U(`DATADOG_${n}`);e.warn(`Conflicting keys ${r}, will use ${i}`),t.push(`${r} (using ${i})`)}else if(o.length){const e=o.map((e=>L(e))).join(" and ");t.push(`${e} (same value)`)}}t.length&&e.info(`Overrides from environment:\n - ${t.join("\n - ")}`)})(m),f.pluginNames.push(...f.plugins.map((e=>e.name))),(e=>{const t=new Set(e.filter((t=>e.filter((e=>e===t)).length>1)));if(t.size>0)throw new Error(`Duplicate plugin names: ${Ns(Array.from(t).join(", "))}`)})(f.pluginNames),f.hook("init",f),h.end(),f.plugins}))})({bundler:D,version:Rs}).esbuild,Fs=Rs,zs=Os;export{_s as datadogEsbuildPlugin,zs as helpers,Fs as version};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|