@datadog/webpack-plugin 2.6.4 → 2.6.5-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{createUnplugin as e}from"unplugin";import t from"chalk";import n from"async-retry";import{File as s}from"buffer";import o from"fs/promises";import r from"fs";import i from"path";import{Readable as a}from"stream";import{outdent as u}from"outdent";import c from"p-queue";import{createGzip as p}from"zlib";import{instrument as l}from"@datadog/js-instrumentation-wasm";import{createFilter as d}from"@rollup/pluginutils";import m from"pretty-bytes";import{performance as f}from"perf_hooks";import{glob as g}from"glob";import{simpleGit as h}from"simple-git";import y from"os";import{createRequire as w}from"module";import b from"webpack";
1
+ import{createUnplugin as e}from"unplugin";import t from"chalk";import n from"async-retry";import{outdent as o}from"outdent";import s from"path";import{File as r}from"buffer";import i from"fs/promises";import a from"fs";import{Readable as u}from"stream";import p from"p-queue";import{createGzip as c}from"zlib";import l from"pretty-bytes";import{performance as d}from"perf_hooks";import{instrument as m}from"@datadog/js-instrumentation-wasm";import{glob as f}from"glob";import{simpleGit as h}from"simple-git";import g from"os";import y from"webpack";
2
2
  // -- Shims --
3
3
  import cjsUrl from 'node:url';
4
4
  import cjsPath from 'node:path';
@@ -6,8 +6,8 @@ import cjsModule from 'node:module';
6
6
  const __filename = cjsUrl.fileURLToPath(import.meta.url);
7
7
  const __dirname = cjsPath.dirname(__filename);
8
8
  const require = cjsModule.createRequire(import.meta.url);
9
- const v="__datadog-helper-file",$=["development","production","test"],k="datadog-build-plugins",S=[400,403,413],E=e=>{const{auth:t,url:s,method:o="GET",getData:r,type:i="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:o,duplex:"half"};let n={"X-Datadog-Origin":"build-plugins"};if(t?.apiKey&&(n["DD-API-KEY"]=t.apiKey),t?.appKey&&(n["DD-APPLICATION-KEY"]=t.appKey),"function"==typeof r){const{data:t,headers:s}=await r();e.body=t,n={...n,...s}}a=await fetch(s,{...e,headers:n})}catch(t){return e(t),{}}if(!a.ok){const t=`HTTP ${a.status} ${a.statusText}`;if(S.includes(a.status))return e(new Error(t)),{};throw new Error(t)}try{let e;return e="json"===i?await a.json():await a.text(),e}catch(t){return e(t),{}}}),a)},D=e=>({message:t,context:n})=>E({retries:2,minTimeout:100,url:"https://browser-http-intake.logs.datadoghq.com/v1/input/pub44d5f4eb86e1392037b7501f7adc540e",method:"POST",type:"json",getData:async()=>{const s={ddsource:e.packageName||k,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(s),headers:{"Content-Type":"application/json"}}}}),x=async(e,t)=>{await(async e=>o.mkdir(e,{recursive:!0}))(i.dirname(e)),await o.writeFile(e,t,{encoding:"utf-8"})},M=(e,t)=>{var n;n=i.dirname(e),r.mkdirSync(n,{recursive:!0}),r.writeFileSync(e,t,{encoding:"utf-8"})},P=e=>{try{return r.existsSync(e)}catch(e){if("ENOENT"===e.code)return!1;throw e}},T=async(e,t)=>{if("function"==typeof r.openAsBlob){const n=await r.openAsBlob(e,{type:t.contentType});return new s([n],t.filename)}{const n=a.toWeb(r.createReadStream(e)),o=await new Response(n).blob();return new s([o],t.filename,{type:t.contentType})}},j=async e=>{const t={empty:!1,exists:!0};try{const{size:n}=await o.stat(e);0===n&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t},N=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),O=e=>e.includes(v),z=e=>{const t=Math.floor(e/1e3/60/60/24),n=new Date(e-24*t*60*60*1e3),s=n.getUTCHours(),o=n.getUTCMinutes(),r=n.getUTCSeconds(),i=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${s?`${s}h `:""}${o?`${o}m `:""}${r?`${r}s`:""}`.trim();return`${a}${!a||i?` ${i}ms`:""}`.trim()},R=(e,t=60,n="[...]")=>{if(e.length<=t)return e;const s=Math.max(4,t-n.length),o=Math.min(10,Math.floor(s/2)),r=s-o;return`${e.slice(0,o)}${n}${e.slice(-r)}`},I=(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}};let A=0;const C={debug:0,info:1,warn:2,error:3,none:4},F=e=>e.split(">").map(N).join(">"),L=(e,n,s,o)=>{const r=F(e);return(i,a="debug",{forward:u}={})=>{let c=t.dim,p=console.log;"error"===a?(c=t.red,p=console.error):"warn"===a?(c=t.yellow,p=console.warn):"info"===a&&(c=t.cyan,p=console.log);const l=`[${n.metadata?.name?`${n.metadata.name}|`:""}${a}|${n.bundler.fullName}|${r}]`,d="string"==typeof i?i:JSON.stringify(i,null,2);if(s.logs.push({bundler:n.bundler.fullName,pluginName:e,type:a,message:d,time:Date.now()}),"error"===a&&s.errors.push(d),"warn"===a&&s.warnings.push(d),u){const t=async()=>{try{const t=D(n);await t({message:d,context:{plugin:e,status:a}})}catch(t){L(e,n,s,o)(`Error forwarding log: ${t}`,"debug")}};s.queue.push(t())}C[a]>=C[o]&&p(`${c(l)} ${d}`)}},_=(e,n,s)=>(o,r={})=>{const{level:i="debug",start:a=!0,log:u=!0,tags:c=[]}=r,p={pluginName:e,label:o,spans:[],tags:[...c,`plugin:${e}`,`level:${i}`],logLevel:i,total:0};n.push(p);const l=()=>p.spans.filter((e=>!e.end)),d=n=>{l().length||(!p.spans.length&&u&&s(t.dim(`[${t.cyan(o)}] : start`),"debug"),p.spans.push({start:n||Date.now(),tags:[`plugin:${e}`]}))},m=(e,n=!0)=>{const r=l();if(r?.length){r.length>1&&s(`Timer ${t.cyan(o)} has more than one ongoing span.`,"debug");for(const t of r)t.end=e||Date.now()}else n&&s(`Timer ${t.cyan(o)} cannot be paused, no ongoing span.`,"debug")};if(a){let e;"number"==typeof a&&(e=a),d(e)}return{timer:p,resume:d,end:e=>{m(e,!1);const n=p.spans.reduce(((e,t)=>e+(t.end-t.start)),0);p.total=n,u&&s(`[${t.cyan(o)}] : ${t.cyan(z(n))}`,i)},pause:m,tag:(e,t={})=>{const{span:n=!1}=t;if(n){const t=l();for(const n of t)n.tags.push(...e)}else p.tags.push(...e)}}},q=(e,t,n="warn")=>s=>{const o=L(s,e,t,n);return{getLogger:o=>q(e,t,n)(`${F(s)}>${o}`),time:_(s,t.timings,o),error:(e,t)=>o(e,"error",t),warn:(e,t)=>o(e,"warn",t),info:(e,t)=>o(e,"info",t),debug:(e,t)=>o(e,"debug",t)}},H=["buildEnd","buildStart","load","loadInclude","resolveId","transform","transformInclude","watchChange","writeBundle","cwd","init","buildReport","bundlerReport","git"],K=(e,t,n,s)=>(...o)=>{const r=s.time(`${e} | ${t}`,{log:!1,tags:["type:hook",`hook:${t}`]}),i=n(...o);return i instanceof Promise?i.finally((()=>{r.end()})):(r.end(),i)},B=(e,t,n)=>{const s=e.getLogger(k);return e=>{const o=s.time(`hook | init ${n}`,{log:!1}),r=t(e).map((e=>((e,t)=>{const n={...e},s=N(e.name);for(const o of H){const r=e[o];r&&(n[o]=K(s,o,r,t))}return n})(e,s))),i=r.map((e=>`plugin:${e.name}`));return o.tag(i),o.end(),r}},W="errorTracking",U="datadog-error-tracking-plugin",G=(e,n,s)=>{if(".map"!==i.extname(s))throw new Error(`The file ${t.green.bold(s)} is not a sourcemap.`);const o=s.replace(/\.map$/,""),r=i.relative(n,o),a=((e,t)=>{if(e.startsWith("/"))return i.join(e,t);try{const n=e.replace(/\/*$/,"/"),s=new URL(n),o=t.replace(/^[\\/]*/,"");return new URL(o,s).href}catch{return`${e}${t}`}})(e,r);return{minifiedFilePath:o,minifiedUrl:a,relativePath:r}},J=/[/]+|[\\]+/g,V=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,Q=(e,t)=>{const n=e.replace(V,"").split(J),s=t.replace(V,"").split(J),o=n.join("/");let r="";for(let e=0;e<s.length;e+=1){const t=s.slice(-e).join("/");o.startsWith(t)&&(r=t)}return r},Y=async(e,t,n,s)=>{const o=await(async(e,t)=>{const[n,s]=await Promise.all([j(e.minifiedFilePath),j(e.sourcemapFilePath)]);return{file:n,sourcemap:s,repeatedPrefix:Q(e.relativePath,t)}})(e,n),r=[],a=[],u=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(s)try{u.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:s.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{a.push(`${i.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:s.hash,repository_url:s.remote}],version:1})})}catch(t){a.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return o.file.empty&&r.push(`Minified file is empty: ${e.minifiedFilePath}`),o.file.exists||r.push(`Minified file not found: ${e.minifiedFilePath}`),o.sourcemap.empty&&r.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),o.sourcemap.exists||r.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),o.repeatedPrefix&&a.push(`The minified file path contains a repeated pattern with the minified path prefix: ${o.repeatedPrefix}`),{content:u,errors:r,warnings:a}},X=t.green.bold,Z=t.yellow.bold,ee=t.red.bold,te=(e,t={})=>async()=>{const n=new FormData,s=p();for(const[t,s]of e.content){const e="file"===s.type?await T(s.path,s.options):new Blob([s.value],{type:s.options.contentType});n.append(t,e,s.options.filename)}const o=new Request("fake://url",{method:"POST",body:n});return{data:a.fromWeb(o.body).pipe(s),headers:{"Content-Encoding":"gzip",...t,...Object.fromEntries(o.headers.entries())}}},ne=async(e,t,n,s)=>{const o=Date.now(),r=t.minifiedPathPrefix,i={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=await Promise.all(e.map((e=>Y(e,i,r,n.git)))),u=a.map((e=>e.errors)).flat(),p=a.map((e=>e.warnings)).flat();if(p.length>0&&s.warn(`Warnings while preparing payloads:\n - ${p.join("\n - ")}`),u.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${u.join("\n - ")}`;if(s.error(e),!0===t.bailOnError)throw new Error(e);return}const{errors:l,warnings:d}=await(async(e,t,n,s)=>{const o=[],r=[];if(!n.apiKey)return o.push({error:new Error("No authentication token provided")}),{errors:o,warnings:r};if(0===e.length)return r.push("No sourcemaps to upload"),{errors:o,warnings:r};const i=new(c.default?c.default:c)({concurrency:t.maxConcurrency}),a={"DD-EVP-ORIGIN":`${n.bundlerName}-build-plugin_sourcemaps`,"DD-EVP-ORIGIN-VERSION":n.version},u=[];for(const c of e){const e={sourcemap:c.content.get("source_map")?.path.replace(n.outDir,"."),file:c.content.get("minified_file")?.path.replace(n.outDir,".")};s.debug(`Queuing ${X(e.sourcemap)} | ${X(e.file)}`),u.push(i.add((async()=>{try{await E({auth:{apiKey:n.apiKey},url:t.intakeUrl,method:"POST",getData:te(c,a),onRetry:(t,n)=>{const o=`Failed to upload ${Z(e.sourcemap)} | ${Z(e.file)}:\n ${t.message}\nRetrying ${n}/5`;r.push(o),s.debug(o)}}),s.debug(`Sent ${X(e.sourcemap)} | ${X(e.file)}`)}catch(n){if(o.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}return await Promise.all(u),await i.onIdle(),{warnings:r,errors:o}})(a,t,{apiKey:n.apiKey,bundlerName:n.bundlerName,version:n.version,outDir:n.outDir},s);if(s.info(`Done uploading ${X(e.length.toString())} sourcemaps in ${X(z(Date.now()-o))}.`),l.length>0){const e=`Failed to upload some sourcemaps:\n${` - ${l.map((({metadata:e,error:t})=>e?`${ee(e.file)} | ${ee(e.sourcemap)} : ${t.message}`:t.message)).join("\n - ")}`}`;if(s.error(e),!0===t.bailOnError)throw new Error(e)}d.length>0&&s.warn(`Warnings while uploading sourcemaps:\n - ${d.join("\n - ")}`)},se=async(e,n,s)=>{const o=t.green.bold,r=Object.entries(e.sourcemaps).map((([e,t])=>` - ${e}: ${o(t.toString())}`)).join("\n"),i=s.time("get sourcemaps files"),a=((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=>({...G(e.minifiedPathPrefix,t.outDir,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,{outDir:n.outDir,outputs:n.outputs});i.end();const c=u`
10
- Uploading ${o(a.length.toString())} sourcemaps with configuration:
11
- ${r}
12
- `;s.info(c);const p=s.time("send sourcemaps");await ne(a,e.sourcemaps,{apiKey:n.apiKey,bundlerName:n.bundlerName,git:n.git,outDir:n.outDir,version:n.version},s),p.end()},oe=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,re=e=>{const n=t.bold.red,s=e[W]||{},o={errors:[]};if(s.sourcemaps){s.sourcemaps.releaseVersion||o.errors.push(`${n("sourcemaps.releaseVersion")} is required.`),s.sourcemaps.service||o.errors.push(`${n("sourcemaps.service")} is required.`),s.sourcemaps.minifiedPathPrefix||o.errors.push(`${n("sourcemaps.minifiedPathPrefix")} is required.`),s.sourcemaps.minifiedPathPrefix&&((e=>{let t;try{t=new URL(e).host}catch{}return!(!t&&!e.startsWith("/"))})(s.sourcemaps.minifiedPathPrefix)||o.errors.push(`${n("sourcemaps.minifiedPathPrefix")} must be a valid URL or start with '/'.`));const e={bailOnError:!1,disableGit:!1,dryRun:!1,maxConcurrency:20,intakeUrl:process.env.DATADOG_SOURCEMAP_INTAKE_URL||s.sourcemaps.intakeUrl||oe,...s.sourcemaps};o.config=e}return o},ie=({options:e,context:t})=>{const n=t.getLogger(U),s=n.time("validate options"),o=((e,t)=>{const n=[],s=re(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${U}.`);const o={disabled:!e[W],...e[W],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return s.end(),o.disabled?[]:[{name:U,enforce:"post",async buildReport(e){if(!o.disabled&&o.sourcemaps){const s=n.time("sourcemaps process");await se(o,{apiKey:t.auth?.apiKey,bundlerName:t.bundler.fullName,git:t.git,outDir:t.bundler.outDir,outputs:e.outputs,version:t.version},n),s.end()}}}]};var ae=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(ae||{});const ue="rum",ce="datadog-rum-plugin",pe="datadog-rum-privacy-plugin";const le=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,de=(e,t)=>{const n=e.sdk;if(n.clientToken)return le(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 s;try{const e=await E({url:`https://api.datadoghq.com/api/v2/rum/applications/${n.applicationId}`,type:"json",auth:t.auth});s=e.data?.attributes?.client_token}catch(e){throw new Error(`Could not fetch the clientToken: ${e.message}`)}if(!s)throw new Error("Missing clientToken in the API response.");return le({...e,sdk:{clientToken:s,...n}})}},me=e=>{const n=t.bold.red,s=e[ue]||{},o={errors:[]};if(!s.sdk)return o;s.sdk.applicationId||o.errors.push(`Missing ${n("applicationId")} in the SDK configuration.`),e.auth?.apiKey&&e.auth?.appKey||s.sdk.clientToken||o.errors.push(`Missing ${n('"auth.apiKey"')} and/or ${n('"auth.appKey"')} to fetch missing client token.`);return o.config={applicationId:"unknown_application_id",allowUntrustedEvents:!1,compressIntakeRequests:!1,defaultPrivacyLevel:"mask",enablePrivacyForActionName:!1,sessionReplaySampleRate:0,sessionSampleRate:100,silentMultipleInit:!1,site:"datadoghq.com",startSessionReplayRecordingManually:!1,storeContextsAcrossPages:!1,telemetrySampleRate:20,traceSampleRate:100,trackingConsent:"granted",trackLongTasks:!1,trackResources:!1,trackUserInteractions:!1,trackViewsManually:!1,...s.sdk},o},fe=e=>{const t=e[ue]||{},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},ge=({options:e,context:t})=>{const n=((e,t)=>{const n=[],s=me(e),o=fe(e);if(n.push(...s.errors),n.push(...o.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${ce}.`);const r={disabled:!e[ue],...e[ue],sdk:void 0,privacy:void 0};return s.config&&(r.sdk=s.config),o.config&&(r.privacy=o.config,t.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(r.privacy,((e,t)=>t instanceof RegExp?t.toString():t))}`,{forward:!0})),r})(e,t.getLogger(ce)),s=[];if(n.disabled)return s;if(n.sdk&&(t.inject({type:"file",position:ae.MIDDLE,value:i.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:ae.MIDDLE,value:de(n,t)})),n.privacy){t.inject({type:"file",position:ae.BEFORE,value:i.join(__dirname,"./privacy-helpers.js")});const e=((e,t)=>{const n=t.getLogger(pe),s=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),o=d(e.include,e.exclude);return{name:pe,enforce:"post",transformInclude:e=>o(e),async transform(e,t){try{return l({id:t,code:e},s)}catch(t){return n.error(`Instrumentation Error: ${t}`,{forward:!0}),{code:e}}}}})(n.privacy,t);s.push(e)}return s},he="telemetry",ye="datadog-telemetry-plugin",we=[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};return/(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),e.value>t[e.type]?e:null}],be=(e,t)=>({type:"gauge",tags:[...e.tags,...t.tags],metric:`${t.prefix?`${t.prefix}.`:""}${e.metric}`,points:[[t.timestamp,e.value]]}),ve=(e="")=>e.endsWith("/")?e:`${e}/`,$e=(e,t)=>{let n=e;return e.split(ve(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},ke=(e,t)=>e.split("!").pop().replace(ve(t),"./"),Se=(e,t,n)=>{let s=e.name||e.userRequest;return s||(s=((e,t)=>{let n=e.userRequest;if(!n){let s;s=t.moduleGraph&&"function"==typeof t.moduleGraph.getIssuer?t.moduleGraph.getIssuer(e):e.issuer,n=s?.userRequest,n||(n=e._identifier?.split("!").pop())}return n||"unknown"})(e,t)),ke(s||"no-name",n)},Ee=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),De=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),xe=(e,t,n,s)=>{const o=new Set;if(s){const{timings:e}=s;e&&(e.tapables&&((e,t)=>{t.add({metric:"plugins.count",type:"count",value:e.size,tags:[]});for(const n of e.values()){let e=0,s=0;for(const o of Object.values(n.events)){let r=0;s+=o.values.length;for(const t of o.values){const n=t.end-t.start;r+=n,e+=n}t.add({metric:"plugins.hooks.duration",type:"duration",value:r,tags:[`pluginName:${n.name}`,`hookName:${o.name}`]}).add({metric:"plugins.hooks.increment",type:"count",value:o.values.length,tags:[`pluginName:${n.name}`,`hookName:${o.name}`]})}t.add({metric:"plugins.duration",type:"duration",value:e,tags:[`pluginName:${n.name}`]}).add({metric:"plugins.increment",type:"count",value:s,tags:[`pluginName:${n.name}`]})}})(e.tapables,o),e.loaders&&((e,t)=>{t.add({metric:"loaders.count",type:"count",value:e.size,tags:[]});for(const n of e.values())t.add({metric:"loaders.duration",type:"duration",value:n.duration,tags:[`loaderName:${n.name}`]}).add({metric:"loaders.increment",type:"count",value:n.increment,tags:[`loaderName:${n.name}`]})})(e.loaders,o))}((e,t)=>{const n=e.inputs||[],s=e.outputs||[],o=e.entries||[],r=e.warnings.length,i=e.errors.length,a=e.duration,u=new Map,c=new Map,p=new Map;for(const e of o){for(const t of e.inputs)u.has(t.filepath)||u.set(t.filepath,[]),u.get(t.filepath).push(e.name);for(const t of e.outputs){const n=t.filepath.replace(/\.map$/,"");p.has(n)||p.set(n,[]),p.get(n).push(e.name)}}for(const e of s)for(const t of e.inputs)c.has(t.filepath)||c.set(t.filepath,[]),c.get(t.filepath).push(e.name);t.add({metric:"assets.count",type:"count",value:s.length,tags:[]}).add({metric:"entries.count",type:"count",value:o.length,tags:[]}).add({metric:"errors.count",type:"count",value:i,tags:[]}).add({metric:"modules.count",type:"count",value:n.length,tags:[]}).add({metric:"warnings.count",type:"count",value:r,tags:[]}),a&&t.add({metric:"compilation.duration",type:"duration",value:a,tags:[]});for(const e of n){const n=[`moduleName:${e.name}`,`moduleType:${e.type}`];u.has(e.filepath)&&n.push(...u.get(e.filepath).map((e=>`entryName:${e}`))),c.has(e.filepath)&&n.push(...c.get(e.filepath).map((e=>`assetName:${e}`))),t.add({metric:"modules.size",type:"size",value:e.size,tags:n}).add({metric:"modules.dependencies",type:"count",value:e.dependencies.size,tags:n}).add({metric:"modules.dependents",type:"count",value:e.dependents.size,tags:n})}for(const e of s){const n=[`assetName:${e.name}`,`assetType:${e.type}`],s=e.filepath.replace(/\.map$/,"");p.has(s)&&n.push(...p.get(s).map((e=>`entryName:${e}`))),t.add({metric:"assets.size",type:"size",value:e.size,tags:n}).add({metric:"assets.modules.count",type:"count",value:e.inputs.length,tags:n})}for(const e of o){const n=[`entryName:${e.name}`];t.add({metric:"entries.size",type:"size",value:e.size,tags:n}).add({metric:"entries.modules.count",type:"count",value:e.inputs.length,tags:n}).add({metric:"entries.assets.count",type:"count",value:e.outputs.length,tags:n})}})(e,o);for(const e of o)if(t.filters?.length){let s=e;for(const n of t.filters){if(!s)break;s=n(e)}s&&n.add(be(s,t))}else n.add(be(e,t));n.add(be({metric:"metrics.count",type:"count",value:n.size+1,tags:[]},t))},Me=async(e,t,n,s)=>{if("string"!=typeof t&&"object"!=typeof t&&!t)return;const{report:o,metrics:r}=e,a=Date.now();let u="";const c={timings:!0,metrics:!0};"object"==typeof t?(u=t.destination,c.timings=t.timings||!1,c.metrics=t.metrics||!1):"string"==typeof t&&(u=t);const p=i.resolve(s,u);try{const e={},t={};c.timings&&o?.timings&&(t.timings={content:{tapables:o.timings.tapables?Array.from(o.timings.tapables.values()):null,loaders:o.timings.loaders?Array.from(o.timings.loaders.values()):null,modules:o.timings.modules?Array.from(o.timings.modules.values()):null}}),c.metrics&&(t.metrics={content:Array.from(r)});const s=Object.entries(t).map((async([t,s])=>{const o=Date.now();n.debug(`Start writing ${t}.json.`);try{await(async(e,t)=>{const n=JSON.stringify(t,null,4);return x(e,n)})(i.join(p,`${t}.json`),s.content),n.debug(`Wrote ${t}.json in ${z(Date.now()-o)}`)}catch(s){n.error(`Failed to write ${t}.json in ${z(Date.now()-o)}`),e[t]=s}}));await Promise.all(s),n.debug(`Wrote files in ${z(Date.now()-a)}.`);const u=Object.keys(e);u.length&&n.error(`Couldn't write files.\n${u.map((t=>` - ${t}: ${e[t].toString()}`))}`)}catch(e){n.error(`Couldn't write files. ${e}`)}},Pe=t.bold.red,Te=t.bold.cyan,je=e=>(t,n)=>{let s,o;return"function"==typeof e?(s=e(t),o=e(n)):(s=t[e],o=n[e]),s>o?-1:s<o?1:0},Ne=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(je("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:z(e.duration)}))),top:!0};n.sort(je("increment"));const o={name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0};return[s,o]},Oe=(e,t,n)=>{const s=[];var o;n&&(s.push(...Ne("Loader",n.timings.loaders)),s.push(...Ne("Tapable",n.timings.tapables)),s.push(...Ne("Module",n.timings.modules))),s.push(...(e=>{const t={name:"Module total dependents",values:[],top:!0},n={name:"Module total dependencies",values:[],top:!0},s={name:"Module size",values:[],top:!0},o={name:"Module aggregated size",values:[],top:!0},r=new Set,i=(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})(e.build),a=new Map,u=new Map,c=new Map;for(const e of i.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,s=c.get(e)||new Set;let o=t.size;for(const e of n)o+=a.get(e)?.size||0;r.add({name:t.name,size:t.size,aggregatedSize:o,dependents:s,dependencies:n})}if(!r.size)return[t,n,s];const p=Array.from(r);return p.sort(je((e=>e.dependents.size))),t.values=p.map((e=>({name:e.name,value:e.dependents.size.toString()}))),p.sort(je((e=>e.dependencies.size))),n.values=p.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),p.sort(je("size")),s.values=p.map((e=>({name:e.name,value:m(e.size)}))),p.sort(je("aggregatedSize")),o.values=p.map((e=>({name:e.name,value:m(e.aggregatedSize||e.size)}))),[t,n,s,o]})(e)),s.push(...(o=e,[{name:"Asset size",values:(o.build.outputs||[]).filter((e=>"map"!==e.type)).sort(je((e=>e.size))).map((e=>({name:e.name,value:m(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(je((e=>e.size))).map((e=>({name:e.name,value:m(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(je((e=>e.size))).map((e=>({name:e.name,value:e.inputs.length.toString()})))||[],top:!0}])),s.push(...(e=>{const t={name:"General Numbers",values:[],top:!1},n=e.build.inputs?e.build.inputs.length:0,s=e.build.outputs?e.build.outputs.length:0,o=e.build.warnings.length,r=e.build.errors.length,i=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:z(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:z(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:z(e.build.writeDuration)}),t.values.push({name:"Number of modules",value:n.toString()},{name:"Number of assets",value:s.toString()},{name:"Number of entries",value:i.toString()},{name:"Number of warnings",value:o.toString()},{name:"Number of errors",value:r.toString()}),[t]})(e));const r=(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=R(e.name,60)}const n=Math.max(...e.map((e=>e.name.length))),s=Math.max(...e.flatMap((e=>e.values.map((e=>e.name.length))))),o=Math.max(...e.flatMap((e=>e.values.map((e=>e.value.length))))),r=Math.max(n+4,s+o+4);for(const n of e){if(0===n.values.length)continue;const e=r-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=o-e.value.length;t+=` [${Pe(e.value)}] ${" ".repeat(n)}${Te(e.name)}\n`}}return t})(s);t.info(r)},ze=["onStart","onLoad","onResolve","onEnd"],Re=new Map,Ie=new Map,Ae=(e,t,n)=>{const s=Object.assign({},e);for(const o of ze)s[o]=async(s,r)=>{const i=Re.get(t)||{name:t,increment:0,duration:0,events:{}};i.events[o]=i.events[o]||{name:o,values:[]};return(0,e[o])(s,(async(...e)=>{const s=ke(e[0].path,n),a=Ie.get(s)||{name:s,increment:0,duration:0,events:{}};a.events[o]=a.events[o]||{name:o,values:[]};const u=f.now();try{return await r(...e)}finally{const n=f.now(),r=n-u,c={start:u,end:n,duration:r,context:De(e)};i.events[o].values.push(c),i.duration+=r,i.increment+=1,Re.set(t,i),a.events[o].values.push(c),a.duration+=r,a.increment+=1,Ie.set(s,a)}}))};return s},Ce=(e,t,n)=>({setup:s=>{t.build.start=Date.now(),s.initialOptions.metafile=!0;const o=n.time("wrapping plugins");((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const s of n){if(s.name.includes(ye))continue;const n=s.setup;s.setup=async o=>{const r=Ae(o,s.name,t);await n({...r,initialOptions:{...r.initialOptions,plugins:e}})}}}})(s,t.cwd),o.end(),s.onEnd((async s=>{if(!s.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const o=n.time("getting plugins results"),{plugins:r,modules:i}={plugins:Re,modules:Ie};o.end(),e.report={timings:{tapables:r,modules:i}},await t.asyncHook("telemetryBundlerContext",e.report)}))}});class Fe{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=Se(e,t,this.cwd),s=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(Ee))(e);s.length||s.push("no-loader"),this.started[n]={module:$e(n),timings:{start:f.now(),duration:0,end:0},loaders:s}}doneModule(e,t){const n=Se(e,t,this.cwd),s=this.started[n];s&&(s.timings.end=f.now(),s.timings.duration=s.timings.end-s.timings.start,this.finished.push(s),delete this.started[n])}getResults(){const e=new Map,t=new Map;for(const n of this.finished){const s=n.timings.end-n.timings.start,o=t.get(n.module)||{name:n.module,increment:0,duration:0,events:{}},r=n.loaders.join(",");o.events[r]=o.events[r]||{name:r,values:[]},o.events[r].values.push(n.timings),o.increment+=1,o.duration+=s,t.set(n.module,o);for(const t of n.loaders){const n=e.get(t)||{name:t,increment:0,duration:0,events:{}};n.increment+=1,n.duration+=s,e.set(t,n)}}return{loaders:e,modules:t}}}class Le{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,s,o,r){const i=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};i.events[n]||(i.events[n]={name:n,values:[]}),i.events[n].values.push({start:o,end:r,duration:r-o,context:s,type:e}),i.duration+=r-o,i.increment+=1,this.timings.set(t,i)}getResults(){const e=this.timings;for(const[t,n]of this.timings){const s=n;s.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,s)}return{monitoredTaps:this.monitoredTaps,tapables:this.tapables,hooks:this.hooks,timings:e}}getPromiseTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=f.now(),i=t.apply(this,o),a=()=>{this.saveResult(e,n,s,De(o),r,f.now())};return i.then(a,a),i}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=f.now(),i=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,De(o),r,f.now()),i(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=f.now(),i=t.apply(this,o);return this.saveResult(e,n,s,De(o),r,f.now()),i}}getTapPatch(e,t,n,s){switch(e){case"promise":return this.getPromiseTapPatch(e,t,n,s);case"async":return this.getAsyncTapPatch(e,t,n,s);default:return this.getDefaultTapPatch(e,t,n,s)}}newTap(e,t,n,s){return(o,r)=>{const i="string"==typeof(a=o)?a:a.name;var a;const u=`${t}-${i}`;if(this.monitoredTaps[u])return n.call(s,o,r);this.monitoredTaps[u]=!0;const c=this.getTapPatch(e,r,i,t);return n.call(s,o,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(ye)||(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 s of n)this.patchHook(t,s,e.hooks[s])}checkNewHooks(){for(const e of this.tapables)this.patchHooks(e)}throughHooks(e){this.tapables.includes(e)||this.tapables.push(e),this.patchHooks(e)}}const _e=(e,t)=>async n=>{const s=t.getLogger(ye);t.build.start=Date.now();const o={name:ye},r=new Le(t.cwd),i=new Fe(t.cwd),a=s.time("parse compiler hooks");r.throughHooks(n),a.end(),n.hooks.thisCompilation.tap(o,(e=>{const t=s.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)}))})),n.hooks.afterEmit.tapPromise(o,(async n=>{const{timings:s}=r.getResults(),{loaders:o,modules:a}=i.getResults();e.report={timings:{tapables:s,loaders:o,modules:a}},await t.asyncHook("telemetryBundlerContext",e.report)}))},qe={filters:we},He=({options:e,context:t})=>{const n=t.getLogger(ye);let s=0;const o={start:Date.now()},r=(e=>{const t=e[he]?.endPoint||"https://app.datadoghq.com";return{disabled:!e[he],enableTracing:!1,filters:we,output:!1,prefix:"",tags:[],...e[he],endPoint:t.startsWith("http")?t:`https://${t}`}})(e),i=[];if(r.disabled)return i;const a={name:ye,enforce:"pre",esbuild:Ce(o,t,n),webpack:_e(o,t),rspack:_e(o,t)},u=n.time("build",{start:!1}),c=r.enableTracing&&["esbuild","webpack4","webpack5","rspack"].includes(t.bundler.fullName);let p,l;const d=async()=>{t.build.end=Date.now(),t.build.duration=t.build.end-t.build.start,t.build.writeDuration=t.build.end-s;const e=new Set,i=(e=>({timestamp:Math.floor((e.timestamp||Date.now())/1e3),tags:e.tags,prefix:e.prefix,filters:e.filters}))(r),a=n.time("aggregating metrics");xe(l,i,e,o.report),a.end();const u=n.time("writing to files");await Me({report:o.report,metrics:e},r.output,n,t.bundler.outDir),u.end();const c=n.time("outputing report");Oe(t,n,o.report),c.end();const p=n.time("sending metrics to Datadog");await((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.info("No metrics to send.");const s=new Map;for(const t of e)s.has(t.metric)||s.set(t.metric,0),s.set(t.metric,s.get(t.metric)+1);const o=Array.from(s.entries()).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${e.size} metrics.\nMetrics:\n - ${o.join("\n - ")}`),E({method:"POST",url:`${t.endPoint}/api/v1/series?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:Array.from(e)})})}).catch((e=>{n.error(`Error sending metrics ${e}`)}))})(e,{apiKey:t.auth?.apiKey,endPoint:r.endPoint},n),p.end()},m={name:"datadog-universal-telemetry-plugin",enforce:"post",buildStart(){u.resume(),t.build.start=t.build.start||Date.now()},buildEnd(){u.end(),s=Date.now()},async telemetryBundlerContext(e){p=e,l&&await d()},async buildReport(e){l=e,!p&&c||await d()}};return r.enableTracing&&i.push(a),i.push(m),i},Ke="datadog-analytics-plugin",Be=({context:e})=>{const t=e.getLogger(Ke);return[{name:Ke,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}`)}})())}}]},We="datadog-async-queue-plugin",Ue=e=>{const{context:t,stores:n}=e,s=t.getLogger(We),o=[];return t.queue=e=>{const t=e.catch((e=>{o.push(e.message||e.toString())}));n.queue.push(t)},[{name:We,asyncTrueEnd:async()=>{await Promise.all(n.queue),o.length>0&&s.error(`Error occurred while processing async queue:\n ${o.join("\n ")}`)}}]},Ge=async(e,t,n)=>{const s=[],o=e.initialOptions.entryPoints,r=[],i=[];if(Array.isArray(o))for(const e of o){const t=e&&"object"==typeof e?e.in:e;r.push({path:t})}else o&&"object"==typeof o&&r.push(...Object.entries(o).map((([e,t])=>({name:e,path:t}))));const a=r.flatMap((e=>{return(t=e.path,t.includes("*")?g.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,o])=>{const r=await e.resolve(o,{kind:"entry-point",resolveDir:t.cwd});r.errors.length&&i.push(...r.errors.map((e=>e.text))),r.path&&s.push({name:n.name,resolved:r.path,original:n.path})}));for(const e of i)n.error(e);return await Promise.all(a),s},Je=(e,t)=>O(t)?v:t.startsWith(e)||i.isAbsolute(t)?t:i.resolve(e,t),Ve=(e,t)=>{const n=[...e].map((e=>Je(t||process.cwd(),e).split(i.sep))),s=n.length?Math.min(...n.map((e=>e.length))):0,o=[];for(let e=0;e<s;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;o.push(t)}return o.length>0&&o.join(i.sep)||i.sep},Qe=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,Ye=/(\?|%3F|\|)+/gi,Xe=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=tt(e),Qe.lastIndex=0,Qe.exec(t)?.[1]||"unknown");var t},Ze=["unknown","commonjsHelpers.js",`vite${i.sep}preload-helper.js`],et=(e,t,n)=>{const s=new Set;for(const n of e){const e=tt(n);O(n)||e===t||Ze.includes(e)||s.add(e)}return s},tt=e=>e.split("!").pop().split(Ye).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/\\]+/,""),nt=(e,t)=>O(t)?v:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):((e,t)=>{const n=t.split(i.sep),s=e.split(i.sep).filter(((e,t)=>e===n[t])).join(i.sep);return e.replace(s,"")})(t.split("!").pop(),e).split("node_modules").pop().split(Ye).shift().replace(/^((\.\.?)?[/\\])+/g,""),st=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Je(t,e),n]))),ot=(e,t)=>({setup(n){const s=new Map;let o=[];const r=t.time("build report",{start:!1});n.onStart((async()=>{s.clear(),o=[],r.resume();const i=t.time("process entries");o.push(...await Ge(n,e,t));for(const t of o){const n=nt(e.bundler.outDir,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}i.end(),r.pause()})),n.onEnd((async n=>{r.resume();const o=t.time("collecting errors and warnings"),a=e.cwd,u=e.bundler.outDir;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(o.end(),!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const c=[],p=[],l=[],d=[],m=[],f={},g={},h=t.time("indexing metafile data"),y=st(n.metafile.inputs,a),w=st(n.metafile.outputs,a);h.end();const b=e=>{if(!O(e))return e;const t=y[Je(a,e)];if(!t)return e;const n=t.imports.find((e=>!O(e.path)));return n?n.path:e},v=t.time("looping through inputs");for(const[e,t]of Object.entries(n.metafile.inputs)){if(O(e))continue;const n=Je(a,e),s={name:nt(u,e),filepath:n,dependents:new Set,dependencies:new Set,size:t.bytes,type:Xe(e)};f[n]=s,c.push(s)}v.end();const $=t.time("looping through outputs");for(const[e,o]of Object.entries(n.metafile.outputs)){const n=Je(a,e),r=nt(u,n),i=[];for(const e of Object.keys(o.inputs)){if(O(e))continue;const n=f[Je(a,e)];n?i.push(n):t.debug(`Input ${e} not found for output ${r}`)}if(o.entryPoint&&!i.length){const e=f[Je(a,o.entryPoint)];if(!e){t.debug(`Input ${o.entryPoint} not found for output ${r}`);continue}i.push(e)}const c={name:r,filepath:n,inputs:i,size:o.bytes,type:Xe(n)};if(g[n]=c,"map"===c.type&&d.push(c),p.push(c),!o.entryPoint)continue;const m=f[Je(a,b(o.entryPoint))];if(m){if(!s.get(m.name))continue;const e={...c,name:s.get(m.name)||m.name,outputs:[c],size:c.size};l.push(e)}}$.end();const k=t.time("looping through sourcemaps");for(const e of d){const n=g[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}k.end();const S={inputs:{report:f,meta:y},outputs:{report:g,meta:w}},E=/(<runtime>|https:|file:|data:|#)/g,D=e=>!O(e)&&!e.match(E),x=(e,n,s={})=>{if(!D(e))return s;const o=n.report[e];if(!o)return t.debug(`Could not find report's ${e}`),s;if(s[o.filepath])return s;s[o.filepath]=o;const r=n.meta[e];if(!r)return t.debug(`Could not find metafile's ${e}`),s;if(!r.imports||!r.imports.length)return s;for(const t of r.imports){const r=t.path.match(/^\.\.?\//),p=r?i.dirname(e):a,l=Je(p,t.path);if(t.external){if(D(t.path)){const e=r?l:t.path,n=S.inputs.report[e]||{filepath:e,name:nt(u,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in o&&(n.dependents.add(o),o.dependencies.add(n)),"inputs"in o&&!o.inputs.includes(n)&&o.inputs.push(n),c.includes(n)||c.push(n),S.inputs.report[e]=n,s[n.filepath]=n}}else x(l,n,s)}return s},M=t.time("looping through entries");for(const e of l){const t={},n={};for(const n of e.inputs)x(n.filepath,S.inputs,t);for(const t of e.outputs)x(t.filepath,S.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),m.push(e)}M.end();const P=t.time("aggregate dependencies and dependents");for(const e of c){if("external"===e.type)continue;const n=S.inputs.meta[e.filepath];if(n)for(const s of n.imports){if(!D(s.path))continue;const n=s.path.match(/^\.?\.\//),o=n?i.dirname(e.filepath):a,r=Je(o,s.path);let u;if(s.external){const e=n?r:s.path;u=S.inputs.report[e]}else u=S.inputs.report[r];u?(e.dependencies.add(u),u.dependents.add(e)):t.debug(`Could not find input file of ${s.path} imported from ${e.name}`)}else t.debug(`Could not find metafile's ${e.name}`)}P.end(),e.build.outputs=p,e.build.inputs=c,e.build.entries=m,r.end(),await e.asyncHook("buildReport",e.build)}))}}),rt=(e,t)=>{const n=t.time("module parsing",{start:!1}),s=t.time("build report",{start:!1}),o=t.time("filling entries",{start:!1}),r=t.time("filling inputs and outputs",{start:!1}),i=t.time("completing dependencies and dependents",{start:!1}),a=t.time("filling dependencies and dependents",{start:!1}),u=t.time("filling sourcemaps inputs",{start:!1}),c=new Map,p=new Map,l=new Map,d=new Map;return{buildStart(){d.clear(),c.clear(),p.clear(),l.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=tt(e.id),s=d.get(t)||{dependencies:new Set,dependents:new Set},o=et(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=et(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)s.dependents.add(e);for(const e of o)s.dependencies.add(e);d.set(t,s),n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,m){s.resume();const f=n.dir?Je(e.cwd,n.dir):e.bundler.outDir,g=new Set,h=new Set,y=new Map;i.resume();for(const[e,{dependencies:t,dependents:n}]of d){for(const n of t){const t=tt(n),s=d.get(t)||{dependencies:new Set,dependents:new Set};s.dependents.has(e)||(s.dependents.add(e),d.set(t,s))}for(const t of n){const n=tt(t),s=d.get(n)||{dependencies:new Set,dependents:new Set};s.dependencies.has(e)||(s.dependencies.add(e),d.set(n,s))}}i.end(),r.resume();for(const[e,n]of Object.entries(m)){const s=Je(f,e),o="code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),r=p.get(s)||{name:e,filepath:s,inputs:[],size:o,type:Xe(e)};if("map"===r.type&&h.add(r),"modules"in n)for(const[e,t]of Object.entries(n.modules)){if(tt(e)!==e)continue;const n=c.get(e)||{name:nt(f,e),dependencies:new Set,dependents:new Set,filepath:e,size:t.originalLength,type:Xe(e)};r.inputs.push(n),c.set(n.filepath,n)}if("imports"in n)for(const e of n.imports){const n=tt(e);if(!d.has(n)){y.set(Je(f,n),r);continue}if(c.has(n)){t.debug(`Input report already there for ${n} from ${r.name}.`);continue}const s=c.get(n)||{name:nt(f,e),dependencies:new Set,dependents:new Set,filepath:n,size:0,type:"external"};r.inputs.push(s),c.set(s.filepath,s)}"isEntry"in n&&n.isEntry&&g.add({...r,name:n.name,size:0,outputs:[r]}),p.set(r.filepath,r)}r.end();for(const[e,n]of y){const s=p.get(e);s?n.inputs.includes(s)||n.inputs.push(s):t.debug(`Could not find the output report for ${e}.`)}a.resume();for(const[e,n]of c){const s=d.get(e);if(s){for(const e of s.dependencies){const s=c.get(e);s?n.dependencies.add(s):t.debug(`Could not find input for dependency ${nt(f,e)} of ${n.name}`)}for(const e of s.dependents){const s=c.get(e);s?n.dependents.add(s):t.debug(`Could not find input for dependent ${nt(f,e)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(a.end(),h.size){u.resume();for(const e of h){const n=e.filepath.replace(/\.map$/,""),s=p.get(n);s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}u.end()}const w=(e,n=new Map)=>{if(n.has(e))return n;const s=nt(f,e),o=p.get(e);if(!o)return c.has(s)||t.debug(`Could not find output for ${s}`),n;n.set(e,o);const r=m[nt(f,e)];if(!r)return t.debug(`Could not find asset for ${s}`),n;const i=[];"imports"in r&&i.push(...r.imports),"dynamicImports"in r&&i.push(...r.dynamicImports);for(const e of i)w(Je(f,e),n);return n};o.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),l.has(e.filepath)&&t.debug(`Entry "${e.name}":"${nt(f,e.filepath)}" already reported.`),l.set(e.filepath,e)}o.pause(),s.pause()},async closeBundle(){e.build.inputs=Array.from(c.values()),e.build.outputs=Array.from(p.values()),e.build.entries=Array.from(l.values()),o.end(),s.end(),await e.asyncHook("buildReport",e.build)}}},it=(e,t,n)=>s=>{let o=[],r=[],i=[];const a=new Map,u=new Map,c=new Map,p=new Map,l=[],d=new Map,m=n.time("build report",{start:!1}),f=e=>!(!e||e.startsWith("webpack/runtime")||e.includes("/webpack4/buildin/")||e.startsWith("multi ")||O(e)),g=e=>e.replace(/(^external[^"]+"|"$)/g,""),h=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"],s=e=>{const n=tt(e);t.add(n),n.startsWith("external ")&&t.add(g(n))};s(e.identifier());for(const t of n){const n=e[t];t&&t in e&&"string"==typeof n&&s(n)}return t})(e);for(const e of n)if(p.has(e)){const n=p.get(e);n.dependencies.push(...t.dependencies||[]),n.blocks.push(...t.blocks||[])}else p.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},w=(e,t)=>{if("request"in t&&t.request){const n=tt(t.request);if(p.has(n))return p.get(n);if(e.context){const t=Je(tt(e.context),n);if(p.has(t))return p.get(t)}}},b=e=>!(!("externalType"in e)||!e.externalType)||(!(!("external"in e)||!e.external)||!!e.identifier?.().startsWith("external "));s.hooks.thisCompilation.tap(t,(s=>{o=[],r=[],i=[],a.clear(),u.clear(),p.clear(),d.clear(),s.hooks.finishModules.tap(t,(t=>{m.resume();const s=n.time("dependency graph"),r=n.time("indexing modules");for(const e of t)h(e);r.end();const i=n.time("building inputs");for(const n of t){const t=n.identifier(),s=nt(e.bundler.outDir,t),r=new Set(y(n).map((e=>{const s=w(n,e);if(!s?.identifier())return!1;const o=s.identifier();return!!f(o)&&(o!==t&&(b(s)?g(o):o))})).filter(Boolean));if(!f(t))continue;const i=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of r){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),i.dependencies.add(e),d.set(e,n)}d.set(t,i);const u=b(n)?{size:0,name:g(s),dependencies:new Set,dependents:new Set,filepath:t,type:"external"}:{size:n.size()||0,name:s,dependencies:new Set,dependents:new Set,filepath:t,type:Xe(t)};o.push(u),a.set(t,u),b(n)&&a.set(g(t),u)}i.end();const u=n.time("assigning dependencies and dependents");for(const e of o){const t=d.get(e.filepath);if(t){for(const s of t.dependencies){const t=a.get(s);t?e.dependencies.add(t):n.debug(`Could not find input of dependency ${s}`)}for(const s of t.dependents){const t=a.get(s);t?e.dependents.add(t):n.debug(`Could not find input of dependent ${s}`)}}else n.debug(`Could not find dependency report for ${e.name}`)}u.end(),s.end(),m.pause()}))})),s.hooks.afterEmit.tapPromise(t,(async t=>{m.resume();const s=t.chunks,p=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Je(e.bundler.outDir,t))),g=n.time("indexing chunks"),h=t.chunkGraph;for(const e of s){const t=d(e),n=(h?h?.getChunkModules(e):"getModules"in e&&"function"==typeof e.getModules?e.getModules():[]).flatMap((e=>"modules"in e&&Array.isArray(e.modules)?e.modules.map((e=>e.identifier())):e.identifier())).filter(f);for(const e of t){if("map"===Xe(e))continue;const t=c.get(e)||new Set;for(const e of n)t.add(e);c.set(e,t)}}g.end();const y=n.time("building outputs");for(const t of p){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:Je(e.bundler.outDir,t.name),type:Xe(t.name)};if(u.set(s.filepath,s),r.push(s),"map"===s.type){l.push(s);continue}const o=c.get(s.filepath);if(o)for(const e of o){const t=a.get(e);t?s.inputs.push(t):n.debug(`Could not find input of ${e}`)}else n.debug(`Could not find modules for ${s.name}`)}y.end();const w=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}`)}w.end();const b=n.time("building entries");for(const[s,o]of t.entrypoints){const t=new Map,r=new Map;let a=0;const c=o.chunks.flatMap(d),p=o.chunks.filter((e=>h?h.getChunkEntryModulesIterable(e):"hasEntryModule"in e&&"function"==typeof e.hasEntryModule&&e.hasEntryModule())).flatMap((e=>Array.from(e.files))).filter((e=>e.includes(s)||o.name&&e.includes(o.name))).find((e=>"js"===Xe(e)));for(const e of c){const s=u.get(e);if(e&&s){if("map"!==s.type&&!t.has(s.name)){t.set(s.name,s);for(const e of s.inputs)r.has(e.filepath)||r.set(e.filepath,e);a+=s.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const l={name:s,filepath:p?Je(e.bundler.outDir,p):"unknown",size:a,inputs:Array.from(r.values()),outputs:Array.from(t.values()),type:p?Xe(p):"unknown"};i.push(l)}b.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=o,e.build.outputs=r,e.build.entries=i,m.end(),await e.asyncHook("buildReport",e.build)}))},at="datadog-build-report-plugin",ut=e=>{const{context:t}=e,n=t.getLogger(at);return[{name:at,enforce:"post",esbuild:ot(t,n),rspack:it(t,at,n),webpack:it(t,at,n),vite:rt(t,n),rollup:rt(t,n)}]},ct="datadog-bundler-report-plugin",pt=(e,t)=>t?i.isAbsolute(t)?t:i.resolve(e,t):"",lt=e=>{if(!e)return[];return(Array.isArray(e)?e:[e]).map((e=>e.dir?e.dir:e.file?i.dirname(e.file):void 0)).filter(Boolean)},dt=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=pt(process.cwd(),t.options.output.path)),e.hook("bundlerReport",e.bundler),t.options.context&&(e.cwd=t.options.context),e.hook("cwd",e.cwd)},mt=e=>({configResolved(t){e.bundler.rawConfig=t;let n=t.build?.outDir??"dist";const s=t.build?.rollupOptions?.output,o=lt(s);e.cwd=t.root??process.cwd(),s&&o.length&&(n=Ve(o,process.cwd())),e.bundler.outDir=pt(e.cwd,n),e.hook("cwd",e.cwd),e.hook("bundlerReport",e.bundler)}}),ft=e=>{const{context:t}=e,n=t.getLogger(ct);return[{name:ct,enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.absWorkingDir&&(t.cwd=e.initialOptions.absWorkingDir),e.initialOptions.outdir&&(t.bundler.outDir=pt(t.cwd,e.initialOptions.outdir)),e.initialOptions.outfile&&(t.bundler.outDir=pt(t.cwd,i.dirname(e.initialOptions.outfile))),t.hook("cwd",t.cwd),t.hook("bundlerReport",t.bundler),e.initialOptions.metafile=!0}},webpack:dt(t),rspack:dt(t),vite:mt(t),rollup:{options(e){let n;if("output"in e){const t=lt(e.output);n=Ve(t,process.cwd())}const s=(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(i.dirname(e))}}return Array.from(t)})(e);if(n){t.bundler.outDir=Je(process.cwd(),n);const e=Ve([n,...s],process.cwd());t.cwd=e===i.sep?process.cwd():e}else t.cwd=Ve(s,process.cwd()),t.bundler.outDir=i.resolve(process.cwd(),"dist");t.hook("cwd",t.cwd)},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 s=lt(e);Ve(s,process.cwd()).startsWith(t.bundler.outDir)||n.info("The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.")}}}]},gt="datadog-custom-hooks-plugin",ht=e=>{const{context:t}=e,n=t.getLogger(gt),s=e=>(s,...o)=>{const r=n.time(`execution | ${s}`,{tags:["type:custom-hook",`hook:${s}`]}),i=[],a=[];for(const n of t.plugins){if(!(s in n))continue;const t=n[s];if("function"==typeof t)try{const r=t(...o);r instanceof Promise&&(e||i.push(`Plugin "${n.name}" returned a promise on the non async hook "${s}".`),a.push(r))}catch(e){i.push(`Plugin "${n.name}" errored on hook "${s}". [${e}]`)}else i.push(`Plugin "${n.name}" has an invalid hook type for "${s}". [${typeof t}]`)}if(i.length>0){for(const e of i)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>r.end()))};return t.hook=s(!1),t.asyncHook=s(!0),[{name:gt,enforce:"pre"}]};class yt{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=(s=e,r.readFileSync(s,{encoding:"utf-8"}));var s;const o=JSON.parse(n);if(!o.sources)return void t("Missing 'sources' field in sourcemap.");const i=o.sources;if(0===i.length)return void t("Empty 'sources' field in sourcemap.");const a=this.matchSources(i);if(0!==a.length)return a;t(`${i.map(this.displaySource).join(", ")} not in the tracked files.`)}matchSources(e){let t=[];const n=new Set;for(const s of e){const e=this.getFilename(s);if(n.has(e))continue;n.add(e);const o=this.trackedFilenames.get(e);o&&(t=t.concat(o))}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 wt=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await bt(e);for(const e of t)if(e.name===n)return I(e.refs.push);return I(t[0].refs.push)},bt=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},vt=async e=>e.revparse("HEAD"),$t=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),kt=async e=>e.branch(),St=async e=>e.show(["-s","--format=%s"]),Et=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),Dt="datadog-git-plugin",xt=e=>{const{options:t,context:n}=e,s=n.getLogger(Dt);return[{name:Dt,enforce:"pre",async buildStart(){if((e=>!!e.errorTracking?.sourcemaps&&!0!==e.errorTracking?.sourcemaps.disableGit&&!0!==e.disableGit)(t))try{const e=s.time("get git information"),t=((e,t)=>{let n,s=Je(process.cwd(),e);for(;!n;){const e=i.resolve(s,t);if(P(e)&&(n=e),s=s.split(i.sep).slice(0,-1).join(i.sep),[i.sep,""].includes(s))break}return n})(n.cwd,".git");if(!t)return void s.warn("No .git directory found, skipping git plugin.");const o=await(async e=>{const t=[vt(e),kt(e),St(e),Et(e),$t(e),wt(e)],[n,s,o,r,i,a]=await Promise.all(t),[u,c,p,l,d,m]=r.split(",").map((e=>e.trim()));return{commit:{author:{name:u,email:c,date:p},committer:{name:l,email:d,date:m},message:o.trim(),hash:n},hash:n,branch:s.current,remote:a.trim(),trackedFilesMatcher:new yt(i)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=h(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return h(t)})(i.dirname(t)));n.git=o,e.end(),await n.asyncHook("git",n.git)}catch(e){s.error(`Could not get git information: ${e.message}`)}}}]},Mt="datadog-injection-plugin",Pt=/^https?:\/\//,Tt=async(e,t=process.cwd())=>(e=>o.readFile(e,{encoding:"utf-8"}))(Je(t,e)),jt=async(e,t,n=process.cwd())=>{let s;const o=await(async e=>"function"==typeof e.value?e.value():e.value)(e);try{if("file"===e.type)s=o.match(Pt)?await(async(e,t=5e3)=>{let n;return Promise.race([E({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,s)=>{n=setTimeout((()=>{s(new Error("Timeout"))}),t)}))])})(o):await Tt(o,n);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);s=o}}catch(r){const i=`${e.type} - ${R(o)}`;e.fallback?(t.info(`Fallback for "${i}": ${r.toString()}`),s=await jt(e.fallback,t,n)):t.warn(`Failed "${i}": ${r.toString()}`)}return s},Nt=e=>{if(0===e.size)return"";return`// begin injection by Datadog build plugins\n${Array.from(e.values()).map((e=>`(() => {${e}})();`)).join("\n\n")}\n// end injection by Datadog build plugins`},Ot=async(e,t,n,s=process.cwd())=>{const o=await(async(e,t,n=process.cwd())=>{const s=new Map;for(const[o,r]of e.entries()){const e=await jt(r,t,n);e&&s.set(o,{value:e,position:r.position||ae.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},zt=r.promises,Rt=(e,t,n)=>({setup(s){const{onStart:o,onResolve:a,onLoad:u,onEnd:c,esbuild:p,initialOptions:l}=s,d=[],m=`${t.bundler.fullName}.${ae.MIDDLE}.${v}.js`,f=r.realpathSync(y.tmpdir()),g=i.resolve(f,m),h=new RegExp(`${m}$`),w=l.inject;l.inject=w?[...w]:[],l.inject.push(g),o((async()=>{d.push(...await Ge(s,t,e)),s.initialOptions.inject=w;try{await x(g,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:h},(async e=>({path:e.path,namespace:Mt}))),u({filter:h,namespace:Mt},(async()=>({contents:Nt(n[ae.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),c((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=Nt(n[ae.BEFORE]),r=Nt(n[ae.AFTER]);if(!o&&!r)return;const i=Object.entries(s.metafile.outputs).map((([e,n])=>{const s=n.entryPoint;if(!s)return;return d.find((e=>e.resolved.endsWith(s)))?Je(t.cwd,e):void 0})).filter(Boolean).map((async t=>{try{const e=await zt.readFile(t,"utf-8"),n=await p.transform(e,{loader:"default",banner:o,footer:r});await zt.writeFile(t,n.code)}catch(n){if(!(e=>e instanceof Error&&"code"in e)(n)||"ENOENT"!==n.code)throw n;e.warn(`Could not inject content in ${t}: ${n}`)}}));await Promise.all(i)}))}}),It=v,At="?inject-proxy",Ct=e=>({banner:t=>t.isEntry?Nt(e[ae.BEFORE]):"",async resolveId(t,n,s){if(O(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&Nt(e[ae.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${At}`}return null},load(t){if(O(t))return Nt(e[ae.MIDDLE]);if(t.endsWith(At)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(It)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?Nt(e[ae.AFTER]):""}),Ft=(e,t,n,s,o)=>a=>{const u=new WeakMap,c=(e=>{if(!e?.sources?.ConcatSource)return w(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),p=n.bundler.fullName,l=i.resolve(n.bundler.outDir,`${p}.${ae.MIDDLE}.${v}.js`);M(l,"");const d=()=>{var e;e=l,r.rmSync(e,{force:!0,maxRetries:3,recursive:!0})};a.hooks.shutdown?a.hooks.shutdown.tap(Mt,d):(a.hooks.done.tap(Mt,d),a.hooks.failed.tap(Mt,d));a.hooks.beforeRun.tapPromise(Mt,(async()=>{await Ot(t,s,o,n.cwd)})),a.hooks.compilation.tap(Mt,(t=>{const n=()=>{const e=Nt(o[ae.BEFORE]),n=Nt(o[ae.AFTER]);for(const s of t.chunks)if(s.canBeInitial())for(const o of s.files)t.updateAsset(o,(t=>{const s=u.get(t);if(!s||s.banner!==e||s.footer!==n){const s=new c(e,"\n",t,"\n",n);return u.set(t,{source:s,banner:e,footer:n}),s}return s.source}))};if(t.hooks.processAssets){const s=e.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;t.hooks.processAssets.tap({name:Mt,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:Mt},n)}));const m=(e=>{const s="webpack4"===n.bundler.fullName?l:{import:[l]},o=e=>{for(const[n,s]of Object.entries(e))"object"==typeof s?(s.import=s.import||[],s.import.unshift(l)):"string"==typeof s?e[n]=[l,s]:Array.isArray(s)?s.unshift(l):t.error("Invalid entry type: "+typeof s)};return e?"function"==typeof e?async()=>{const t=await e();return o(t),t}:"object"!=typeof e?"string"==typeof e?[s,e]:(t.error("Invalid entry type: "+typeof e),e):(o(e),e):{ddHelper:s}})(a.options.entry);a.options.entry=m},Lt=e=>{const{bundler:t,context:n}=e,s=n.getLogger(Mt),o=new Map,r={[ae.BEFORE]:new Map,[ae.MIDDLE]:new Map,[ae.AFTER]:new Map};n.inject=e=>{o.set(`${Date.now()}.${performance.now()}.${++A}`,e)};const i={name:Mt,enforce:"post",esbuild:Rt(s,n,r),webpack:Ft(t,s,n,o,r),rspack:Ft(t,s,n,o,r),rollup:Ct(r),vite:{...Ct(r),enforce:"pre"}};var a;return a=n.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(a)?(i.loadInclude=e=>!!O(e)||null,i.load=e=>O(e)?{code:Nt(r[ae.MIDDLE])}:null):i.buildStart=async()=>{await Ot(s,o,r,n.cwd)},[i]},_t="datadog-true-end-plugin",qt=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},s=()=>{t.hook("syncTrueEnd")},o=async()=>{s(),await n()},r=e=>{e.hooks.shutdown?e.hooks.shutdown.tapPromise(_t,o):(e.hooks.done.tapPromise(_t,o),e.hooks.failed.tap(_t,s))},i={async writeBundle(){},async closeBundle(){await o()}};return[{name:_t,enforce:"post",webpack:r,esbuild:{setup(e){e.onEnd((async()=>{await n()})),e.onDispose((()=>{s()}))}},vite:i,rollup:i,rspack:r}]},Ht={[he]:qe};var Kt="2.6.4";const Bt=(({bundler:n,version:s})=>{const o=Date.now();return e(((e,r)=>{const i=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",metadata:{},...e}))(e);"esbuild"===r.framework&&(r.esbuildHostName=k);const a=process.env.BUILD_PLUGINS_ENV||"production",u=$.includes(a)?a:"development",c=n.rspackVersion||n.version||n.VERSION,p=r.framework,l="webpack"===p?c.split(".")[0]:"",d={bundler:{name:p,fullName:`${p}${l}`,variant:l,version:c},env:u,metadata:i.metadata||{},packageName:`@datadog/${p}-plugin`,version:s},m={errors:[],logs:[],queue:[],timings:[],warnings:[]},f=(({start:e,options:t,data:n,stores:s})=>{const o=process.cwd(),r={errors:s.errors,warnings:s.warnings,logs:s.logs,metadata:n.metadata,timings:s.timings,bundler:n.bundler};return{auth:t.auth,pluginNames:[],bundler:{...r.bundler,outDir:o},build:r,cwd:o,env:n.env,getLogger:q(n,s,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:D(n),start:e,version:n.version}})({start:o,options:i,data:d,stores:m}),g=f.getLogger("factory").time("Plugins initialization",{start:o});f.pluginNames.push(k);const h=[];h.push(["analytics",Be],["async-queue",Ue],["build-report",ut],["bundler-report",ft],["custom-hooks",ht],["git",xt],["injection",Lt],["true-end",qt]),i.customPlugins&&h.push(["custom",i.customPlugins]),h.push(["error-tracking",ie],["rum",ge],["telemetry",He]);for(const[e,t]of h)f.plugins.push(...B(f,t,e)({bundler:n,context:f,options:i,data:d,stores:m}));f.pluginNames.push(...f.plugins.map((e=>e.name)));const y=new Set(f.pluginNames.filter((e=>f.pluginNames.filter((t=>t===e)).length>1)));if(y.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(y).join(", "))}`);return f.hook("init",f),g.end(),f.plugins}))})({bundler:b,version:Kt}).webpack,Wt=Kt,Ut=Ht;export{Bt as datadogWebpackPlugin,Ut as helpers,Wt as version};
9
+ const b=e=>process.env[`DATADOG_${e}`]||process.env[`DD_${e}`],w="__datadog-helper-file",v=new RegExp(w),$=["development","production","test"],k="datadog-build-plugins",S=[400,403,413],E=e=>{const{auth:t,url:o,method:s="GET",getData:r,type:i="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:s,duplex:"half"};let n={"X-Datadog-Origin":"build-plugins"};if(t?.apiKey&&(n["DD-API-KEY"]=t.apiKey),t?.appKey&&(n["DD-APPLICATION-KEY"]=t.appKey),"function"==typeof r){const{data:t,headers:o}=await r();e.body=t,n={...n,...o}}a=await fetch(o,{...e,headers:n})}catch(t){return e(t),{}}if(!a.ok){const t=`HTTP ${a.status} ${a.statusText}`;if(S.includes(a.status))return e(new Error(t)),{};throw new Error(t)}try{let e;return e="json"===i?await a.json():await a.text(),e}catch(t){return e(t),{}}}),a)},D=e=>({message:t,context:n})=>E({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||k,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"}}}}),x=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),R=e=>e.includes(w),M=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},P=e=>{const t=!!e.errorTracking?.sourcemaps,n=e.enableGit??!0;return t&&n},T=e=>{const t=Math.floor(e/1e3/60/60/24),n=new Date(e-24*t*60*60*1e3),o=n.getUTCHours(),s=n.getUTCMinutes(),r=n.getUTCSeconds(),i=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${o?`${o}h `:""}${s?`${s}m `:""}${r?`${r}s`:""}`.trim();return`${a}${!a||i?` ${i}ms`:""}`.trim()},j=(e,t=60,n="[...]")=>{if(e.length<=t)return e;const o=Math.max(4,t-n.length),s=Math.min(10,Math.floor(o/2)),r=o-s;return`${e.slice(0,s)}${n}${e.slice(-r)}`},O=(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}};let z=0;const N={debug:0,info:1,warn:2,error:3,none:4},A=e=>e.split(">").map(x).join(">"),I=(e,n,o,s)=>{const r=A(e);return(i,a="debug",{forward:u}={})=>{let p=t.dim,c=console.log;"error"===a?(p=t.red,c=console.error):"warn"===a?(p=t.yellow,c=console.warn):"info"===a&&(p=t.cyan,c=console.log);const l=`[${n.metadata?.name?`${n.metadata.name}|`:""}${a}|${n.bundler.name}|${r}]`,d="string"==typeof i?i:JSON.stringify(i,null,2);if(o.logs.push({bundler:n.bundler.name,pluginName:e,type:a,message:d,time:Date.now()}),"error"===a&&o.errors.push(d),"warn"===a&&o.warnings.push(d),u){const t=async()=>{try{const t=D(n);await t({message:d,context:{plugin:e,status:a}})}catch(t){I(e,n,o,s)(`Error forwarding log: ${t}`,"debug")}};o.queue.push(t())}N[a]>=N[s]&&c(`${p(l)} ${d}`)}},C=(e,n,o)=>(s,r={})=>{const{level:i="debug",start:a=!0,log:u=!0,tags:p=[]}=r,c={pluginName:e,label:s,spans:[],tags:[...p,`plugin:${e}`,`level:${i}`],logLevel:i,total:0};n.push(c);const l=()=>c.spans.filter((e=>!e.end)),d=n=>{l().length||(!c.spans.length&&u&&o(t.dim(`[${t.cyan(s)}] : start`),"debug"),c.spans.push({start:n||Date.now(),tags:[`plugin:${e}`]}))},m=(e,n=!0)=>{const r=l();if(r?.length){r.length>1&&o(`Timer ${t.cyan(s)} has more than one ongoing span.`,"debug");for(const t of r)t.end=e||Date.now()}else n&&o(`Timer ${t.cyan(s)} cannot be paused, no ongoing span.`,"debug")};if(a){let e;"number"==typeof a&&(e=a),d(e)}return{timer:c,resume:d,end:e=>{m(e,!1);const n=c.spans.reduce(((e,t)=>e+(t.end-t.start)),0);c.total=n,u&&o(`[${t.cyan(s)}] : ${t.cyan(T(n))}`,i)},pause:m,tag:(e,t={})=>{const{span:n=!1}=t;if(n){const t=l();for(const n of t)n.tags.push(...e)}else c.tags.push(...e)}}},F=(e,t,n="warn")=>o=>{const s=I(o,e,t,n);return{getLogger:s=>F(e,t,n)(`${A(o)}>${s}`),time:C(o,t.timings,s),error:(e,t)=>s(e,"error",t),warn:(e,t)=>s(e,"warn",t),info:(e,t)=>s(e,"info",t),debug:(e,t)=>s(e,"debug",t)}},L=["buildEnd","buildStart","load","resolveId","transform","watchChange","writeBundle","buildRoot","init","buildReport","bundlerReport","git"],_=(e,t,n,o)=>{const s=n=>function(...s){const r=o.time(`${e} | ${t}`,{log:!1,tags:["type:hook",`hook:${t}`]}),i=n.apply(this,s);return i instanceof Promise?i.finally((()=>{r.end()})):(r.end(),i)};return"object"==typeof n&&null!==n&&"handler"in n?{...n,handler:s(n.handler)}:s(n)},K=(e,t,n)=>{const o=e.getLogger(k);return e=>{const s=o.time(`hook | init ${n}`,{log:!1}),r=t(e).map((e=>((e,t)=>{const n={...e},o=x(e.name);for(const s of L){const r=e[s];r&&(n[s]=_(o,s,r,t))}return n})(e,o))),i=r.map((e=>`plugin:${e.name}`));return s.tag(i),s.end(),r}},H="errorTracking",q="datadog-error-tracking-plugin",B=(e,n,o)=>{if(".map"!==s.extname(o))throw new Error(`The file ${t.green.bold(o)} is not a sourcemap.`);const r=o.replace(/\.map$/,""),i=s.relative(n,r),a=((e,t)=>{if(e.startsWith("/"))return s.join(e,t);try{const n=e.replace(/\/*$/,"/"),o=new URL(n),s=t.replace(/^[\\/]*/,"");return new URL(s,o).href}catch{return`${e}${t}`}})(e,i);return{minifiedFilePath:r,minifiedUrl:a,relativePath:i}},W=async(e,t)=>{await(async e=>i.mkdir(e,{recursive:!0}))(s.dirname(e)),await i.writeFile(e,t,{encoding:"utf-8"})},U=(e,t)=>{var n;n=s.dirname(e),a.mkdirSync(n,{recursive:!0}),a.writeFileSync(e,t,{encoding:"utf-8"})},G=e=>{try{return a.existsSync(e)}catch(e){if("ENOENT"===e.code)return!1;throw e}},J=async(e,t)=>{if("function"==typeof a.openAsBlob){const n=await a.openAsBlob(e,{type:t.contentType});return new r([n],t.filename)}{const n=u.toWeb(a.createReadStream(e)),o=await new Response(n).blob();return new r([o],t.filename,{type:t.contentType})}},V=async e=>{const t={empty:!1,exists:!0};try{const{size:n}=await i.stat(e);0===n&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t},Y=/[/]+|[\\]+/g,Q=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,X=(e,t)=>{const n=e.replace(Q,"").split(Y),o=t.replace(Q,"").split(Y),s=n.join("/");let r="";for(let e=0;e<o.length;e+=1){const t=o.slice(-e).join("/");s.startsWith(t)&&(r=t)}return r},Z=async(e,t,n,o)=>{const r=await(async(e,t)=>{const[n,o]=await Promise.all([V(e.minifiedFilePath),V(e.sourcemapFilePath)]);return{file:n,sourcemap:o,repeatedPrefix:X(e.relativePath,t)}})(e,n),i=[],a=[],u=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{u.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:o.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{a.push(`${s.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:o.hash,repository_url:o.remote}],version:1})})}catch(t){a.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&&a.push(`The minified file path contains a repeated pattern with the minified path prefix: ${r.repeatedPrefix}`),{content:u,errors:i,warnings:a}},ee=t.green.bold,te=t.yellow.bold,ne=t.red.bold,oe=(e,t={})=>async()=>{const n=new FormData,o=c();for(const[t,o]of e.content){const e="file"===o.type?await J(o.path,o.options):new Blob([o.value],{type:o.options.contentType});n.append(t,e,o.options.filename)}const s=new Request("fake://url",{method:"POST",body:n});return{data:u.fromWeb(s.body).pipe(o),headers:{"Content-Encoding":"gzip",...t,...Object.fromEntries(s.headers.entries())}}},se=async(e,t,n,o)=>{const s=Date.now(),r=t.minifiedPathPrefix,i={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=await Promise.all(e.map((e=>Z(e,i,r,n.git)))),u=a.map((e=>e.errors)).flat(),c=a.map((e=>e.warnings)).flat();if(c.length>0&&o.warn(`Warnings while preparing payloads:\n - ${c.join("\n - ")}`),u.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${u.join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e);return}const{errors:l,warnings:d}=await(async(e,t,n,o)=>{const s=[],r=[];if(!n.apiKey)return s.push({error:new Error("No authentication token provided")}),{errors:s,warnings:r};if(0===e.length)return r.push("No sourcemaps to upload"),{errors:s,warnings:r};const i=new(p.default?p.default:p)({concurrency:t.maxConcurrency}),a={"DD-EVP-ORIGIN":`${n.bundlerName}-build-plugin_sourcemaps`,"DD-EVP-ORIGIN-VERSION":n.version},u=[];for(const p of e){const e={sourcemap:p.content.get("source_map")?.path.replace(n.outDir,"."),file:p.content.get("minified_file")?.path.replace(n.outDir,".")};o.debug(`Queuing ${ee(e.sourcemap)} | ${ee(e.file)}`),u.push(i.add((async()=>{try{await E({auth:{apiKey:n.apiKey},url:(i=n.site,process.env.DATADOG_SOURCEMAP_INTAKE_URL||`https://sourcemap-intake.${i}/api/v2/srcmap`),method:"POST",getData:oe(p,a),onRetry:(t,n)=>{const s=`Failed to upload ${te(e.sourcemap)} | ${te(e.file)}:\n ${t.message}\nRetrying ${n}/5`;r.push(s),o.debug(s)}}),o.debug(`Sent ${ee(e.sourcemap)} | ${ee(e.file)}`)}catch(n){if(s.push({metadata:e,error:n}),!0===t.bailOnError)throw n}var i})))}return await Promise.all(u),await i.onIdle(),{warnings:r,errors:s}})(a,t,{apiKey:n.apiKey,bundlerName:n.bundlerName,version:n.version,outDir:n.outDir,site:n.site},o);if(o.info(`Done uploading ${ee(e.length.toString())} sourcemaps in ${ee(T(Date.now()-s))}.`),l.length>0){const e=`Failed to upload some sourcemaps:\n${` - ${l.map((({metadata:e,error:t})=>e?`${ne(e.file)} | ${ne(e.sourcemap)} : ${t.message}`:t.message)).join("\n - ")}`}`;if(o.error(e),!0===t.bailOnError)throw new Error(e)}d.length>0&&o.warn(`Warnings while uploading sourcemaps:\n - ${d.join("\n - ")}`)},re=async(e,n,s)=>{const r=t.green.bold,i=Object.entries(e.sourcemaps).map((([e,t])=>` - ${e}: ${r(t.toString())}`)).join("\n"),a=s.time("get sourcemaps files"),u=((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=>({...B(e.minifiedPathPrefix,t.outDir,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,{outDir:n.outDir,outputs:n.outputs});a.end();const p=o`
10
+ Uploading ${r(u.length.toString())} sourcemaps with configuration:
11
+ ${i}
12
+ `;s.info(p);const c=s.time("send sourcemaps");await se(u,e.sourcemaps,{apiKey:n.apiKey,bundlerName:n.bundlerName,git:n.git,outDir:n.outDir,site:n.site,version:n.version},s),c.end()},ie=e=>{const n=t.bold.red,o=e[H]||{},s={errors:[]};if(o.sourcemaps){o.sourcemaps.releaseVersion||s.errors.push(`${n("sourcemaps.releaseVersion")} is required.`),o.sourcemaps.service||s.errors.push(`${n("sourcemaps.service")} is required.`),o.sourcemaps.minifiedPathPrefix||s.errors.push(`${n("sourcemaps.minifiedPathPrefix")} is required.`),o.sourcemaps.minifiedPathPrefix&&((e=>{let t;try{t=new URL(e).host}catch{}return!(!t&&!e.startsWith("/"))})(o.sourcemaps.minifiedPathPrefix)||s.errors.push(`${n("sourcemaps.minifiedPathPrefix")} must be a valid URL or start with '/'.`));const e={bailOnError:!1,dryRun:!1,maxConcurrency:20,...o.sourcemaps};s.config=e}return s},ae=({options:e,context:t})=>{const n=t.getLogger(q),o=n.time("validate options"),s=((e,t)=>{const n=[],o=ie(e);if(n.push(...o.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${q}.`);const s={enable:!!e[H],...e[H],sourcemaps:void 0};return o.config&&(s.sourcemaps=o.config),s})(e,n);if(o.end(),!s.enable)return[];let r,i;const a=async()=>{if(!s.sourcemaps)return;const e=n.time("sourcemaps process");await re(s,{apiKey:t.auth.apiKey,bundlerName:t.bundler.name,git:r,outDir:t.bundler.outDir,outputs:i?.outputs||[],site:t.auth.site,version:t.version},n),e.end()};return[{name:q,enforce:"post",async git(e){r=e,i&&await a()},async buildReport(t){i=t,!r&&P(e)||await a()}}]},ue=[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};/(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}],pe="metrics",ce="datadog-metrics-plugin",le=e=>Math.floor((e||Date.now())/1e3),de=(e,t,n)=>({...e,tags:[...e.tags,...t],metric:n?`${n}.${e.metric}`:e.metric}),me=(e="")=>e.endsWith("/")?e:`${e}/`,fe=(e,t)=>{let n=e;return e.split(me(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},he=(e,t)=>e.split("!").pop().replace(me(t),"./"),ge=(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)),he(o||"no-name",n)},ye=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),be=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),we=t.bold.red,ve=t.bold.cyan,$e=e=>(t,n)=>{let o,s;return"function"==typeof e?(o=e(t),s=e(n)):(o=t[e],s=n[e]),o>s?-1:o<s?1:0},ke=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort($e("duration"));const o={name:`${e} duration`,values:n.map((e=>({name:e.name,value:T(e.duration)}))),top:!0};n.sort($e("increment"));return[o,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},Se=(e,t,n)=>{const o=[];var s;n&&(o.push(...ke("Loader",n.loaders)),o.push(...ke("Tapable",n.tapables)),o.push(...ke("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},s={name:"Module aggregated size",values:[],top:!0},r=new Set,i=M(e.build),a=new Map,u=new Map,p=new Map;for(const e of i.inputs||[]){if("map"===e.type)continue;const t=new Set(e.dependencies),n=new Set(e.dependents);for(const n of t)p.has(n)||p.set(n,new Set),p.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(p.has(e.filepath)){const t=p.get(e.filepath);for(const e of t)n.add(e)}u.set(e.filepath,t),p.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=p.get(e)||new Set;let s=t.size;for(const e of n)s+=a.get(e)?.size||0;r.add({name:t.name,size:t.size,aggregatedSize:s,dependents:o,dependencies:n})}if(!r.size)return[t,n,o];const c=Array.from(r);return c.sort($e((e=>e.dependents.size))),t.values=c.map((e=>({name:e.name,value:e.dependents.size.toString()}))),c.sort($e((e=>e.dependencies.size))),n.values=c.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),c.sort($e("size")),o.values=c.map((e=>({name:e.name,value:l(e.size)}))),c.sort($e("aggregatedSize")),s.values=c.map((e=>({name:e.name,value:l(e.aggregatedSize||e.size)}))),[t,n,o,s]})(e)),o.push(...(s=e,[{name:"Asset size",values:(s.build.outputs||[]).filter((e=>"map"!==e.type)).sort($e((e=>e.size))).map((e=>({name:e.name,value:l(e.size)}))),top:!0},{name:"Entry aggregated size",values:(s.build.entries||[]).sort($e((e=>e.size))).map((e=>({name:e.name,value:l(e.size)}))),top:!0},{name:"Entry number of modules",values:(s.build.entries||[]).sort($e((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,s=e.build.warnings.length,r=e.build.errors.length,i=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:T(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:T(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:T(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:i.toString()},{name:"Number of warnings",value:s.toString()},{name:"Number of errors",value:r.toString()}),[t]})(e));const r=(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=j(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))))),s=Math.max(...e.flatMap((e=>e.values.map((e=>e.value.length))))),r=Math.max(n+4,o+s+4);for(const n of e){if(0===n.values.length)continue;const e=r-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=s-e.value.length;t+=` [${we(e.value)}] ${" ".repeat(n)}${ve(e.name)}\n`}}return t})(o);t.info(r)},Ee=["onStart","onLoad","onResolve","onEnd"],De=new Map,xe=new Map,Re=new Map,Me=(e,t,n)=>{const o=Object.assign({},e);for(const s of Ee)o[s]=async(o,r)=>{const i=xe.get(t)||{name:t,increment:0,duration:0,events:{}};i.events[s]=i.events[s]||{name:s,values:[]};const a="onLoad"===s;return(0,e[s])(o,(async(...e)=>{const o=he(e[0].path,n),u=Re.get(o)||{name:o,increment:0,duration:0,events:{}};u.events[s]=u.events[s]||{name:s,values:[]};const p=d.now();try{return await r(...e)}finally{const n=d.now(),r=n-p,c={start:p,end:n,duration:r,context:be(e)};if(i.events[s].values.push(c),i.duration+=r,i.increment+=1,xe.set(t,i),u.events[s].values.push(c),u.duration+=r,u.increment+=1,Re.set(o,u),a){const e=De.get(t)||{name:t,increment:0,duration:0,events:{}};e.events[s]=e.events[s]||{name:s,values:[]},e.events[s].values.push(c),e.duration+=r,e.increment+=1,De.set(t,e)}}}))};return o},Pe=(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 s=>{const r=Me(s,o.name,t);await n({...r,initialOptions:{...r.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:s,loaders:r,modules:i}={plugins:xe,modules:Re,loaders:De};o.end(),await e.asyncHook("timings",{tapables:s,loaders:r,modules:i})}))}});class Te{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=ge(e,t,this.cwd),o=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(ye))(e);o.length||o.push("no-loader"),this.started[n]={module:fe(n),timings:{start:d.now(),duration:0,end:0},loaders:o}}doneModule(e,t){const n=ge(e,t,this.cwd),o=this.started[n];o&&(o.timings.end=d.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,s=t.get(n.module)||{name:n.module,increment:0,duration:0,events:{}},r=n.loaders.join(",");s.events[r]=s.events[r]||{name:r,values:[]},s.events[r].values.push(n.timings),s.increment+=1,s.duration+=o,t.set(n.module,s);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 je{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,o,s,r){const i=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};i.events[n]||(i.events[n]={name:n,values:[]}),i.events[n].values.push({start:s,end:r,duration:r-s,context:o,type:e}),i.duration+=r-s,i.increment+=1,this.timings.set(t,i)}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(...s)=>{this.checkNewHooks();const r=d.now(),i=t.apply(this,s),a=()=>{this.saveResult(e,n,o,be(s),r,d.now())};return i.then(a,a),i}}getAsyncTapPatch(e,t,n,o){return(...s)=>{this.checkNewHooks();const r=d.now(),i=s.pop();return t.apply(this,[...s,(...t)=>(this.saveResult(e,n,o,be(s),r,d.now()),i(...t))])}}getDefaultTapPatch(e,t,n,o){return(...s)=>{this.checkNewHooks();const r=d.now(),i=t.apply(this,s);return this.saveResult(e,n,o,be(s),r,d.now()),i}}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(s,r)=>{const i="string"==typeof(a=s)?a:a.name;var a;const u=`${t}-${i}`;if(this.monitoredTaps[u])return n.call(o,s,r);this.monitoredTaps[u]=!0;const p=this.getTapPatch(e,r,i,t);return n.call(o,s,p)}}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(ce)||(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 Oe=e=>async t=>{const n=e.getLogger(ce),o={name:ce},s=new je(e.buildRoot),r=new Te(e.buildRoot),i=n.time("parse compiler hooks");s.throughHooks(t),i.end(),t.hooks.thisCompilation.tap(o,(e=>{const t=n.time("parse compilation hooks");s.throughHooks(e),t.end(),e.hooks.buildModule.tap(o,(t=>{r.startModule(t,e)})),e.hooks.succeedModule.tap(o,(t=>{r.doneModule(t,e)})),e.hooks.failedModule&&e.hooks.failedModule.tap(o,(t=>{r.doneModule(t,e)}))})),t.hooks.afterEmit.tapPromise(o,(async()=>{const{timings:t}=s.getResults(),{loaders:n,modules:o}=r.getResults();await e.asyncHook("timings",{tapables:t,loaders:n,modules:o})}))},ze={filters:ue},Ne=({options:e,context:t})=>{const n=t.getLogger(ce);let o=0;const s=((e,t)=>{const n=e[pe],o=le(n?.timestamp);let s=!1===n?.enableStaticPrefix?"":`build.${t}`;return n?.prefix&&(s+=s?`.${n.prefix}`:n.prefix),{enable:!!e[pe],enableStaticPrefix:!0,enableTracing:!1,filters:ue,tags:[],...e[pe],timestamp:o,prefix:s.toLowerCase().replace(/(^\.*|\.*$)/g,"")}})(e,t.bundler.name),r=[];if(!s.enable)return r;const i={name:ce,enforce:"pre",esbuild:Pe(t,n),webpack:Oe(t),rspack:Oe(t)},a=n.time("build",{start:!1}),u=s.enableTracing&&["esbuild","webpack","rspack"].includes(t.bundler.name);let p,c;const l=async()=>{t.build.end=Date.now(),t.build.duration=t.build.end-t.build.start,t.build.writeDuration=t.build.end-o;const e=n.time("aggregating metrics"),r=s.timestamp,i=((e,t)=>{const n=new Set,o=e.inputs||[],s=e.outputs||[],r=e.entries||[],i=e.warnings.length,a=e.errors.length,u=e.duration,p=new Map,c=new Map,l=new Map;for(const e of r){for(const t of e.inputs)p.has(t.filepath)||p.set(t.filepath,[]),p.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 s)for(const t of e.inputs)c.has(t.filepath)||c.set(t.filepath,[]),c.get(t.filepath).push(e.name);n.add({metric:"assets.count",type:"count",points:[[t,s.length]],tags:[]}).add({metric:"entries.count",type:"count",points:[[t,r.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,i]],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}`];p.has(e.filepath)&&o.push(...p.get(e.filepath).map((e=>`entryName:${e}`))),c.has(e.filepath)&&o.push(...c.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 s){const o=[`assetName:${e.name}`,`assetType:${e.type}`],s=e.filepath.replace(/\.map$/,"");l.has(s)&&o.push(...l.get(s).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 r){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})(c,r),a=((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,s=0;for(const r of Object.values(o.events)){let i=0;s+=r.values.length;for(const t of r.values){const n=t.end-t.start;i+=n,e+=n}n.add({metric:"plugins.hooks.duration",type:"duration",points:[[t,i]],tags:[`pluginName:${o.name}`,`hookName:${r.name}`]}).add({metric:"plugins.hooks.increment",type:"count",points:[[t,r.values.length]],tags:[`pluginName:${o.name}`,`hookName:${r.name}`]})}n.add({metric:"plugins.duration",type:"duration",points:[[t,e]],tags:[`pluginName:${o.name}`]}).add({metric:"plugins.increment",type:"count",points:[[t,s]],tags:[`pluginName:${o.name}`]})}return n})(p?.tapables,r),u=((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})(p?.loaders,r),l=((e,t,n,o,s)=>{const r=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}r.add(de(e,o,s))}const i=Array.from(r).filter((e=>e.toSend)).length;return r.add(de({metric:"metrics.count",type:"count",points:[[t,i+1]],tags:[],toSend:!0},o,s)),r})(new Set([...i,...a,...u]),r,s.filters,s.tags,s.prefix);await t.asyncHook("metrics",l),e.end();const d=n.time("outputing report");Se(t,n,p),d.end();const m=n.time("sending metrics to Datadog");await((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.info("No metrics to send.");const o=Array.from(e).filter((e=>e.toSend)).map((e=>({...e,toSend:void 0}))),s=new Map;for(const e of o)s.has(e.metric)||s.set(e.metric,0),s.set(e.metric,s.get(e.metric)+1);const r=Array.from(s.entries()).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${o.length} metrics.\nMetrics:\n - ${r.join("\n - ")}`),E({method:"POST",url:`https://api.${t.site}/api/v1/series?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:o})})}).catch((e=>{n.error(`Error sending metrics ${e}`)}))})(l,{apiKey:t.auth.apiKey,site:t.auth.site},n),m.end()},d={name:"datadog-universal-metrics-plugin",enforce:"post",buildStart(){a.resume(),t.build.start=t.build.start||Date.now(),e[pe]?.timestamp||(s.timestamp=le(t.build.start))},buildEnd(){a.end(),o=Date.now()},async timings(e){p=e,c&&await l()},async buildReport(e){c=e,!p&&u||await l()}};return s.enableTracing&&r.push(i),r.push(d),r},Ae="output",Ie=(e,t)=>"string"==typeof t?t.replace(/(\.json)?$/,".json"):!0===t?`${e}.json`:t,Ce=e=>{const t=void 0===e;return{build:Ie("build",e?.build??t),bundler:Ie("bundler",e?.bundler??t),dependencies:Ie("dependencies",e?.dependencies??t),errors:Ie("errors",e?.errors??t),logs:Ie("logs",e?.logs??t),metrics:Ie("metrics",e?.metrics??t),timings:Ie("timings",e?.timings??t),warnings:Ie("warnings",e?.warnings??t)}},Fe=e=>t=>{t.hooks.done.tap("bundler-outputs",(t=>{const n=t.toJson({all:!1,assets:!0,children:!0,chunks:!0,chunkGroupAuxiliary:!0,chunkGroupChildren:!0,chunkGroups:!0,chunkModules:!0,chunkRelations:!0,entrypoints:!0,errors:!0,ids:!0,modules:!0,nestedModules:!0,reasons:!0,relatedAssets:!0,warnings:!0});e(n)}))},Le=e=>{const t=new Set;return{buildStart(){t.clear()},writeBundle(e,n){t.add(n)},closeBundle(){e(Array.from(t))}}},_e=({options:e,context:t})=>{const n=(e=>({enable:!!e[Ae],path:"./",...e[Ae],files:Ce(e[Ae]?.files)}))(e);if(!n.enable)return[];const o=(e,o)=>{const r=n.files[e];o&&!1!==r&&((e,t)=>{const n=JSON.stringify(t,null,4);U(e,n)})(((e,t,n)=>{const o=s.isAbsolute(t)?t:s.resolve(e,t);return s.resolve(o,n)})(t.bundler.outDir,n.path,r),o)};return[{name:"datadog-output-plugin",buildReport(e){const t=M(e);o("build",{bundler:t.bundler,metadata:t.metadata,start:t.start,end:t.end,duration:t.duration,writeDuration:t.writeDuration,entries:t.entries,outputs:t.outputs}),o("logs",t.logs),o("timings",t.timings),o("dependencies",t.inputs),o("errors",t.errors),o("warnings",t.warnings)},metrics(e){o("metrics",Array.from(e))},esbuild:{setup(e){e.onEnd((e=>{o("bundler",e.metafile)}))}},rspack:Fe((e=>{o("bundler",e)})),rollup:Le((e=>{o("bundler",e)})),vite:Le((e=>{o("bundler",e)})),webpack:Fe((e=>{o("bundler",e)}))}]};var Ke=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Ke||{});const He="rum",qe="datadog-rum-plugin",Be="datadog-rum-privacy-plugin";const We=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,Ue=(e,t)=>{const n=e.sdk;if(n.clientToken)return We(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 E({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 We({...e,sdk:{clientToken:o,...n}})}},Ge=e=>{const n=t.bold.red,o=e[He]||{},s={errors:[]};if(!o.sdk)return s;o.sdk.applicationId||s.errors.push(`Missing ${n("applicationId")} in the SDK configuration.`),e.auth.apiKey&&e.auth.appKey||o.sdk.clientToken||s.errors.push(`Missing ${n('"auth.apiKey"')} and/or ${n('"auth.appKey"')} to fetch missing client token.`);return s.config={applicationId:"unknown_application_id",allowUntrustedEvents:!1,compressIntakeRequests:!1,defaultPrivacyLevel:"mask",enablePrivacyForActionName:!1,sessionReplaySampleRate:0,sessionSampleRate:100,silentMultipleInit:!1,site:"datadoghq.com",startSessionReplayRecordingManually:!1,storeContextsAcrossPages:!1,telemetrySampleRate:20,traceSampleRate:100,trackingConsent:"granted",trackLongTasks:!1,trackResources:!1,trackUserInteractions:!1,trackViewsManually:!1,...o.sdk},s},Je=e=>{const t=e[He]||{},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},Ve=({options:e,context:t})=>{const n=((e,t)=>{const n=[],o=Ge(e),s=Je(e);if(n.push(...o.errors),n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${qe}.`);const r={enable:!!e[He],...e[He],sdk:void 0,privacy:void 0};return o.config&&(r.sdk=o.config),s.config&&(r.privacy=s.config,t.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(r.privacy,((e,t)=>t instanceof RegExp?t.toString():t))}`,{forward:!0})),r})(e,t.getLogger(qe)),o=[];if(!n.enable)return o;if(n.sdk&&(t.inject({type:"file",position:Ke.MIDDLE,value:s.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Ke.MIDDLE,value:Ue(n,t)})),n.privacy){t.inject({type:"file",position:Ke.BEFORE,value:s.join(__dirname,"./privacy-helpers.js")});const e=((e,t)=>{const n=t.getLogger(Be),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);return{name:Be,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(e,t){try{return m({id:t,code:e},o)}catch(t){return n.error(`Instrumentation Error: ${t}`,{forward:!0}),{code:e}}}}}})(n.privacy,t);o.push(e)}return o},Ye="datadog-analytics-plugin",Qe=({context:e})=>{const t=e.getLogger(Ye);return[{name:Ye,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}`)}})())}}]},Xe="datadog-async-queue-plugin",Ze=e=>{const{context:t,stores:n}=e,o=t.getLogger(Xe),s=[];return t.queue=e=>{const t=e.catch((e=>{s.push(e.message||e.toString())}));n.queue.push(t)},[{name:Xe,asyncTrueEnd:async()=>{await Promise.all(n.queue),s.length>0&&o.error(`Error occurred while processing async queue:\n ${s.join("\n ")}`)}}]},et=async(e,t,n)=>{const o=[],s=e.initialOptions.entryPoints,r=[],i=[];if(Array.isArray(s))for(const e of s){const t=e&&"object"==typeof e?e.in:e;r.push({path:t})}else s&&"object"==typeof s&&r.push(...Object.entries(s).map((([e,t])=>({name:e,path:t}))));const a=r.flatMap((e=>{return(t=e.path,t.includes("*")?f.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,s])=>{const r=await e.resolve(s,{kind:"entry-point",resolveDir:t.buildRoot});r.errors.length&&i.push(...r.errors.map((e=>e.text))),r.path&&o.push({name:n.name,resolved:r.path,original:n.path})}));for(const e of i)n.error(e);return await Promise.all(a),o},tt=(e,t)=>R(t)?w:t.startsWith(e)||s.isAbsolute(t)?t:s.resolve(e,t),nt=(e,t)=>{const n=[...e].map((e=>tt(t||process.cwd(),e).split(s.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(s.sep)||s.sep},ot=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,st=/(\?|%3F|\|)+/gi,rt=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=ut(e),ot.lastIndex=0,ot.exec(t)?.[1]||"unknown");var t},it=["unknown","commonjsHelpers.js",`vite${s.sep}preload-helper.js`],at=(e,t,n)=>{const o=new Set;for(const n of e){const e=ut(n);R(n)||e===t||it.includes(e)||o.add(e)}return o},ut=e=>e.split("!").pop().split(st).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/\\]+/,""),pt=(e,t)=>R(t)?w:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):((e,t)=>{const n=t.split(s.sep),o=e.split(s.sep).filter(((e,t)=>e===n[t])).join(s.sep);return e.replace(o,"")})(t.split("!").pop(),e).split("node_modules").pop().split(st).shift().replace(/^((\.\.?)?[/\\])+/g,""),ct=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[tt(t,e),n]))),lt=(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 et(n,e,t));for(const t of r){const n=pt(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"),a=e.bundler.outDir,u=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 p=[],c=[],l=[],d=[],m=[],f={},h={},g=t.time("indexing metafile data"),y=ct(n.metafile.inputs,u),b=ct(n.metafile.outputs,u);g.end();const w=e=>{if(!R(e))return e;const t=y[tt(u,e)];if(!t)return e;const n=t.imports.find((e=>!R(e.path)));return n?n.path:e},v=t.time("looping through inputs");for(const[e,t]of Object.entries(n.metafile.inputs)){if(R(e))continue;const n=tt(u,e),o={name:pt(a,e),filepath:n,dependents:new Set,dependencies:new Set,size:t.bytes,type:rt(e)};f[n]=o,p.push(o)}v.end();const $=t.time("looping through outputs");for(const[e,s]of Object.entries(n.metafile.outputs)){const n=tt(u,e),r=pt(a,n),i=[];for(const e of Object.keys(s.inputs)){if(R(e))continue;const n=f[tt(u,e)];n?i.push(n):t.debug(`Input ${e} not found for output ${r}`)}if(s.entryPoint&&!i.length){const e=f[tt(u,s.entryPoint)];if(!e){t.debug(`Input ${s.entryPoint} not found for output ${r}`);continue}i.push(e)}const p={name:r,filepath:n,inputs:i,size:s.bytes,type:rt(n)};if(h[n]=p,"map"===p.type&&d.push(p),c.push(p),!s.entryPoint)continue;const m=f[tt(u,w(s.entryPoint))];if(m){if(!o.get(m.name))continue;const e={...p,name:o.get(m.name)||m.name,outputs:[p],size:p.size};l.push(e)}}$.end();const k=t.time("looping through sourcemaps");for(const e of d){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 S={inputs:{report:f,meta:y},outputs:{report:h,meta:b}},E=/(<runtime>|https:|file:|data:|#)/g,D=e=>!R(e)&&!e.match(E),x=(e,n,o={})=>{if(!D(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(/^\.\.?\//),c=i?s.dirname(e):u,l=tt(c,t.path);if(t.external){if(D(t.path)){const e=i?l:t.path,n=S.inputs.report[e]||{filepath:e,name:pt(a,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),p.includes(n)||p.push(n),S.inputs.report[e]=n,o[n.filepath]=n}}else x(l,n,o)}return o},M=t.time("looping through entries");for(const e of l){const t={},n={};for(const n of e.inputs)x(n.filepath,S.inputs,t);for(const t of e.outputs)x(t.filepath,S.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),m.push(e)}M.end();const P=t.time("aggregate dependencies and dependents");for(const e of p){if("external"===e.type)continue;const n=S.inputs.meta[e.filepath];if(n)for(const o of n.imports){if(!D(o.path))continue;const n=o.path.match(/^\.?\.\//),r=n?s.dirname(e.filepath):u,i=tt(r,o.path);let a;if(o.external){const e=n?i:o.path;a=S.inputs.report[e]}else a=S.inputs.report[i];a?(e.dependencies.add(a),a.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}`)}P.end(),e.build.outputs=c,e.build.inputs=p,e.build.entries=m,i.end(),await e.asyncHook("buildReport",e.build)}))}}),dt=(e,t)=>{const n=t.time("module parsing",{start:!1}),o=t.time("build report",{start:!1}),s=t.time("filling entries",{start:!1}),r=t.time("filling inputs and outputs",{start:!1}),i=t.time("completing dependencies and dependents",{start:!1}),a=t.time("filling dependencies and dependents",{start:!1}),u=t.time("filling sourcemaps inputs",{start:!1}),p=new Map,c=new Map,l=new Map,d=new Map;return{buildStart(){d.clear(),p.clear(),c.clear(),l.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=ut(e.id),o=d.get(t)||{dependencies:new Set,dependents:new Set},s=at(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=at(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)o.dependents.add(e);for(const e of s)o.dependencies.add(e);d.set(t,o),n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,m){o.resume();const f=n.dir?tt(e.buildRoot,n.dir):e.bundler.outDir,h=new Set,g=new Set,y=new Map;i.resume();for(const[e,{dependencies:t,dependents:n}]of d){for(const n of t){const t=ut(n),o=d.get(t)||{dependencies:new Set,dependents:new Set};o.dependents.has(e)||(o.dependents.add(e),d.set(t,o))}for(const t of n){const n=ut(t),o=d.get(n)||{dependencies:new Set,dependents:new Set};o.dependencies.has(e)||(o.dependencies.add(e),d.set(n,o))}}i.end(),r.resume();for(const[e,n]of Object.entries(m)){const o=tt(f,e),s="code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),r=c.get(o)||{name:e,filepath:o,inputs:[],size:s,type:rt(e)};if("map"===r.type&&g.add(r),"modules"in n)for(const[e,t]of Object.entries(n.modules)){if(ut(e)!==e)continue;const n=p.get(e)||{name:pt(f,e),dependencies:new Set,dependents:new Set,filepath:e,size:t.originalLength,type:rt(e)};r.inputs.push(n),p.set(n.filepath,n)}if("imports"in n)for(const e of n.imports){const n=ut(e);if(!d.has(n)){y.set(tt(f,n),r);continue}if(p.has(n)){t.debug(`Input report already there for ${n} from ${r.name}.`);continue}const o=p.get(n)||{name:pt(f,e),dependencies:new Set,dependents:new Set,filepath:n,size:0,type:"external"};r.inputs.push(o),p.set(o.filepath,o)}"isEntry"in n&&n.isEntry&&h.add({...r,name:n.name,size:0,outputs:[r]}),c.set(r.filepath,r)}r.end();for(const[e,n]of y){const o=c.get(e);o?n.inputs.includes(o)||n.inputs.push(o):t.debug(`Could not find the output report for ${e}.`)}a.resume();for(const[e,n]of p){const o=d.get(e);if(o){for(const e of o.dependencies){const o=p.get(e);o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${pt(f,e)} of ${n.name}`)}for(const e of o.dependents){const o=p.get(e);o?n.dependents.add(o):t.debug(`Could not find input for dependent ${pt(f,e)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(a.end(),g.size){u.resume();for(const e of g){const n=e.filepath.replace(/\.map$/,""),o=c.get(n);o?e.inputs.push(o):t.debug(`Could not find output for sourcemap ${e.name}`)}u.end()}const b=(e,n=new Map)=>{if(n.has(e))return n;const o=pt(f,e),s=c.get(e);if(!s)return p.has(o)||t.debug(`Could not find output for ${o}`),n;n.set(e,s);const r=m[pt(f,e)];if(!r)return t.debug(`Could not find asset for ${o}`),n;const i=[];"imports"in r&&i.push(...r.imports),"dynamicImports"in r&&i.push(...r.dynamicImports);for(const e of i)b(tt(f,e),n);return n};s.resume();for(const e of h){const n=b(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),l.has(e.filepath)&&t.debug(`Entry "${e.name}":"${pt(f,e.filepath)}" already reported.`),l.set(e.filepath,e)}s.pause(),o.pause()},async closeBundle(){e.build.inputs=Array.from(p.values()),e.build.outputs=Array.from(c.values()),e.build.entries=Array.from(l.values()),s.end(),o.end(),await e.asyncHook("buildReport",e.build)}}},mt=(e,t,n)=>o=>{let s=[],r=[],i=[];const a=new Map,u=new Map,p=new Map,c=new Map,l=[],d=new Map,m=n.time("build report",{start:!1}),f=e=>!(!e||e.startsWith("webpack/runtime")||e.startsWith("multi ")||R(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=ut(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(c.has(e)){const n=c.get(e);n.dependencies.push(...t.dependencies||[]),n.blocks.push(...t.blocks||[])}else c.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=ut(t.request);if(c.has(n))return c.get(n);if(e.context){const t=tt(ut(e.context),n);if(c.has(t))return c.get(t)}}},w=e=>!(!("externalType"in e)||!e.externalType)||(!(!("external"in e)||!e.external)||!!e.identifier?.().startsWith("external "));o.hooks.thisCompilation.tap(t,(o=>{s=[],r=[],i=[],a.clear(),u.clear(),c.clear(),d.clear(),o.hooks.finishModules.tap(t,(t=>{m.resume();const o=n.time("dependency graph"),r=n.time("indexing modules");for(const e of t)g(e);r.end();const i=n.time("building inputs");for(const n of t){const t=n.identifier(),o=pt(e.bundler.outDir,t),r=new Set(y(n).map((e=>{const o=b(n,e);if(!o?.identifier())return!1;const s=o.identifier();return!!f(s)&&(s!==t&&(w(o)?h(s):s))})).filter(Boolean));if(!f(t))continue;const i=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of r){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),i.dependencies.add(e),d.set(e,n)}d.set(t,i);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:rt(t)};s.push(u),a.set(t,u),w(n)&&a.set(h(t),u)}i.end();const u=n.time("assigning dependencies and dependents");for(const e of s){const t=d.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(),m.pause()}))})),o.hooks.afterEmit.tapPromise(t,(async t=>{m.resume();const o=t.chunks,c=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>tt(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of o){const t=d(e),n=(g?.getChunkModules(e)||[]).flatMap((e=>"modules"in e&&Array.isArray(e.modules)?e.modules.map((e=>e.identifier())):e.identifier())).filter(f);for(const e of t){if("map"===rt(e))continue;const t=p.get(e)||new Set;for(const e of n)t.add(e);p.set(e,t)}}h.end();const y=n.time("building outputs");for(const t of c){const o={size:t.source.size()||0,name:t.name,inputs:[],filepath:tt(e.bundler.outDir,t.name),type:rt(t.name)};if(u.set(o.filepath,o),r.push(o),"map"===o.type){l.push(o);continue}const s=p.get(o.filepath);if(s)for(const e of s){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");for(const[o,s]of t.entrypoints){const t=new Map,r=new Map;let a=0;const p=s.chunks.flatMap(d),c=s.chunks.filter((e=>g.getChunkEntryModulesIterable(e)||!1)).flatMap((e=>Array.from(e.files))).filter((e=>e.includes(o)||s.name&&e.includes(s.name))).find((e=>"js"===rt(e)));for(const e of p){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)r.has(e.filepath)||r.set(e.filepath,e);a+=o.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const l={name:o,filepath:c?tt(e.bundler.outDir,c):"unknown",size:a,inputs:Array.from(r.values()),outputs:Array.from(t.values()),type:c?rt(c):"unknown"};i.push(l)}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=s,e.build.outputs=r,e.build.entries=i,m.end(),await e.asyncHook("buildReport",e.build)}))},ft="datadog-build-report-plugin",ht=e=>{const{context:t}=e,n=t.getLogger(ft);return[{name:ft,enforce:"post",esbuild:lt(t,n),rspack:mt(t,ft,n),webpack:mt(t,ft,n),vite:dt(t,n),rollup:dt(t,n)}]},gt="datadog-bundler-report-plugin",yt=(e,t)=>t?s.isAbsolute(t)?t:s.resolve(e,t):"",bt=e=>{if(!e)return[];return(Array.isArray(e)?e:[e]).map((e=>e.dir?e.dir:e.file?s.dirname(e.file):void 0)).filter(Boolean)},wt=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=yt(process.cwd(),t.options.output.path)),e.hook("bundlerReport",e.bundler),t.options.context&&(e.buildRoot=t.options.context),e.hook("buildRoot",e.buildRoot)},vt=e=>({configResolved(t){e.bundler.rawConfig=t;let n=t.build?.outDir??"dist";const o=t.build?.rollupOptions?.output,s=bt(o);e.buildRoot=t.root??process.cwd(),o&&s.length&&(n=nt(s,process.cwd())),e.bundler.outDir=yt(e.buildRoot,n),e.hook("buildRoot",e.buildRoot),e.hook("bundlerReport",e.bundler)}}),$t=e=>{const{context:t}=e,n=t.getLogger(gt);return[{name:gt,enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.absWorkingDir&&(t.buildRoot=e.initialOptions.absWorkingDir),e.initialOptions.outdir&&(t.bundler.outDir=yt(t.buildRoot,e.initialOptions.outdir)),e.initialOptions.outfile&&(t.bundler.outDir=yt(t.buildRoot,s.dirname(e.initialOptions.outfile))),t.hook("buildRoot",t.buildRoot),t.hook("bundlerReport",t.bundler),e.initialOptions.metafile=!0}},webpack:wt(t),rspack:wt(t),vite:vt(t),rollup:{options(e){let n;if("output"in e){const t=bt(e.output);n=nt(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(s.dirname(e))}}return Array.from(t)})(e);if(n){t.bundler.outDir=tt(process.cwd(),n);const e=nt([n,...o],process.cwd());t.buildRoot=e===s.sep?process.cwd():e}else t.buildRoot=nt(o,process.cwd()),t.bundler.outDir=s.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=bt(e);nt(o,process.cwd()).startsWith(t.bundler.outDir)||n.info("The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.")}}}]},kt="datadog-custom-hooks-plugin",St=e=>{const{context:t}=e,n=t.getLogger(kt),o=e=>(o,...s)=>{const r=n.time(`execution | ${o}`,{tags:["type:custom-hook",`hook:${o}`]}),i=[],a=[];for(const n of t.plugins){if(!(o in n))continue;const t=n[o];if("function"==typeof t)try{const r=t(...s);r instanceof Promise&&(e||i.push(`Plugin "${n.name}" returned a promise on the non async hook "${o}".`),a.push(r))}catch(e){i.push(`Plugin "${n.name}" errored on hook "${o}". [${e}]`)}else i.push(`Plugin "${n.name}" has an invalid hook type for "${o}". [${typeof t}]`)}if(i.length>0){for(const e of i)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>r.end()))};return t.hook=o(!1),t.asyncHook=o(!0),[{name:kt,enforce:"pre"}]};class Et{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=(o=e,a.readFileSync(o,{encoding:"utf-8"}));var o;const s=JSON.parse(n);if(!s.sources)return void t("Missing 'sources' field in sourcemap.");const r=s.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 s=this.trackedFilenames.get(e);s&&(t=t.concat(s))}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 Dt=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await xt(e);for(const e of t)if(e.name===n)return O(e.refs.push);return O(t[0].refs.push)},xt=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},Rt=async e=>e.revparse("HEAD"),Mt=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),Pt=async e=>e.branch(),Tt=async e=>e.show(["-s","--format=%s"]),jt=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),Ot="datadog-git-plugin",zt=e=>{const{options:t,context:n}=e,o=n.getLogger(Ot),r=o.time("get git information",{start:!1}),i=async e=>{try{const t=await(async e=>{const t=[Rt(e),Pt(e),Tt(e),jt(e),Mt(e),Dt(e)],[n,o,s,r,i,a]=await Promise.all(t),[u,p,c,l,d,m]=r.split(",").map((e=>e.trim()));return{commit:{author:{name:u,email:p,date:c},committer:{name:l,email:d,date:m},message:s.trim(),hash:n},hash:n,branch:o.current,remote:a.trim(),trackedFilesMatcher:new Et(i)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=h(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return h(t)})(s.dirname(e)));n.git=t,r.end(),await n.asyncHook("git",n.git)}catch(e){o.error(`Could not get git information: ${e.message}`)}};return[{name:Ot,enforce:"pre",buildRoot(e){if(P(t))try{r.resume();const t=((e,t)=>{let n,o=tt(process.cwd(),e);for(;!n;){const e=s.resolve(o,t);if(G(e)&&(n=e),o=o.split(s.sep).slice(0,-1).join(s.sep),[s.sep,""].includes(o))break}return n})(e,".git");if(!t)return void o.warn("No .git directory found, skipping git plugin.");n.queue(i(t))}catch(e){o.error(`Could not get git information: ${e.message}`)}}}]},Nt="datadog-injection-plugin",At=/^https?:\/\//,It=async(e,t=process.cwd())=>(e=>i.readFile(e,{encoding:"utf-8"}))(tt(t,e)),Ct=async(e,t,n=process.cwd())=>{let o;const s=await(async e=>"function"==typeof e.value?e.value():e.value)(e);try{if("file"===e.type)o=s.match(At)?await(async(e,t=5e3)=>{let n;return Promise.race([E({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,o)=>{n=setTimeout((()=>{o(new Error("Timeout"))}),t)}))])})(s):await It(s,n);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);o=s}}catch(r){const i=`${e.type} - ${j(s)}`;e.fallback?(t.info(`Fallback for "${i}": ${r.toString()}`),o=await Ct(e.fallback,t,n)):t.warn(`Failed "${i}": ${r.toString()}`)}return o},Ft=e=>{if(0===e.size)return"";return`// begin injection by Datadog build plugins\n${Array.from(e.values()).map((e=>`(() => {${e}})();`)).join("\n\n")}\n// end injection by Datadog build plugins`},Lt=async(e,t,n,o=process.cwd())=>{const s=await(async(e,t,n=process.cwd())=>{const o=new Map;for(const[s,r]of e.entries()){const e=await Ct(r,t,n);e&&o.set(s,{value:e,position:r.position||Ke.BEFORE})}return o})(t,e,o);for(const[e,t]of s.entries())n[t.position].set(e,t.value)},_t=a.promises,Kt=(e,t,n)=>({setup(o){const{onStart:r,onResolve:i,onLoad:u,onEnd:p,esbuild:c,initialOptions:l}=o,d=[],m=`${t.bundler.name}.${Ke.MIDDLE}.${w}.js`,f=a.realpathSync(g.tmpdir()),h=s.resolve(f,m),y=new RegExp(`${m}$`),b=l.inject;l.inject=b?[...b]:[],l.inject.push(h),r((async()=>{d.push(...await et(o,t,e)),o.initialOptions.inject=b;try{await W(h,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),i({filter:y},(async e=>({path:e.path,namespace:Nt}))),u({filter:y,namespace:Nt},(async()=>({contents:Ft(n[Ke.MIDDLE])||" ",resolveDir:t.buildRoot,loader:"js"}))),p((async o=>{if(!o.metafile)return void e.warn("Missing metafile from build result.");const s=Ft(n[Ke.BEFORE]),r=Ft(n[Ke.AFTER]);if(!s&&!r)return;const i=Object.entries(o.metafile.outputs).map((([e,n])=>{const o=n.entryPoint;if(!o)return;return d.find((e=>e.resolved.endsWith(o)))?tt(t.buildRoot,e):void 0})).filter(Boolean).map((async t=>{try{const e=await _t.readFile(t,"utf-8"),n=await c.transform(e,{loader:"default",banner:s,footer:r});await _t.writeFile(t,n.code)}catch(n){if(!(e=>e instanceof Error&&"code"in e)(n)||"ENOENT"!==n.code)throw n;e.warn(`Could not inject content in ${t}: ${n}`)}}));await Promise.all(i)}))}}),Ht=w,qt="?inject-proxy",Bt=e=>({banner:t=>t.isEntry?Ft(e[Ke.BEFORE]):"",async resolveId(t,n,o){if(R(t))return{id:t,moduleSideEffects:!0};if(o.isEntry&&Ft(e[Ke.MIDDLE])){const e=await this.resolve(t,n,o);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${qt}`}return null},load(t){if(R(t))return Ft(e[Ke.MIDDLE]);if(t.endsWith(qt)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let o=`import ${JSON.stringify(Ht)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(o+=`export { default } from ${JSON.stringify(e)};`),o}return null},footer:t=>t.isEntry?Ft(e[Ke.AFTER]):""}),Wt=(e,t,n,o,r)=>i=>{const u=new WeakMap,p=e.sources.ConcatSource,c=n.bundler.name,l=s.resolve(n.bundler.outDir,`${c}.${Ke.MIDDLE}.${w}.js`);U(l,"");i.hooks.shutdown.tap(Nt,(()=>{var e;e=l,a.rmSync(e,{force:!0,maxRetries:3,recursive:!0})}));i.hooks.beforeRun.tapPromise(Nt,(async()=>{await Lt(t,o,r,n.buildRoot)})),i.hooks.compilation.tap(Nt,(t=>{const n=e.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;t.hooks.processAssets.tap({name:Nt,stage:n},(()=>{const e=Ft(r[Ke.BEFORE]),n=Ft(r[Ke.AFTER]);for(const o of t.chunks)if(o.canBeInitial())for(const s of o.files)t.updateAsset(s,(t=>{const o=u.get(t);if(!o||o.banner!==e||o.footer!==n){const o=new p(e,"\n",t,"\n",n);return u.set(t,{source:o,banner:e,footer:n}),o}return o.source}))}))}));const d=(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=d},Ut=e=>{const{bundler:t,context:n}=e,o=n.getLogger(Nt),s=new Map,r={[Ke.BEFORE]:new Map,[Ke.MIDDLE]:new Map,[Ke.AFTER]:new Map};n.inject=e=>{s.set(`${Date.now()}.${performance.now()}.${++z}`,e)};const i={name:Nt,enforce:"post",esbuild:Kt(o,n,r),webpack:Wt(t,o,n,s,r),rspack:Wt(t,o,n,s,r),rollup:Bt(r),vite:{...Bt(r),enforce:"pre"}};var a;return a=n.bundler.name,["rspack","webpack"].includes(a)?i.load={filter:{id:v},handler:()=>({code:Ft(r[Ke.MIDDLE])})}:i.buildStart=async()=>{await Lt(o,s,r,n.buildRoot)},[i]},Gt="datadog-true-end-plugin",Jt=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},o=()=>{t.hook("syncTrueEnd")},s=async()=>{o(),await n()},r=e=>{e.hooks.shutdown.tapPromise(Gt,s)},i={async writeBundle(){},async closeBundle(){await s()}};return[{name:Gt,enforce:"post",webpack:r,esbuild:{setup(e){e.onEnd((async()=>{await n()})),e.onDispose((()=>{o()}))}},vite:i,rollup:i,rspack:r}]},Vt={[pe]:ze};var Yt="2.6.5-0";const Qt=(({bundler:n,version:o})=>{const s=Date.now();return e(((e,r)=>{const i=((e={})=>{const t={site:b("SITE")||e.auth?.site||"datadoghq.com"};return Object.defineProperty(t,"apiKey",{value:b("API_KEY")||e.auth?.apiKey,enumerable:!1}),Object.defineProperty(t,"appKey",{value:b("APP_KEY")||e.auth?.appKey,enumerable:!1}),{enableGit:!0,logLevel:"warn",metadata:{},...e,auth:t}})(e);"esbuild"===r.framework&&(r.esbuildHostName=k);const a=process.env.BUILD_PLUGINS_ENV||"production",u=$.includes(a)?a:"development",p=n.rspackVersion||n.version||n.VERSION,c=r.framework,l={bundler:{name:c,version:p},env:u,metadata:i.metadata||{},packageName:`@datadog/${c}-plugin`,version:o},d={errors:[],logs:[],queue:[],timings:[],warnings:[]},m=(({start:e,options:t,data:n,stores:o})=>{const s=process.cwd(),r={errors:o.errors,warnings:o.warnings,logs:o.logs,metadata:n.metadata,timings:o.timings,bundler:n.bundler};return{auth:t.auth,pluginNames:[],bundler:{...r.bundler,outDir:s},build:r,buildRoot:s,env:n.env,getLogger:F(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:D(n),start:e,version:n.version}})({start:s,options:i,data:l,stores:d}),f=m.getLogger("factory").time("Plugins initialization",{start:s});m.pluginNames.push(k);const h=[];h.push(["analytics",Qe],["async-queue",Ze],["build-report",ht],["bundler-report",$t],["custom-hooks",St],["git",zt],["injection",Ut],["true-end",Jt]),i.customPlugins&&h.push(["custom",i.customPlugins]),h.push(["error-tracking",ae],["metrics",Ne],["output",_e],["rum",Ve]);for(const[e,t]of h)m.plugins.push(...K(m,t,e)({bundler:n,context:m,options:i,data:l,stores:d}));m.pluginNames.push(...m.plugins.map((e=>e.name)));const g=new Set(m.pluginNames.filter((e=>m.pluginNames.filter((t=>t===e)).length>1)));if(g.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(g).join(", "))}`);return m.hook("init",m),f.end(),m.plugins}))})({bundler:y,version:Yt}).webpack,Xt=Yt,Zt=Vt;export{Qt as datadogWebpackPlugin,Zt as helpers,Xt as version};
13
13
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../../factory/src/validate.ts","../../../../plugins/error-tracking/src/sourcemaps/index.ts"],"sourcesContent":["// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Options, OptionsWithDefaults } from '@dd/core/types';\n\nexport const validateOptions = (options: Options = {}): OptionsWithDefaults => {\n return {\n auth: {},\n disableGit: false,\n logLevel: 'warn',\n metadata: {},\n ...options,\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\nimport chalk from 'chalk';\nimport { outdent } from 'outdent';\n\nimport type { ErrorTrackingOptionsWithSourcemaps } from '../types';\n\nimport type { SourcemapsFilesContext } from './files';\nimport { getSourcemapsFiles } from './files';\nimport type { SourcemapsSenderContext } from './sender';\nimport { sendSourcemaps } from './sender';\n\nexport type UploadSourcemapsContext = SourcemapsSenderContext & SourcemapsFilesContext;\n\nexport const uploadSourcemaps = async (\n options: ErrorTrackingOptionsWithSourcemaps,\n context: UploadSourcemapsContext,\n log: Logger,\n) => {\n // Show a pretty summary of the configuration.\n const green = chalk.green.bold;\n const configurationString = Object.entries(options.sourcemaps)\n .map(([key, value]) => ` - ${key}: ${green(value.toString())}`)\n .join('\\n');\n\n // Gather the sourcemaps files.\n const sourcemapsTime = log.time('get sourcemaps files');\n const sourcemaps = getSourcemapsFiles(options.sourcemaps, {\n outDir: context.outDir,\n outputs: context.outputs,\n });\n sourcemapsTime.end();\n\n const summary = outdent`\n Uploading ${green(sourcemaps.length.toString())} sourcemaps with configuration:\n ${configurationString}\n `;\n\n log.info(summary);\n\n // Send everything.\n const sendTime = log.time('send sourcemaps');\n await sendSourcemaps(\n sourcemaps,\n options.sourcemaps,\n {\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n git: context.git,\n outDir: context.outDir,\n version: context.version,\n },\n log,\n );\n sendTime.end();\n};\n"],"names":["green","configurationString","log"],"mappings":";;;;;;;;AAMO;AC+BSA;AACVC;AAGFC"}
1
+ {"version":3,"file":"index.mjs","sources":["../../../../factory/src/validate.ts","../../../../plugins/error-tracking/src/sourcemaps/index.ts"],"sourcesContent":["// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { AuthOptionsWithDefaults, Options, OptionsWithDefaults } from '@dd/core/types';\n\nconst getEnvValue = (key: string) => {\n return process.env[`DATADOG_${key}`] || process.env[`DD_${key}`];\n};\n\nexport const validateOptions = (options: Options = {}): OptionsWithDefaults => {\n const auth: AuthOptionsWithDefaults = {\n // DATADOG_SITE env var takes precedence over configuration\n site: getEnvValue('SITE') || options.auth?.site || 'datadoghq.com',\n };\n\n // Prevent these from being accidentally logged.\n Object.defineProperty(auth, 'apiKey', {\n value: getEnvValue('API_KEY') || options.auth?.apiKey,\n enumerable: false,\n });\n\n Object.defineProperty(auth, 'appKey', {\n value: getEnvValue('APP_KEY') || options.auth?.appKey,\n enumerable: false,\n });\n\n return {\n enableGit: true,\n logLevel: 'warn',\n metadata: {},\n ...options,\n auth,\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\nimport chalk from 'chalk';\nimport { outdent } from 'outdent';\n\nimport type { ErrorTrackingOptionsWithSourcemaps } from '../types';\n\nimport type { SourcemapsFilesContext } from './files';\nimport { getSourcemapsFiles } from './files';\nimport type { SourcemapsSenderContext } from './sender';\nimport { sendSourcemaps } from './sender';\n\nexport type UploadSourcemapsContext = SourcemapsSenderContext & SourcemapsFilesContext;\n\nexport const uploadSourcemaps = async (\n options: ErrorTrackingOptionsWithSourcemaps,\n context: UploadSourcemapsContext,\n log: Logger,\n) => {\n // Show a pretty summary of the configuration.\n const green = chalk.green.bold;\n const configurationString = Object.entries(options.sourcemaps)\n .map(([key, value]) => ` - ${key}: ${green(value.toString())}`)\n .join('\\n');\n\n // Gather the sourcemaps files.\n const sourcemapsTime = log.time('get sourcemaps files');\n const sourcemaps = getSourcemapsFiles(options.sourcemaps, {\n outDir: context.outDir,\n outputs: context.outputs,\n });\n sourcemapsTime.end();\n\n const summary = outdent`\n Uploading ${green(sourcemaps.length.toString())} sourcemaps with configuration:\n ${configurationString}\n `;\n\n log.info(summary);\n\n // Send everything.\n const sendTime = log.time('send sourcemaps');\n await sendSourcemaps(\n sourcemaps,\n options.sourcemaps,\n {\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n git: context.git,\n outDir: context.outDir,\n site: context.site,\n version: context.version,\n },\n log,\n );\n sendTime.end();\n};\n"],"names":["green","configurationString","log"],"mappings":";;;;;;;;AAMA;AC+BgBA;AACVC;AAGFC"}