@datadog/rollup-plugin 2.6.3-dev-3 → 2.6.3-dev-5

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.
@@ -39,9 +39,6 @@ interface PrivacyOptions {
39
39
  include?: RegExp[] | string[];
40
40
  helpersModule?: string;
41
41
  addToDictionaryFunctionName?: string;
42
- module?: 'cjs' | 'esm';
43
- jsx?: boolean;
44
- typescript?: boolean;
45
42
  disabled?: boolean | undefined;
46
43
  }
47
44
 
@@ -118,6 +115,13 @@ type Output = FileReport & {
118
115
  type Entry = Output & {
119
116
  outputs: Output[];
120
117
  };
118
+ type Log = {
119
+ bundler?: BundlerFullName;
120
+ pluginName: string;
121
+ type: LogLevel;
122
+ message: string;
123
+ time: number;
124
+ };
121
125
  type LogTags = string[];
122
126
  type Timer = {
123
127
  label: string;
@@ -135,18 +139,12 @@ type BuildMetadata = {
135
139
  name?: string;
136
140
  };
137
141
  type BuildReport = {
138
- bundler: Omit<BundlerReport, 'outDir' | 'rawConfig'>;
139
- errors: string[];
140
- warnings: string[];
141
- logs: {
142
- bundler: BundlerFullName;
143
- pluginName: string;
144
- type: LogLevel;
145
- message: string;
146
- time: number;
147
- }[];
148
- metadata: BuildMetadata;
149
- timings: Timer[];
142
+ bundler: GlobalData['bundler'];
143
+ errors: GlobalStores['errors'];
144
+ warnings: GlobalStores['warnings'];
145
+ logs: GlobalStores['logs'];
146
+ timings: GlobalStores['timings'];
147
+ metadata: GlobalData['metadata'];
150
148
  entries?: Entry[];
151
149
  inputs?: Input[];
152
150
  outputs?: Output[];
@@ -157,13 +155,9 @@ type BuildReport = {
157
155
  };
158
156
  type BundlerFullName = (typeof FULL_NAME_BUNDLERS)[number];
159
157
  type BundlerName = (typeof SUPPORTED_BUNDLERS)[number];
160
- type BundlerReport = {
161
- name: BundlerName;
162
- fullName: BundlerFullName;
158
+ type BundlerReport = GlobalData['bundler'] & {
163
159
  outDir: string;
164
160
  rawConfig?: any;
165
- variant?: string;
166
- version: string;
167
161
  };
168
162
  type InjectedValue = string | (() => Promise<string>);
169
163
  declare enum InjectPosition {
@@ -193,13 +187,23 @@ type TimeLog = (label: string, opts?: {
193
187
  tags?: LogTags;
194
188
  }) => TimeLogger;
195
189
  type GetLogger = (name: string) => Logger;
190
+ type LogOptions = {
191
+ forward?: boolean;
192
+ };
193
+ type LoggerFn = (text: any, opts?: LogOptions) => void;
196
194
  type Logger = {
197
195
  getLogger: GetLogger;
198
196
  time: TimeLog;
199
- error: (text: any) => void;
200
- warn: (text: any) => void;
201
- info: (text: any) => void;
202
- debug: (text: any) => void;
197
+ error: LoggerFn;
198
+ warn: LoggerFn;
199
+ info: LoggerFn;
200
+ debug: LoggerFn;
201
+ };
202
+ type RestContext = string | string[] | number | boolean;
203
+ type LogData = Record<string, RestContext | Record<string, RestContext>>;
204
+ type DdLogOptions = {
205
+ message: string;
206
+ context?: LogData;
203
207
  };
204
208
  type Env = (typeof ALL_ENVS)[number];
205
209
  type TriggerHook<R> = <K extends keyof CustomHooks>(name: K, ...args: Parameters<NonNullable<CustomHooks[K]>>) => R;
@@ -209,16 +213,17 @@ type GlobalContext = {
209
213
  build: BuildReport;
210
214
  bundler: BundlerReport;
211
215
  cwd: string;
212
- env: Env;
216
+ env: GlobalData['env'];
213
217
  getLogger: GetLogger;
214
218
  git?: RepositoryData;
215
219
  hook: TriggerHook<void>;
216
220
  inject: (item: ToInjectItem) => void;
217
221
  pluginNames: string[];
218
222
  plugins: (PluginOptions | CustomPluginOptions)[];
219
- sendLog: (message: string, ctx?: any) => Promise<void>;
223
+ queue: (promise: Promise<any>) => void;
224
+ sendLog: (args: DdLogOptions) => Promise<void>;
220
225
  start: number;
221
- version: string;
226
+ version: GlobalData['version'];
222
227
  };
223
228
  type HookFn<T extends Array<any>> = (...args: T) => void;
224
229
  type AsyncHookFn<T extends Array<any>> = (...args: T) => Promise<void> | void;
@@ -241,6 +246,8 @@ type GetPluginsArg = {
241
246
  bundler: any;
242
247
  context: GlobalContext;
243
248
  options: Options;
249
+ data: GlobalData;
250
+ stores: GlobalStores;
244
251
  };
245
252
  type GetCustomPlugins = (arg: GetPluginsArg) => CustomPluginOptions[];
246
253
  type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';
@@ -261,6 +268,25 @@ interface Options extends BaseOptions {
261
268
  customPlugins?: GetCustomPlugins;
262
269
  }
263
270
  type PluginName = `datadog-${Lowercase<string>}-plugin`;
271
+ type GlobalData = {
272
+ bundler: {
273
+ name: BundlerName;
274
+ fullName: BundlerFullName;
275
+ variant: string;
276
+ version: string;
277
+ };
278
+ env: Env;
279
+ metadata: BuildMetadata;
280
+ packageName: string;
281
+ version: string;
282
+ };
283
+ type GlobalStores = {
284
+ errors: string[];
285
+ logs: Log[];
286
+ queue: Promise<any>[];
287
+ timings: Timer[];
288
+ warnings: string[];
289
+ };
264
290
 
265
291
  interface Metric {
266
292
  metric: string;
package/dist/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var e=require("unplugin"),t=require("chalk"),n=require("buffer"),s=require("fs/promises"),o=require("fs"),i=require("path"),r=require("stream"),a=require("outdent"),u=require("async-retry"),c=require("p-queue"),p=require("zlib"),l=require("@datadog/js-instrumentation-wasm"),d=require("@rollup/pluginutils"),m=require("node:fs"),f=require("node:path"),h=require("pretty-bytes"),g=require("perf_hooks"),y=require("glob"),w=require("simple-git"),b=require("os"),v=require("module"),$=require("rollup");const k="__datadog-helper-file",S=["development","production","test"],D="datadog-build-plugins",E=async(e,t)=>{await(async e=>s.mkdir(e,{recursive:!0}))(i.dirname(e)),await s.writeFile(e,t,{encoding:"utf-8"})},M=(e,t)=>{var n;n=i.dirname(e),o.mkdirSync(n,{recursive:!0}),o.writeFileSync(e,t,{encoding:"utf-8"})},x=e=>{try{return o.existsSync(e)}catch(e){if("ENOENT"===e.code)return!1;throw e}},P=async(e,t)=>{if("function"==typeof o.openAsBlob){const s=await o.openAsBlob(e,{type:t.contentType});return new n.File([s],t.filename)}{const s=r.Readable.toWeb(o.createReadStream(e)),i=await new Response(s).blob();return new n.File([i],t.filename,{type:t.contentType})}},j=async e=>{const t={empty:!1,exists:!0};try{const{size:n}=await s.stat(e);0===n&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t},T=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),O=e=>e.includes(k),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(),i=n.getUTCSeconds(),r=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${s?`${s}h `:""}${o?`${o}m `:""}${i?`${i}s`:""}`.trim();return`${a}${!a||r?` ${r}ms`:""}`.trim()},N=(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)),i=s-o;return`${e.slice(0,o)}${n}${e.slice(-i)}`},R=(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 I=0;const A=()=>`${Date.now()}.${performance.now()}.${++I}`,F={debug:0,info:1,warn:2,error:3,none:4},C=(e,n="warn")=>s=>{const o=(e=>e.split(">").map(T).join(">"))(s),i=(i,r="debug")=>{let a=t.dim,u=console.log;"error"===r?(a=t.red,u=console.error):"warn"===r?(a=t.yellow,u=console.warn):"info"===r&&(a=t.cyan,u=console.log);const c=`[${e.metadata?.name?`${e.metadata.name}|`:""}${r}|${e.bundler.fullName}|${o}]`,p="string"==typeof i?i:JSON.stringify(i,null,2);e.logs.push({bundler:e.bundler.fullName,pluginName:s,type:r,message:p,time:Date.now()}),"error"===r&&e.errors.push(p),"warn"===r&&e.warnings.push(p),F[r]>=F[n]&&u(`${a(c)} ${p}`)};return{getLogger:t=>C(e,n)(`${o}>${t}`),time:(n,o={})=>{const{level:r="debug",start:a=!0,log:u=!0,tags:c=[]}=o,p={pluginName:s,label:n,spans:[],tags:[...c,`plugin:${s}`,`level:${r}`],logLevel:r,total:0};e.timings.push(p);const l=()=>p.spans.filter((e=>!e.end)),d=e=>{l().length||(!p.spans.length&&u&&i(t.dim(`[${t.cyan(n)}] : start`),"debug"),p.spans.push({start:e||Date.now(),tags:[`plugin:${s}`]}))},m=e=>{const s=l();if(s?.length){s.length>1&&i(`Timer ${t.cyan(n)} has more than one ongoing span.`,"debug");for(const t of s)t.end=e||Date.now()}else i(`Timer ${t.cyan(n)} 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);const s=p.spans.reduce(((e,t)=>e+(t.end-t.start)),0);p.total=s,u&&i(`[${t.cyan(n)}] : ${t.cyan(z(s))}`,r)},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)}}},error:e=>i(e,"error"),warn:e=>i(e,"warn"),info:e=>i(e,"info"),debug:e=>i(e,"debug")}},L=["buildEnd","buildStart","load","loadInclude","resolveId","transform","transformInclude","watchChange","writeBundle","cwd","init","buildReport","bundlerReport","git"],_=(e,t,n,s)=>(...o)=>{const i=s.time(`${e} | ${t}`,{log:!1,tags:["type:hook",`hook:${t}`]}),r=n(...o);return r instanceof Promise?r.finally((()=>{i.end()})):(i.end(),r)},q=(e,t,n)=>{const s=e.getLogger(D);return e=>{const o=s.time(`hook | init ${n}`,{log:!1}),i=t(e).map((e=>((e,t)=>{const n={...e},s=T(e.name);for(const o of L){const i=e[o];i&&(n[o]=_(s,o,i,t))}return n})(e,s))),r=i.map((e=>`plugin:${e.name}`));return o.tag(r),o.end(),i}},H="errorTracking",W="datadog-error-tracking-plugin",B=(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.bundler.outDir,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.minifiedPathPrefix,r);return{minifiedFilePath:o,minifiedUrl:a,relativePath:r}},K=[400,403,413],U=e=>{const{auth:t,url:n,method:s="GET",getData:o,type:i="text"}=e,r={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return u((async(e,r)=>{let a;try{const e={method:s,duplex:"half"};let i={"X-Datadog-Origin":"build-plugins"};if(t?.apiKey&&(i["DD-API-KEY"]=t.apiKey),t?.appKey&&(i["DD-APPLICATION-KEY"]=t.appKey),"function"==typeof o){const{data:t,headers:n}=await o();e.body=t,i={...i,...n}}a=await fetch(n,{...e,headers:i})}catch(t){return e(t),{}}if(!a.ok){const t=`HTTP ${a.status} ${a.statusText}`;if(K.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),{}}}),r)},G=/[/]+|[\\]+/g,J=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,V=(e,t)=>{const n=e.replace(J,"").split(G),s=t.replace(J,"").split(G),o=n.join("/");let i="";for(let e=0;e<s.length;e+=1){const t=s.slice(-e).join("/");o.startsWith(t)&&(i=t)}return i},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:V(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}},Q=t.green.bold,X=t.yellow.bold,Z=t.red.bold,ee=(e,t={})=>async()=>{const n=new FormData,s=p.createGzip();for(const[t,s]of e.content){const e="file"===s.type?await P(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:r.Readable.fromWeb(o.body).pipe(s),headers:{"Content-Encoding":"gzip",...t,...Object.fromEntries(o.headers.entries())}}},te=async(e,t,n,s)=>{const o=Date.now(),i=t.minifiedPathPrefix,r={git_repository_url:n.git?.remote,git_commit_sha:n.git?.hash,plugin_version:n.version,project_path:n.bundler.outDir,service:t.service,type:"js_sourcemap",version:t.releaseVersion},a=await Promise.all(e.map((e=>Y(e,r,i,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=[],i=[];if(!n.auth?.apiKey)return o.push({error:new Error("No authentication token provided")}),{errors:o,warnings:i};if(0===e.length)return i.push("No sourcemaps to upload"),{errors:o,warnings:i};const r=new(c.default?c.default:c)({concurrency:t.maxConcurrency}),a={"DD-EVP-ORIGIN":`${n.bundler.fullName}-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.bundler.outDir,"."),file:c.content.get("minified_file")?.path.replace(n.bundler.outDir,".")};s.debug(`Queuing ${Q(e.sourcemap)} | ${Q(e.file)}`),u.push(r.add((async()=>{try{await U({auth:{apiKey:n.auth.apiKey},url:t.intakeUrl,method:"POST",getData:ee(c,a),onRetry:(t,n)=>{const o=`Failed to upload ${X(e.sourcemap)} | ${X(e.file)}:\n ${t.message}\nRetrying ${n}/5`;i.push(o),s.debug(o)}}),s.debug(`Sent ${Q(e.sourcemap)} | ${Q(e.file)}`)}catch(n){if(o.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}return await Promise.all(u),await r.onIdle(),{warnings:i,errors:o}})(a,t,n,s);if(s.info(`Done uploading ${Q(e.length.toString())} sourcemaps in ${Q(z(Date.now()-o))}.`),l.length>0){const e=`Failed to upload some sourcemaps:\n${` - ${l.map((({metadata:e,error:t})=>e?`${Z(e.file)} | ${Z(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 - ")}`)},ne=async(e,n,s)=>{const o=t.green.bold,i=Object.entries(e.sourcemaps).map((([e,t])=>` - ${e}: ${o(t.toString())}`)).join("\n"),r=s.time("get sourcemaps files"),u=((e,t)=>{if(!t.build.outputs||0===t.build.outputs.length)throw new Error("No output files found.");return t.build.outputs.filter((e=>e.filepath.endsWith(".map"))).map((e=>e.filepath)).map((n=>({...B(e,t,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,n);r.end();const c=a.outdent`
2
- Uploading ${o(u.length.toString())} sourcemaps with configuration:
3
- ${i}
4
- `;s.info(c);const p=s.time("send sourcemaps");await te(u,e.sourcemaps,n,s),p.end()},se=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,oe=e=>{const n=t.bold.red,s=e[H]||{},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||se,...s.sourcemaps};o.config=e}return o},ie=({options:e,context:t})=>{const n=t.getLogger(W),s=n.time("validate options"),o=((e,t)=>{const n=[],s=oe(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${W}.`);const o={disabled:!e[H],...e[H],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return s.end(),o.disabled?[]:[{name:W,enforce:"post",async writeBundle(){if(!o.disabled&&o.sourcemaps){const e=n.time("sourcemaps process");await ne(o,t,n),e.end()}}}]};var re=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(re||{});const ae="rum",ue="datadog-rum-plugin",ce="datadog-rum-privacy-plugin",pe="\0datadog:privacy-helpers";const le=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,de=(e,t)=>{const n=e.sdk;if(n.disabled)return"";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 U({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[ae]||{},o={errors:[]};if(s.sdk?.disabled)return o;if(s.sdk){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.`);const t={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.config={...t,...s.sdk}}return o},fe=(e,t)=>{const n=e[ae]||{},s={errors:[]};if(t.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(n.privacy)}`),n.privacy){const e={exclude:[/\/node_modules\//,/\.preval\./,/^[!@#$%^&*()=+~`\\\-/]/],include:[/\.(?:c|m)?(?:j|t)sx?$/],addToDictionaryFunctionName:"$",helpersModule:pe};s.config={...e,...n.privacy}}return s},he=({options:e,context:t})=>{const n=((e,t)=>{const n=[],s=me(e),o=fe(e,t);if(n.push(...s.errors),n.push(...o.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${ue}.`);const i={disabled:!e[ae],...e[ae],sdk:void 0,privacy:void 0};return s.config&&(i.sdk=s.config),o.config&&(i.privacy=o.config),i})(e,t.getLogger(ue)),s=[];if(n.disabled)return s;if(n.sdk&&(t.inject({type:"file",position:re.MIDDLE,value:i.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:re.MIDDLE,value:de(n,t)})),n.privacy){const e=((e,t)=>{const n=t.getLogger(ce);if(e.disabled)return;const s=function(e){return{input:{module:e.module,jsx:e.jsx,typescript:e.typescript},privacy:{addToDictionaryHelper:{import:{cjsModule:`${e.helpersModule}.cjs`,esmModule:`${e.helpersModule}.mjs`,func:e.addToDictionaryFunctionName??"$"}}}}}(e),o=d.createFilter(e.include,e.exclude),i=e.helpersModule??pe;return{name:ce,enforce:"post",resolveId:async e=>e.includes(i)?{id:e}:null,loadInclude:e=>!!e.includes(i),async load(e){let t;return e.includes(i)?(t=e.endsWith(".cjs")?f.join(__dirname,"privacy-helpers.js"):f.join(__dirname,"privacy-helpers.mjs"),{code:m.readFileSync(t,"utf8"),map:null}):null},transformInclude:e=>o(e),async transform(e,o){try{return"esbuild"!==t.bundler.name&&"webpack"!==t.bundler.name&&"rspack"!==t.bundler.name||(s.output={...s.output,inlineSourceMap:!1,embedCodeInSourceMap:!0}),l.instrument({id:o,code:e},s)}catch(t){return n.error(`Instrumentation Error: ${t}`),{code:e}}}}})(n.privacy,t);e&&s.push(e)}return s},ge="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)},De=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),Ee=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),Me=(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 i=0;s+=o.values.length;for(const t of o.values){const n=t.end-t.start;i+=n,e+=n}t.add({metric:"plugins.hooks.duration",type:"duration",value:i,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.build.inputs||[],s=e.build.outputs||[],o=e.build.entries||[],i=e.build.warnings.length,r=e.build.errors.length,a=e.build.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:r,tags:[]}).add({metric:"modules.count",type:"count",value:n.length,tags:[]}).add({metric:"warnings.count",type:"count",value:i,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))},xe=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 E(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,je=t.bold.cyan,Te=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},Oe=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(Te("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:z(e.duration)}))),top:!0};n.sort(Te("increment"));return[s,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},ze=(e,t,n)=>{const s=[];var o;n&&(s.push(...Oe("Loader",n.timings.loaders)),s.push(...Oe("Tapable",n.timings.tapables)),s.push(...Oe("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},i=new Set,r=(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 r.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;i.add({name:t.name,size:t.size,aggregatedSize:o,dependents:s,dependencies:n})}if(!i.size)return[t,n,s];const p=Array.from(i);return p.sort(Te((e=>e.dependents.size))),t.values=p.map((e=>({name:e.name,value:e.dependents.size.toString()}))),p.sort(Te((e=>e.dependencies.size))),n.values=p.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),p.sort(Te("size")),s.values=p.map((e=>({name:e.name,value:h(e.size)}))),p.sort(Te("aggregatedSize")),o.values=p.map((e=>({name:e.name,value:h(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(Te((e=>e.size))).map((e=>({name:e.name,value:h(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(Te((e=>e.size))).map((e=>({name:e.name,value:h(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(Te((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,i=e.build.errors.length,r=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:r.toString()},{name:"Number of warnings",value:o.toString()},{name:"Number of errors",value:i.toString()}),[t]})(e));const i=(e=>{let t="";for(const t of e){t.top&&t.values.length>=5&&(t.values=t.values.slice(0,5),t.name=`Top 5 ${t.name}`);for(const e of t.values)e.name=N(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))))),i=Math.max(n+4,s+o+4);for(const n of e){if(0===n.values.length)continue;const e=i-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=o-e.value.length;t+=` [${Pe(e.value)}] ${" ".repeat(n)}${je(e.name)}\n`}}return t})(s);t.info(i)},Ne=["onStart","onLoad","onResolve","onEnd"],Re=new Map,Ie=new Map,Ae=(e,t,n)=>{const s=Object.assign({},e);for(const o of Ne)s[o]=async(s,i)=>{const r=Re.get(t)||{name:t,increment:0,duration:0,events:{}};r.events[o]=r.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=g.performance.now();try{return await i(...e)}finally{const n=g.performance.now(),i=n-u,c={start:u,end:n,duration:i,context:Ee(e)};r.events[o].values.push(c),r.duration+=i,r.increment+=1,Re.set(t,r),a.events[o].values.push(c),a.duration+=i,a.increment+=1,Ie.set(s,a)}}))};return s},Fe=(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 i=Ae(o,s.name,t);await n({...i,initialOptions:{...i.initialOptions,plugins:e}})}}}})(s,t.cwd),o.end(),s.onEnd((async t=>{if(!t.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const s=n.time("getting plugins results"),{plugins:o,modules:i}={plugins:Re,modules:Ie};s.end(),e.report={timings:{tapables:o,modules:i}}}))}});class Ce{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(De))(e);s.length||s.push("no-loader"),this.started[n]={module:$e(n),timings:{start:g.performance.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=g.performance.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:{}},i=n.loaders.join(",");o.events[i]=o.events[i]||{name:i,values:[]},o.events[i].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,i){const r=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};r.events[n]||(r.events[n]={name:n,values:[]}),r.events[n].values.push({start:o,end:i,duration:i-o,context:s,type:e}),r.duration+=i-o,r.increment+=1,this.timings.set(t,r)}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 i=g.performance.now(),r=t.apply(this,o),a=()=>{this.saveResult(e,n,s,Ee(o),i,g.performance.now())};return r.then(a,a),r}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const i=g.performance.now(),r=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,Ee(o),i,g.performance.now()),r(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const i=g.performance.now(),r=t.apply(this,o);return this.saveResult(e,n,s,Ee(o),i,g.performance.now()),r}}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,i)=>{const r="string"==typeof(a=o)?a:a.name;var a;const u=`${t}-${r}`;if(this.monitoredTaps[u])return n.call(s,o,i);this.monitoredTaps[u]=!0;const c=this.getTapPatch(e,i,r,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},i=new Le(t.cwd),r=new Ce(t.cwd),a=s.time("parse compiler hooks");i.throughHooks(n),a.end(),n.hooks.thisCompilation.tap(o,(e=>{const t=s.time("parse compilation hooks");i.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)}))})),n.hooks.afterEmit.tapPromise(o,(async t=>{const{timings:n}=i.getResults(),{loaders:s,modules:o}=r.getResults();e.report={timings:{tapables:n,loaders:s,modules:o}}}))},qe={filters:we},He=({options:e,context:t})=>{const n=t.getLogger(ye);let s=0;const o={start:Date.now()},i=(e=>{const t=e[ge]?.endPoint||"https://app.datadoghq.com";return{disabled:!e[ge],enableTracing:!1,filters:we,output:!1,prefix:"",tags:[],...e[ge],endPoint:t.startsWith("http")?t:`https://${t}`}})(e),r=[];if(i.disabled)return r;const a={name:ye,enforce:"pre",esbuild:Fe(o,t,n),webpack:_e(o,t),rspack:_e(o,t)},u=n.time("build",{start:!1}),c={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 writeBundle(){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,r=(e=>({timestamp:Math.floor((e.timestamp||Date.now())/1e3),tags:e.tags,prefix:e.prefix,filters:e.filters}))(i),a=n.time("aggregating metrics");Me(t,r,e,o.report),a.end();const u=n.time("writing to files");await xe({report:o.report,metrics:e},i.output,n,t.bundler.outDir),u.end();const c=n.time("outputing report");ze(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 - ")}`),U({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:i.endPoint},n),p.end()}};return i.enableTracing&&r.push(a),r.push(c),r},We="datadog-analytics-plugin",Be=e=>{const{context:t}=e,n=e.context.getLogger(We);return t.sendLog=async(e,s={})=>{if("production"===t.env)try{const n={name:t.bundler.name,version:t.bundler.version};await U({retries:2,minTimeout:100,url:"https://browser-http-intake.logs.datadoghq.com/v1/input/pub44d5f4eb86e1392037b7501f7adc540e",method:"POST",type:"json",getData:async()=>{const o={ddsource:`@datadog/${n.name}-plugin`,env:t.env,message:e,service:"build-plugins",bundler:n,metadata:t.build.metadata,plugins:t.pluginNames,version:t.version,team:"language-foundations",...s};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}})}catch(e){n.debug(`Could not submit data to Datadog: ${e}`)}},[{name:We,async buildStart(){await t.sendLog("Build started")}}]},Ke=async(e,t,n)=>{const s=[],o=e.initialOptions.entryPoints,i=[],r=[];if(Array.isArray(o))for(const e of o){const t=e&&"object"==typeof e?e.in:e;i.push({path:t})}else o&&"object"==typeof o&&i.push(...Object.entries(o).map((([e,t])=>({name:e,path:t}))));const a=i.flatMap((e=>{return(t=e.path,t.includes("*")?y.glob.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,o])=>{const i=await e.resolve(o,{kind:"entry-point",resolveDir:t.cwd});i.errors.length&&r.push(...i.errors.map((e=>e.text))),i.path&&s.push({name:n.name,resolved:i.path,original:n.path})}));for(const e of r)n.error(e);return await Promise.all(a),s},Ue=(e,t)=>O(t)?k:t.startsWith(e)||i.isAbsolute(t)?t:i.resolve(e,t),Ge=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,Je=/(\?|%3F|\|)+/gi,Ve=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=Xe(e),Ge.lastIndex=0,Ge.exec(t)?.[1]||"unknown");var t},Ye=["unknown","commonjsHelpers.js",`vite${i.sep}preload-helper.js`],Qe=(e,t,n)=>{const s=new Set;for(const n of e){const e=Xe(n);O(n)||e===t||Ye.includes(e)||s.add(e)}return s},Xe=e=>e.split("!").pop().split(Je).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/\\]+/,""),Ze=(e,t)=>O(t)?k:"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(),Ue(e.cwd,e.bundler.outDir)).split("node_modules").pop().split(Je).shift().replace(/^((\.\.?)?[/\\])+/g,""),et=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Ue(t,e),n]))),tt=(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 Ke(n,e,t));for(const t of o){const n=Ze(e,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}i.end(),r.pause()})),n.onEnd((n=>{r.resume();const o=t.time("collecting errors and warnings"),a=e.cwd;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 u=[],c=[],p=[],l=[],d=[],m={},f={},h=t.time("indexing metafile data"),g=et(n.metafile.inputs,a),y=et(n.metafile.outputs,a);h.end();const w=e=>{if(!O(e))return e;const t=g[Ue(a,e)];if(!t)return e;const n=t.imports.find((e=>!O(e.path)));return n?n.path:e},b=t.time("looping through inputs");for(const[t,s]of Object.entries(n.metafile.inputs)){if(O(t))continue;const n=Ue(a,t),o={name:Ze(e,t),filepath:n,dependents:new Set,dependencies:new Set,size:s.bytes,type:Ve(t)};m[n]=o,u.push(o)}b.end();const v=t.time("looping through outputs");for(const[o,i]of Object.entries(n.metafile.outputs)){const n=Ue(a,o),r=Ze(e,n),u=[];for(const e of Object.keys(i.inputs)){if(O(e))continue;const n=m[Ue(a,e)];n?u.push(n):t.debug(`Input ${e} not found for output ${r}`)}if(i.entryPoint&&!u.length){const e=m[Ue(a,i.entryPoint)];if(!e){t.debug(`Input ${i.entryPoint} not found for output ${r}`);continue}u.push(e)}const d={name:r,filepath:n,inputs:u,size:i.bytes,type:Ve(n)};if(f[n]=d,"map"===d.type&&l.push(d),c.push(d),!i.entryPoint)continue;const h=m[Ue(a,w(i.entryPoint))];if(h){if(!s.get(h.name))continue;const e={...d,name:s.get(h.name)||h.name,outputs:[d],size:d.size};p.push(e)}}v.end();const $=t.time("looping through sourcemaps");for(const e of l){const n=f[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}$.end();const k={inputs:{report:m,meta:g},outputs:{report:f,meta:y}},S=/(<runtime>|https:|file:|data:|#)/g,D=e=>!O(e)&&!e.match(S),E=(n,s,o={})=>{if(!D(n))return o;const r=s.report[n];if(!r)return t.debug(`Could not find report's ${n}`),o;if(o[r.filepath])return o;o[r.filepath]=r;const c=s.meta[n];if(!c)return t.debug(`Could not find metafile's ${n}`),o;if(!c.imports||!c.imports.length)return o;for(const t of c.imports){const c=t.path.match(/^\.\.?\//),p=c?i.dirname(n):a,l=Ue(p,t.path);if(t.external){if(D(t.path)){const n=c?l:t.path,s=k.inputs.report[n]||{filepath:n,name:Ze(e,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in r&&(s.dependents.add(r),r.dependencies.add(s)),"inputs"in r&&!r.inputs.includes(s)&&r.inputs.push(s),u.includes(s)||u.push(s),k.inputs.report[n]=s,o[s.filepath]=s}}else E(l,s,o)}return o},M=t.time("looping through entries");for(const e of p){const t={},n={};for(const n of e.inputs)E(n.filepath,k.inputs,t);for(const t of e.outputs)E(t.filepath,k.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),d.push(e)}M.end();const x=t.time("aggregate dependencies and dependents");for(const e of u){if("external"===e.type)continue;const n=k.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=Ue(o,s.path);let u;if(s.external){const e=n?r:s.path;u=k.inputs.report[e]}else u=k.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}`)}x.end(),e.build.outputs=c,e.build.inputs=u,e.build.entries=d,r.end(),e.hook("buildReport",e.build)}))}}),nt=(e,t)=>{const n=t.time("module parsing",{start:!1});let s={};return{buildStart(){s={}},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=Xe(e.id),o=s[t]||{dependencies:new Set,dependents:new Set},i=Qe(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=Qe(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)o.dependents.add(e);for(const e of i)o.dependencies.add(e);s[t]=o,n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,o){const i=t.time("build report"),r=[],a=[],u=[],c=[],p={},l=[],d={},m={},f=t.time("completing dependencies and dependents");for(const[e,{dependencies:t,dependents:n}]of Object.entries(s)){for(const n of t){const t=Xe(n);s[t]||(s[t]={dependencies:new Set,dependents:new Set}),s[t].dependents.has(e)||s[t].dependents.add(e)}for(const t of n){const n=Xe(t);s[n]||(s[n]={dependencies:new Set,dependents:new Set}),s[n].dependencies.has(e)||s[n].dependencies.add(e)}}f.end();const h=t.time("filling inputs and outputs");for(const[n,i]of Object.entries(o)){const o={name:n,filepath:Ue(e.bundler.outDir,n),inputs:[],size:"code"in i?Buffer.byteLength(i.code,"utf8"):Buffer.byteLength(i.source,"utf8"),type:Ve(n)};if("map"===o.type&&c.push(o),"modules"in i)for(const[t,n]of Object.entries(i.modules)){if(Xe(t)!==t)continue;const s={name:Ze(e,t),dependencies:new Set,dependents:new Set,filepath:t,size:n.originalLength,type:Ve(t)};o.inputs.push(s),d[s.filepath]=s,r.push(s)}if("imports"in i)for(const n of i.imports){const i=Xe(n);if(!s[i]){p[Ue(e.bundler.outDir,i)]=o;continue}if(d[i]){t.debug(`Input report already there for ${i} from ${o.name}.`);continue}const a={name:Ze(e,n),dependencies:new Set,dependents:new Set,filepath:i,size:0,type:"external"};o.inputs.push(a),d[a.filepath]=a,r.push(a)}"isEntry"in i&&i.isEntry&&u.push({...o,name:i.name,size:0,outputs:[o]}),m[o.filepath]=o,a.push(o)}h.end();for(const[e,n]of Object.entries(p)){const s=m[e];s?n.inputs.includes(s)||n.inputs.push(s):t.debug(`Could not find the output report for ${e}.`)}const g=t.time("filling dependencies and dependents");for(const n of r){const o=s[n.filepath];if(o){for(const s of o.dependencies){const o=d[s];o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${Ze(e,s)} of ${n.name}`)}for(const s of o.dependents){const o=d[s];o?n.dependents.add(o):t.debug(`Could not find input for dependent ${Ze(e,s)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(g.end(),c.length){const e=t.time("filling sourcemaps inputs");for(const e of c){const n=e.filepath.replace(/\.map$/,""),s=m[n];s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}e.end()}const y=(n,s={})=>{if(s[n])return s;const i=Ze(e,n),r=m[n];if(!r){return!!d[i]||t.debug(`Could not find output for ${i}`),s}s[n]=r;const a=o[Ze(e,n)];if(!a)return t.debug(`Could not find asset for ${i}`),s;const u=[];"imports"in a&&u.push(...a.imports),"dynamicImports"in a&&u.push(...a.dynamicImports);for(const t of u)y(Ue(e.bundler.outDir,t),s);return s},w=t.time("filling entries");for(const e of u){const t=y(e.filepath);e.outputs=Object.values(t),e.inputs=Array.from(new Set(e.outputs.flatMap((e=>e.inputs)))),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),l.push(e)}w.end(),e.build.inputs=r,e.build.outputs=a,e.build.entries=l,i.end(),e.hook("buildReport",e.build)}}},st=(e,t,n)=>s=>{let o=[],i=[],r=[];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)),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"],s=e=>{const n=Xe(e);t.add(n),n.startsWith("external ")&&t.add(h(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=Xe(t.request);if(p.has(n))return p.get(n);if(e.context){const t=Ue(Xe(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=[],i=[],r=[],a.clear(),u.clear(),p.clear(),d.clear(),s.hooks.finishModules.tap(t,(t=>{m.resume();const s=n.time("dependency graph"),i=n.time("indexing modules");for(const e of t)g(e);i.end();const r=n.time("building inputs");for(const n of t){const t=n.identifier(),s=Ze(e,t),i=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)?h(o):o))})).filter(Boolean));if(!f(t))continue;const r=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of i){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),r.dependencies.add(e),d.set(e,n)}d.set(t,r);const u=b(n)?{size:0,name:h(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:Ve(t)};o.push(u),a.set(t,u),b(n)&&a.set(h(t),u)}r.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.tap(t,(t=>{m.resume();const s=t.chunks,p=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Ue(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of s){const t=d(e),n=(g?g?.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"===Ve(e))continue;const t=c.get(e)||new Set;for(const e of n)t.add(e);c.set(e,t)}}h.end();const y=n.time("building outputs");for(const t of p){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:Ue(e.bundler.outDir,t.name),type:Ve(t.name)};if(u.set(s.filepath,s),i.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,i=new Map;let a=0;const c=o.chunks.flatMap(d),p=o.chunks.filter((e=>g?g.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"===Ve(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)i.has(e.filepath)||i.set(e.filepath,e);a+=s.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const l={name:s,filepath:p?Ue(e.bundler.outDir,p):"unknown",size:a,inputs:Array.from(i.values()),outputs:Array.from(t.values()),type:p?Ve(p):"unknown"};r.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=i,e.build.entries=r,m.end(),e.hook("buildReport",e.build)}))},ot="datadog-build-report-plugin",it=e=>{const{context:t}=e,n=t.getLogger(ot);return[{name:ot,enforce:"post",esbuild:tt(t,n),rspack:st(t,ot,n),webpack:st(t,ot,n),vite:nt(t,n),rollup:nt(t,n)}]},rt=(e,t)=>{const n=(e=>{let t,n=Ue(process.cwd(),e),s=n.split(i.sep).length;for(;s>0;){const e=i.resolve(n,"package.json");x(e)&&(t=n),n=n.split(i.sep).slice(0,-1).join(i.sep),s--}return t})(t);if(n)return n;const s=(e=>{const t=[...e].map((e=>Ue(process.cwd(),e).split(i.sep))),n=t.length?Math.min(...t.map((e=>e.length))):0,s=[];for(let e=0;e<n;e++){const n=t[0][e];if(!t.every((t=>t[e]===n)))break;s.push(n)}return s.length>0&&s.join(i.sep)||i.sep})(Array.from(e));return s!==i.sep?s:void 0},at=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=t.options.output.path),e.hook("bundlerReport",e.bundler),t.options.context&&(e.cwd=t.options.context),e.hook("cwd",e.cwd)},ut=e=>{const{context:t}=e,n=new Set,s=e=>{e&&(e.dir?(t.bundler.outDir=e.dir,n.add(e.dir)):e.file&&(t.bundler.outDir=i.dirname(e.file),n.add(t.bundler.outDir)),t.bundler.outDir=Ue(process.cwd(),t.bundler.outDir),"vite"!==t.bundler.name&&(t.cwd=rt(n,t.bundler.outDir)||t.cwd,t.hook("cwd",t.cwd)))},o=()=>({options(e){if(t.bundler.rawConfig=e,e.input)if(Array.isArray(e.input))for(const t of e.input)n.add(i.dirname(t));else if("object"==typeof e.input)for(const t of Object.values(e.input))n.add(i.dirname(t));else{if("string"!=typeof e.input)throw new Error("Invalid input type");n.add(i.dirname(e.input))}if("output"in e){const t=Array.isArray(e.output)?e.output:[e.output];for(const e of t)s(e)}t.hook("bundlerReport",t.bundler)}});return[{name:"datadog-bundler-report-plugin",enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.outdir&&(t.bundler.outDir=e.initialOptions.outdir),e.initialOptions.outfile&&(t.bundler.outDir=i.dirname(e.initialOptions.outfile)),t.hook("bundlerReport",t.bundler),e.initialOptions.absWorkingDir&&(t.cwd=e.initialOptions.absWorkingDir),t.hook("cwd",t.cwd),e.initialOptions.metafile=!0}},webpack:at(t),rspack:at(t),vite:{...o(),config(e){e.build?.outDir&&(t.bundler.outDir=e.build.outDir),e.root?t.cwd=e.root:t.cwd=rt(n,t.bundler.outDir)||t.cwd,t.hook("cwd",t.cwd)}},rollup:o()}]},ct="datadog-custom-hooks-plugin",pt=e=>{const{context:t}=e,n=t.getLogger(ct),s=e=>(s,...o)=>{const i=n.time(`execution | ${s}`,{tags:["type:custom-hook",`hook:${s}`]}),r=[],a=[];for(const n of t.plugins){if(!(s in n))continue;const t=n[s];if("function"==typeof t)try{const i=t(...o);i instanceof Promise&&(e||r.push(`Plugin "${n.name}" returned a promise on the non async hook "${s}".`),a.push(i))}catch(e){r.push(`Plugin "${n.name}" errored on hook "${s}". [${e}]`)}else r.push(`Plugin "${n.name}" has an invalid hook type for "${s}". [${typeof t}]`)}if(r.length>0){for(const e of r)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>i.end()))};return t.hook=s(!1),t.asyncHook=s(!0),[{name:ct,enforce:"pre"}]};class lt{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,o.readFileSync(s,{encoding:"utf-8"}));var s;const i=JSON.parse(n);if(!i.sources)return void t("Missing 'sources' field in sourcemap.");const r=i.sources;if(0===r.length)return void t("Empty 'sources' field in sourcemap.");const a=this.matchSources(r);if(0!==a.length)return a;t(`${r.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 dt=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await mt(e);for(const e of t)if(e.name===n)return R(e.refs.push);return R(t[0].refs.push)},mt=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},ft=async e=>e.revparse("HEAD"),ht=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),gt=async e=>e.branch(),yt=async e=>e.show(["-s","--format=%s"]),wt=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),bt="datadog-git-plugin",vt=e=>{const{options:t,context:n}=e,s=n.getLogger(bt);return[{name:bt,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=await(async e=>{const t=[ft(e),gt(e),yt(e),wt(e),ht(e),dt(e)],[n,s,o,i,r,a]=await Promise.all(t),[u,c,p,l,d,m]=i.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 lt(r)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=w.simpleGit(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return w.simpleGit(t)})(n.cwd));n.git=t,e.end(),await n.asyncHook("git",n.git)}catch(e){s.error(`Could not get git information: ${e.message}`)}}}]},$t="datadog-injection-plugin",kt=/^https?:\/\//,St=async(e,t=process.cwd())=>(e=>s.readFile(e,{encoding:"utf-8"}))(Ue(t,e)),Dt=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(kt)?await(async(e,t=5e3)=>{let n;return Promise.race([U({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,s)=>{n=setTimeout((()=>{s(new Error("Timeout"))}),t)}))])})(o):await St(o,n);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);s=o}}catch(i){const r=`${e.type} - ${N(o)}`;e.fallback?(t.info(`Fallback for "${r}": ${i.toString()}`),s=await Dt(e.fallback,t,n)):t.warn(`Failed "${r}": ${i.toString()}`)}return s},Et=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`},Mt=async(e,t,n,s=process.cwd())=>{const o=await(async(e,t,n=process.cwd())=>{const s=new Map;for(const[o,i]of e.entries()){const e=await Dt(i,t,n);e&&s.set(o,{value:e,position:i.position||re.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},xt=o.promises,Pt=(e,t,n)=>({setup(s){const{onStart:r,onResolve:a,onLoad:u,onEnd:c,esbuild:p,initialOptions:l}=s,d=[],m=`${A()}.${re.MIDDLE}.${k}.js`,f=o.realpathSync(b.tmpdir()),h=i.resolve(f,m),g=new RegExp(`${m}$`),y=l.inject;l.inject=y?[...y]:[],l.inject.push(h),r((async()=>{d.push(...await Ke(s,t,e)),s.initialOptions.inject=y;try{await E(h,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:g},(async e=>({path:e.path,namespace:$t}))),u({filter:g,namespace:$t},(async()=>({contents:Et(n[re.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),c((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=Et(n[re.BEFORE]),i=Et(n[re.AFTER]);if(!o&&!i)return;const r=Object.entries(s.metafile.outputs).map((([e,n])=>{const s=n.entryPoint;if(!s)return;return d.find((e=>e.resolved.endsWith(s)))?Ue(t.cwd,e):void 0})).filter(Boolean).map((async e=>{const t=await xt.readFile(e,"utf-8"),n=await p.transform(t,{loader:"default",banner:o,footer:i});await xt.writeFile(e,n.code)}));await Promise.all(r)}))}}),jt=k,Tt="?inject-proxy",Ot=e=>({banner:t=>t.isEntry?Et(e[re.BEFORE]):"",async resolveId(t,n,s){if(O(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&Et(e[re.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${Tt}`}return null},load(t){if(O(t))return Et(e[re.MIDDLE]);if(t.endsWith(Tt)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(jt)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?Et(e[re.AFTER]):""}),zt=(e,t,n,s,r)=>a=>{const u=new WeakMap,c=(e=>{if(!e?.sources?.ConcatSource)return v.createRequire(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),p=i.resolve(n.bundler.outDir,`${A()}.${re.MIDDLE}.${k}.js`);M(p,"");const l=()=>{var e;e=p,o.rmSync(e,{force:!0,maxRetries:3,recursive:!0})};a.hooks.shutdown?a.hooks.shutdown.tap($t,l):(a.hooks.done.tap($t,l),a.hooks.failed.tap($t,l));a.hooks.beforeRun.tapPromise($t,(async()=>{await Mt(t,s,r,n.cwd)})),a.hooks.compilation.tap($t,(t=>{const n=()=>{const e=Et(r[re.BEFORE]),n=Et(r[re.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:$t,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:$t},n)}));const d=(e=>{const s="webpack4"===n.bundler.fullName?p:{import:[p]},o=e=>{for(const[n,s]of Object.entries(e))"object"==typeof s?(s.import=s.import||[],s.import.unshift(p)):"string"==typeof s?e[n]=[p,s]:Array.isArray(s)?s.unshift(p):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=d},Nt=e=>{const{bundler:t,context:n}=e,s=n.getLogger($t),o=new Map,i={[re.BEFORE]:new Map,[re.MIDDLE]:new Map,[re.AFTER]:new Map};n.inject=e=>{o.set(A(),e)};const r={name:$t,enforce:"post",esbuild:Pt(s,n,i),webpack:zt(t,s,n,o,i),rspack:zt(t,s,n,o,i),rollup:Ot(i),vite:{...Ot(i),enforce:"pre"}};var a;return a=n.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(a)?(r.loadInclude=e=>!!O(e)||null,r.load=e=>O(e)?{code:Et(i[re.MIDDLE])}:null):r.buildStart=async()=>{await Mt(s,o,i,n.cwd)},[r]},Rt="datadog-true-end-plugin",It=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},s=()=>{t.hook("syncTrueEnd")},o=async()=>{s(),await n()},i=e=>{e.hooks.shutdown?e.hooks.shutdown.tapPromise(Rt,o):(e.hooks.done.tapPromise(Rt,o),e.hooks.failed.tap(Rt,s))},r={async writeBundle(){},async closeBundle(){await o()}};return[{name:Rt,enforce:"post",webpack:i,esbuild:{setup(e){e.onEnd((async()=>{await n()})),e.onDispose((()=>{s()}))}},vite:r,rollup:r,rspack:i}]},At={[ge]:qe};var Ft="2.6.3-dev-3";const Ct=(({bundler:n,version:s})=>{const o=Date.now();return e.createUnplugin(((e,i)=>{const r=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",metadata:{},...e}))(e);"esbuild"===i.framework&&(i.esbuildHostName=D);const a=(({start:e,options:t,bundlerName:n,bundlerVersion:s,version:o})=>{const i=process.cwd(),r="webpack"===n?s.split(".")[0]:"",a={errors:[],warnings:[],logs:[],metadata:t.metadata||{},timings:[],bundler:{name:n,fullName:`${n}${r}`,variant:r,version:s}},u=process.env.BUILD_PLUGINS_ENV||"production",c=S.includes(u)?u:"development";return{auth:t.auth,pluginNames:[],bundler:{...a.bundler,outDir:i},build:a,cwd:i,env:c,getLogger:C(a,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.")},sendLog:()=>{throw new Error("SendLog function called before it was initialized.")},plugins:[],start:e,version:o}})({start:o,options:r,bundlerVersion:n.rspackVersion||n.version||n.VERSION,bundlerName:i.framework,version:s}),u=a.getLogger("factory").time("Plugins initialization",{start:o});a.pluginNames.push(D);const c=[];c.push(["analytics",Be],["build-report",it],["bundler-report",ut],["custom-hooks",pt],["git",vt],["injection",Nt],["true-end",It]),r.customPlugins&&c.push(["custom",r.customPlugins]),c.push(["error-tracking",ie],["rum",he],["telemetry",He]);for(const[e,t]of c)a.plugins.push(...q(a,t,e)({bundler:n,context:a,options:r}));a.pluginNames.push(...a.plugins.map((e=>e.name)));const p=new Set(a.pluginNames.filter((e=>a.pluginNames.filter((t=>t===e)).length>1)));if(p.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(p).join(", "))}`);return a.hook("init",a),u.end(),a.plugins}))})({bundler:$,version:Ft}).rollup,Lt=Ft,_t=At;exports.datadogRollupPlugin=Ct,exports.helpers=_t,exports.version=Lt;
1
+ "use strict";var e=require("unplugin"),t=require("chalk"),n=require("async-retry"),s=require("buffer"),o=require("fs/promises"),r=require("fs"),i=require("path"),a=require("stream"),u=require("outdent"),c=require("p-queue"),p=require("zlib"),l=require("@datadog/js-instrumentation-wasm"),d=require("@rollup/pluginutils"),m=require("node:path"),f=require("pretty-bytes"),h=require("perf_hooks"),g=require("glob"),y=require("simple-git"),w=require("os"),b=require("module"),v=require("rollup");const $="__datadog-helper-file",k=["development","production","test"],S="datadog-build-plugins",D=[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(D.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)},x=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||S,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"}}}}),M=async(e,t)=>{await(async e=>o.mkdir(e,{recursive:!0}))(i.dirname(e)),await o.writeFile(e,t,{encoding:"utf-8"})},P=(e,t)=>{var n;n=i.dirname(e),r.mkdirSync(n,{recursive:!0}),r.writeFileSync(e,t,{encoding:"utf-8"})},j=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.File([n],t.filename)}{const n=a.Readable.toWeb(r.createReadStream(e)),o=await new Response(n).blob();return new s.File([o],t.filename,{type:t.contentType})}},O=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},z=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),N=e=>e.includes($),R=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()},I=(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)}`},A=(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 F=0;const q=()=>`${Date.now()}.${performance.now()}.${++F}`,C={debug:0,info:1,warn:2,error:3,none:4},L=e=>e.split(">").map(z).join(">"),_=(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=>{const n=l();if(n?.length){n.length>1&&s(`Timer ${t.cyan(o)} has more than one ongoing span.`,"debug");for(const t of n)t.end=e||Date.now()}else 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);const n=p.spans.reduce(((e,t)=>e+(t.end-t.start)),0);p.total=n,u&&s(`[${t.cyan(o)}] : ${t.cyan(R(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)}}},H=(e,n,s="warn")=>o=>{const r=((e,n,s,o)=>{const r=L(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);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&&s.queue.push(x(n)({message:d,context:{plugin:e,status:a}})),C[a]>=C[o]&&p(`${c(l)} ${d}`)}})(o,e,n,s);return{getLogger:t=>H(e,n,s)(`${L(o)}>${t}`),time:_(o,n.timings,r),error:(e,t)=>r(e,"error",t),warn:(e,t)=>r(e,"warn",t),info:(e,t)=>r(e,"info",t),debug:(e,t)=>r(e,"debug",t)}},B=["buildEnd","buildStart","load","loadInclude","resolveId","transform","transformInclude","watchChange","writeBundle","cwd","init","buildReport","bundlerReport","git"],W=(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)},K=(e,t,n)=>{const s=e.getLogger(S);return e=>{const o=s.time(`hook | init ${n}`,{log:!1}),r=t(e).map((e=>((e,t)=>{const n={...e},s=z(e.name);for(const o of B){const r=e[o];r&&(n[o]=W(s,o,r,t))}return n})(e,s))),i=r.map((e=>`plugin:${e.name}`));return o.tag(i),o.end(),r}},U="errorTracking",G="datadog-error-tracking-plugin",J=(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.bundler.outDir,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.minifiedPathPrefix,r);return{minifiedFilePath:o,minifiedUrl:a,relativePath:r}},V=/[/]+|[\\]+/g,Q=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,Y=(e,t)=>{const n=e.replace(Q,"").split(V),s=t.replace(Q,"").split(V),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},X=async(e,t,n,s)=>{const o=await(async(e,t)=>{const[n,s]=await Promise.all([O(e.minifiedFilePath),O(e.sourcemapFilePath)]);return{file:n,sourcemap:s,repeatedPrefix:Y(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}},Z=t.green.bold,ee=t.yellow.bold,te=t.red.bold,ne=(e,t={})=>async()=>{const n=new FormData,s=p.createGzip();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.Readable.fromWeb(o.body).pipe(s),headers:{"Content-Encoding":"gzip",...t,...Object.fromEntries(o.headers.entries())}}},se=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.bundler.outDir,service:t.service,type:"js_sourcemap",version:t.releaseVersion},a=await Promise.all(e.map((e=>X(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.auth?.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.bundler.fullName}-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.bundler.outDir,"."),file:c.content.get("minified_file")?.path.replace(n.bundler.outDir,".")};s.debug(`Queuing ${Z(e.sourcemap)} | ${Z(e.file)}`),u.push(i.add((async()=>{try{await E({auth:{apiKey:n.auth.apiKey},url:t.intakeUrl,method:"POST",getData:ne(c,a),onRetry:(t,n)=>{const o=`Failed to upload ${ee(e.sourcemap)} | ${ee(e.file)}:\n ${t.message}\nRetrying ${n}/5`;r.push(o),s.debug(o)}}),s.debug(`Sent ${Z(e.sourcemap)} | ${Z(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,n,s);if(s.info(`Done uploading ${Z(e.length.toString())} sourcemaps in ${Z(R(Date.now()-o))}.`),l.length>0){const e=`Failed to upload some sourcemaps:\n${` - ${l.map((({metadata:e,error:t})=>e?`${te(e.file)} | ${te(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 - ")}`)},oe=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.build.outputs||0===t.build.outputs.length)throw new Error("No output files found.");return t.build.outputs.filter((e=>e.filepath.endsWith(".map"))).map((e=>e.filepath)).map((n=>({...J(e,t,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,n);i.end();const c=u.outdent`
2
+ Uploading ${o(a.length.toString())} sourcemaps with configuration:
3
+ ${r}
4
+ `;s.info(c);const p=s.time("send sourcemaps");await se(a,e.sourcemaps,n,s),p.end()},re=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,ie=e=>{const n=t.bold.red,s=e[U]||{},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||re,...s.sourcemaps};o.config=e}return o},ae=({options:e,context:t})=>{const n=t.getLogger(G),s=n.time("validate options"),o=((e,t)=>{const n=[],s=ie(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${G}.`);const o={disabled:!e[U],...e[U],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return s.end(),o.disabled?[]:[{name:G,enforce:"post",async writeBundle(){if(!o.disabled&&o.sourcemaps){const e=n.time("sourcemaps process");await oe(o,t,n),e.end()}}}]};var ue=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(ue||{});const ce="rum",pe="datadog-rum-plugin",le="datadog-rum-privacy-plugin";const de=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,me=(e,t)=>{const n=e.sdk;if(n.disabled)return"";if(n.clientToken)return de(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 de({...e,sdk:{clientToken:s,...n}})}},fe=e=>{const n=t.bold.red,s=e[ce]||{},o={errors:[]};if(!s.sdk||s.sdk.disabled)return o;if(s.sdk){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.`);const t={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.config={...t,...s.sdk}}return o},he=(e,t)=>{const n=e[ce]||{},s={errors:[]};if(n.privacy){const e={exclude:[/\/node_modules\//,/\.preval\./,/^[!@#$%^&*()=+~`-]/],include:[/\.(?:c|m)?(?:j|t)sx?$/],addToDictionaryFunctionName:"$",helpersModule:"\0datadog:privacy-helpers"};s.config={...e,...n.privacy}}return t.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(s.config,((e,t)=>t instanceof RegExp?t.toString():t))}`),s},ge=({options:e,context:t})=>{const n=((e,t)=>{const n=[],s=fe(e),o=he(e,t);if(n.push(...s.errors),n.push(...o.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${pe}.`);const r={disabled:!e[ce],...e[ce],sdk:void 0,privacy:void 0};return s.config&&(r.sdk=s.config),o.config&&(r.privacy=o.config),r})(e,t.getLogger(pe)),s=[];if(n.disabled)return s;if(n.sdk&&(t.inject({type:"file",position:ue.MIDDLE,value:i.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:ue.MIDDLE,value:me(n,t)})),n.privacy){const e=((e,t)=>{const n=t.getLogger(le);if(e.disabled)return;t.inject({type:"file",position:ue.BEFORE,value:m.join(__dirname,"./privacy-helpers.js")});const s={privacy:{addToDictionaryHelper:{expression:{code:"((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()"}}}},o=d.createFilter(e.include,e.exclude);return{name:le,enforce:"post",transformInclude:e=>o(e),async transform(e,o){try{return["esbuild","webpack","rspack"].includes(t.bundler.name)&&(s.output={...s.output,inlineSourceMap:!1,embedCodeInSourceMap:!0}),l.instrument({id:o,code:e},s)}catch(t){return n.error(`Instrumentation Error: ${t}`),{code:e}}}}})(n.privacy,t);e&&s.push(e)}return s},ye="telemetry",we="datadog-telemetry-plugin",be=[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}],ve=(e,t)=>({type:"gauge",tags:[...e.tags,...t.tags],metric:`${t.prefix?`${t.prefix}.`:""}${e.metric}`,points:[[t.timestamp,e.value]]}),$e=(e="")=>e.endsWith("/")?e:`${e}/`,ke=(e,t)=>{let n=e;return e.split($e(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},Se=(e,t)=>e.split("!").pop().replace($e(t),"./"),De=(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)),Se(s||"no-name",n)},Ee=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),xe=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),Me=(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.build.inputs||[],s=e.build.outputs||[],o=e.build.entries||[],r=e.build.warnings.length,i=e.build.errors.length,a=e.build.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(ve(s,t))}else n.add(ve(e,t));n.add(ve({metric:"metrics.count",type:"count",value:n.size+1,tags:[]},t))},Pe=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 M(e,n)})(i.join(p,`${t}.json`),s.content),n.debug(`Wrote ${t}.json in ${R(Date.now()-o)}`)}catch(s){n.error(`Failed to write ${t}.json in ${R(Date.now()-o)}`),e[t]=s}}));await Promise.all(s),n.debug(`Wrote files in ${R(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}`)}},je=t.bold.red,Te=t.bold.cyan,Oe=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},ze=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(Oe("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:R(e.duration)}))),top:!0};n.sort(Oe("increment"));return[s,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},Ne=(e,t,n)=>{const s=[];var o;n&&(s.push(...ze("Loader",n.timings.loaders)),s.push(...ze("Tapable",n.timings.tapables)),s.push(...ze("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(Oe((e=>e.dependents.size))),t.values=p.map((e=>({name:e.name,value:e.dependents.size.toString()}))),p.sort(Oe((e=>e.dependencies.size))),n.values=p.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),p.sort(Oe("size")),s.values=p.map((e=>({name:e.name,value:f(e.size)}))),p.sort(Oe("aggregatedSize")),o.values=p.map((e=>({name:e.name,value:f(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(Oe((e=>e.size))).map((e=>({name:e.name,value:f(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(Oe((e=>e.size))).map((e=>({name:e.name,value:f(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(Oe((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:R(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:R(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:R(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=I(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+=` [${je(e.value)}] ${" ".repeat(n)}${Te(e.name)}\n`}}return t})(s);t.info(r)},Re=["onStart","onLoad","onResolve","onEnd"],Ie=new Map,Ae=new Map,Fe=(e,t,n)=>{const s=Object.assign({},e);for(const o of Re)s[o]=async(s,r)=>{const i=Ie.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=Se(e[0].path,n),a=Ae.get(s)||{name:s,increment:0,duration:0,events:{}};a.events[o]=a.events[o]||{name:o,values:[]};const u=h.performance.now();try{return await r(...e)}finally{const n=h.performance.now(),r=n-u,c={start:u,end:n,duration:r,context:xe(e)};i.events[o].values.push(c),i.duration+=r,i.increment+=1,Ie.set(t,i),a.events[o].values.push(c),a.duration+=r,a.increment+=1,Ae.set(s,a)}}))};return s},qe=(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(we))continue;const n=s.setup;s.setup=async o=>{const r=Fe(o,s.name,t);await n({...r,initialOptions:{...r.initialOptions,plugins:e}})}}}})(s,t.cwd),o.end(),s.onEnd((async t=>{if(!t.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const s=n.time("getting plugins results"),{plugins:o,modules:r}={plugins:Ie,modules:Ae};s.end(),e.report={timings:{tapables:o,modules:r}}}))}});class Ce{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=De(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:ke(n),timings:{start:h.performance.now(),duration:0,end:0},loaders:s}}doneModule(e,t){const n=De(e,t,this.cwd),s=this.started[n];s&&(s.timings.end=h.performance.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=h.performance.now(),i=t.apply(this,o),a=()=>{this.saveResult(e,n,s,xe(o),r,h.performance.now())};return i.then(a,a),i}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=h.performance.now(),i=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,xe(o),r,h.performance.now()),i(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=h.performance.now(),i=t.apply(this,o);return this.saveResult(e,n,s,xe(o),r,h.performance.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(we)||(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(we);t.build.start=Date.now();const o={name:we},r=new Le(t.cwd),i=new Ce(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 t=>{const{timings:n}=r.getResults(),{loaders:s,modules:o}=i.getResults();e.report={timings:{tapables:n,loaders:s,modules:o}}}))},He={filters:be},Be=({options:e,context:t})=>{const n=t.getLogger(we);let s=0;const o={start:Date.now()},r=(e=>{const t=e[ye]?.endPoint||"https://app.datadoghq.com";return{disabled:!e[ye],enableTracing:!1,filters:be,output:!1,prefix:"",tags:[],...e[ye],endPoint:t.startsWith("http")?t:`https://${t}`}})(e),i=[];if(r.disabled)return i;const a={name:we,enforce:"pre",esbuild:qe(o,t,n),webpack:_e(o,t),rspack:_e(o,t)},u=n.time("build",{start:!1}),c={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 writeBundle(){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");Me(t,i,e,o.report),a.end();const u=n.time("writing to files");await Pe({report:o.report,metrics:e},r.output,n,t.bundler.outDir),u.end();const c=n.time("outputing report");Ne(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()}};return r.enableTracing&&i.push(a),i.push(c),i},We="datadog-analytics-plugin",Ke=({context:e})=>{const t=e.getLogger(We);return[{name:We,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}`)}})())}}]},Ue="datadog-async-queue-plugin",Ge=e=>{const{context:t,stores:n}=e,s=t.getLogger(Ue),o=[];return t.queue=e=>{const t=e.catch((e=>{o.push(e.message||e.toString())}));n.queue.push(t)},[{name:Ue,asyncTrueEnd:async()=>{await Promise.all(n.queue),o.length>0&&s.error(`Error occurred while processing async queue:\n ${o.join("\n ")}`)}}]},Je=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.glob.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},Ve=(e,t)=>N(t)?$:t.startsWith(e)||i.isAbsolute(t)?t:i.resolve(e,t),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);N(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)=>N(t)?$:"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(),Ve(e.cwd,e.bundler.outDir)).split("node_modules").pop().split(Ye).shift().replace(/^((\.\.?)?[/\\])+/g,""),st=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Ve(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 Je(n,e,t));for(const t of o){const n=nt(e,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}i.end(),r.pause()})),n.onEnd((n=>{r.resume();const o=t.time("collecting errors and warnings"),a=e.cwd;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 u=[],c=[],p=[],l=[],d=[],m={},f={},h=t.time("indexing metafile data"),g=st(n.metafile.inputs,a),y=st(n.metafile.outputs,a);h.end();const w=e=>{if(!N(e))return e;const t=g[Ve(a,e)];if(!t)return e;const n=t.imports.find((e=>!N(e.path)));return n?n.path:e},b=t.time("looping through inputs");for(const[t,s]of Object.entries(n.metafile.inputs)){if(N(t))continue;const n=Ve(a,t),o={name:nt(e,t),filepath:n,dependents:new Set,dependencies:new Set,size:s.bytes,type:Xe(t)};m[n]=o,u.push(o)}b.end();const v=t.time("looping through outputs");for(const[o,r]of Object.entries(n.metafile.outputs)){const n=Ve(a,o),i=nt(e,n),u=[];for(const e of Object.keys(r.inputs)){if(N(e))continue;const n=m[Ve(a,e)];n?u.push(n):t.debug(`Input ${e} not found for output ${i}`)}if(r.entryPoint&&!u.length){const e=m[Ve(a,r.entryPoint)];if(!e){t.debug(`Input ${r.entryPoint} not found for output ${i}`);continue}u.push(e)}const d={name:i,filepath:n,inputs:u,size:r.bytes,type:Xe(n)};if(f[n]=d,"map"===d.type&&l.push(d),c.push(d),!r.entryPoint)continue;const h=m[Ve(a,w(r.entryPoint))];if(h){if(!s.get(h.name))continue;const e={...d,name:s.get(h.name)||h.name,outputs:[d],size:d.size};p.push(e)}}v.end();const $=t.time("looping through sourcemaps");for(const e of l){const n=f[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}$.end();const k={inputs:{report:m,meta:g},outputs:{report:f,meta:y}},S=/(<runtime>|https:|file:|data:|#)/g,D=e=>!N(e)&&!e.match(S),E=(n,s,o={})=>{if(!D(n))return o;const r=s.report[n];if(!r)return t.debug(`Could not find report's ${n}`),o;if(o[r.filepath])return o;o[r.filepath]=r;const c=s.meta[n];if(!c)return t.debug(`Could not find metafile's ${n}`),o;if(!c.imports||!c.imports.length)return o;for(const t of c.imports){const c=t.path.match(/^\.\.?\//),p=c?i.dirname(n):a,l=Ve(p,t.path);if(t.external){if(D(t.path)){const n=c?l:t.path,s=k.inputs.report[n]||{filepath:n,name:nt(e,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in r&&(s.dependents.add(r),r.dependencies.add(s)),"inputs"in r&&!r.inputs.includes(s)&&r.inputs.push(s),u.includes(s)||u.push(s),k.inputs.report[n]=s,o[s.filepath]=s}}else E(l,s,o)}return o},x=t.time("looping through entries");for(const e of p){const t={},n={};for(const n of e.inputs)E(n.filepath,k.inputs,t);for(const t of e.outputs)E(t.filepath,k.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),d.push(e)}x.end();const M=t.time("aggregate dependencies and dependents");for(const e of u){if("external"===e.type)continue;const n=k.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=Ve(o,s.path);let u;if(s.external){const e=n?r:s.path;u=k.inputs.report[e]}else u=k.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}`)}M.end(),e.build.outputs=c,e.build.inputs=u,e.build.entries=d,r.end(),e.hook("buildReport",e.build)}))}}),rt=(e,t)=>{const n=t.time("module parsing",{start:!1});let s={};return{buildStart(){s={}},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),o=s[t]||{dependencies:new Set,dependents:new Set},r=et(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),i=et(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of i)o.dependents.add(e);for(const e of r)o.dependencies.add(e);s[t]=o,n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,o){const r=t.time("build report"),i=[],a=[],u=[],c=[],p={},l=[],d={},m={},f=t.time("completing dependencies and dependents");for(const[e,{dependencies:t,dependents:n}]of Object.entries(s)){for(const n of t){const t=tt(n);s[t]||(s[t]={dependencies:new Set,dependents:new Set}),s[t].dependents.has(e)||s[t].dependents.add(e)}for(const t of n){const n=tt(t);s[n]||(s[n]={dependencies:new Set,dependents:new Set}),s[n].dependencies.has(e)||s[n].dependencies.add(e)}}f.end();const h=t.time("filling inputs and outputs");for(const[n,r]of Object.entries(o)){const o={name:n,filepath:Ve(e.bundler.outDir,n),inputs:[],size:"code"in r?Buffer.byteLength(r.code,"utf8"):Buffer.byteLength(r.source,"utf8"),type:Xe(n)};if("map"===o.type&&c.push(o),"modules"in r)for(const[t,n]of Object.entries(r.modules)){if(tt(t)!==t)continue;const s={name:nt(e,t),dependencies:new Set,dependents:new Set,filepath:t,size:n.originalLength,type:Xe(t)};o.inputs.push(s),d[s.filepath]=s,i.push(s)}if("imports"in r)for(const n of r.imports){const r=tt(n);if(!s[r]){p[Ve(e.bundler.outDir,r)]=o;continue}if(d[r]){t.debug(`Input report already there for ${r} from ${o.name}.`);continue}const a={name:nt(e,n),dependencies:new Set,dependents:new Set,filepath:r,size:0,type:"external"};o.inputs.push(a),d[a.filepath]=a,i.push(a)}"isEntry"in r&&r.isEntry&&u.push({...o,name:r.name,size:0,outputs:[o]}),m[o.filepath]=o,a.push(o)}h.end();for(const[e,n]of Object.entries(p)){const s=m[e];s?n.inputs.includes(s)||n.inputs.push(s):t.debug(`Could not find the output report for ${e}.`)}const g=t.time("filling dependencies and dependents");for(const n of i){const o=s[n.filepath];if(o){for(const s of o.dependencies){const o=d[s];o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${nt(e,s)} of ${n.name}`)}for(const s of o.dependents){const o=d[s];o?n.dependents.add(o):t.debug(`Could not find input for dependent ${nt(e,s)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(g.end(),c.length){const e=t.time("filling sourcemaps inputs");for(const e of c){const n=e.filepath.replace(/\.map$/,""),s=m[n];s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}e.end()}const y=(n,s={})=>{if(s[n])return s;const r=nt(e,n),i=m[n];if(!i){return!!d[r]||t.debug(`Could not find output for ${r}`),s}s[n]=i;const a=o[nt(e,n)];if(!a)return t.debug(`Could not find asset for ${r}`),s;const u=[];"imports"in a&&u.push(...a.imports),"dynamicImports"in a&&u.push(...a.dynamicImports);for(const t of u)y(Ve(e.bundler.outDir,t),s);return s},w=t.time("filling entries");for(const e of u){const t=y(e.filepath);e.outputs=Object.values(t),e.inputs=Array.from(new Set(e.outputs.flatMap((e=>e.inputs)))),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),l.push(e)}w.end(),e.build.inputs=i,e.build.outputs=a,e.build.entries=l,r.end(),e.hook("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 ")||N(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"],s=e=>{const n=tt(e);t.add(n),n.startsWith("external ")&&t.add(h(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=Ve(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)g(e);r.end();const i=n.time("building inputs");for(const n of t){const t=n.identifier(),s=nt(e,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)?h(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:h(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(h(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.tap(t,(t=>{m.resume();const s=t.chunks,p=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Ve(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of s){const t=d(e),n=(g?g?.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)}}h.end();const y=n.time("building outputs");for(const t of p){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:Ve(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=>g?g.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?Ve(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(),e.hook("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=(e,t)=>{const n=(e=>{let t,n=Ve(process.cwd(),e),s=n.split(i.sep).length;for(;s>0;){const e=i.resolve(n,"package.json");j(e)&&(t=n),n=n.split(i.sep).slice(0,-1).join(i.sep),s--}return t})(t);if(n)return n;const s=(e=>{const t=[...e].map((e=>Ve(process.cwd(),e).split(i.sep))),n=t.length?Math.min(...t.map((e=>e.length))):0,s=[];for(let e=0;e<n;e++){const n=t[0][e];if(!t.every((t=>t[e]===n)))break;s.push(n)}return s.length>0&&s.join(i.sep)||i.sep})(Array.from(e));return s!==i.sep?s:void 0},pt=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=t.options.output.path),e.hook("bundlerReport",e.bundler),t.options.context&&(e.cwd=t.options.context),e.hook("cwd",e.cwd)},lt=e=>{const{context:t}=e,n=new Set,s=e=>{e&&(e.dir?(t.bundler.outDir=e.dir,n.add(e.dir)):e.file&&(t.bundler.outDir=i.dirname(e.file),n.add(t.bundler.outDir)),t.bundler.outDir=Ve(process.cwd(),t.bundler.outDir),"vite"!==t.bundler.name&&(t.cwd=ct(n,t.bundler.outDir)||t.cwd,t.hook("cwd",t.cwd)))},o=()=>({options(e){if(t.bundler.rawConfig=e,e.input)if(Array.isArray(e.input))for(const t of e.input)n.add(i.dirname(t));else if("object"==typeof e.input)for(const t of Object.values(e.input))n.add(i.dirname(t));else{if("string"!=typeof e.input)throw new Error("Invalid input type");n.add(i.dirname(e.input))}if("output"in e){const t=Array.isArray(e.output)?e.output:[e.output];for(const e of t)s(e)}t.hook("bundlerReport",t.bundler)}});return[{name:"datadog-bundler-report-plugin",enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.outdir&&(t.bundler.outDir=e.initialOptions.outdir),e.initialOptions.outfile&&(t.bundler.outDir=i.dirname(e.initialOptions.outfile)),t.hook("bundlerReport",t.bundler),e.initialOptions.absWorkingDir&&(t.cwd=e.initialOptions.absWorkingDir),t.hook("cwd",t.cwd),e.initialOptions.metafile=!0}},webpack:pt(t),rspack:pt(t),vite:{...o(),config(e){e.build?.outDir&&(t.bundler.outDir=e.build.outDir),e.root?t.cwd=e.root:t.cwd=ct(n,t.bundler.outDir)||t.cwd,t.hook("cwd",t.cwd)}},rollup:o()}]},dt="datadog-custom-hooks-plugin",mt=e=>{const{context:t}=e,n=t.getLogger(dt),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:dt,enforce:"pre"}]};class ft{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 ht=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await gt(e);for(const e of t)if(e.name===n)return A(e.refs.push);return A(t[0].refs.push)},gt=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},yt=async e=>e.revparse("HEAD"),wt=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),bt=async e=>e.branch(),vt=async e=>e.show(["-s","--format=%s"]),$t=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),kt="datadog-git-plugin",St=e=>{const{options:t,context:n}=e,s=n.getLogger(kt);return[{name:kt,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=await(async e=>{const t=[yt(e),bt(e),vt(e),$t(e),wt(e),ht(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 ft(i)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=y.simpleGit(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return y.simpleGit(t)})(n.cwd));n.git=t,e.end(),await n.asyncHook("git",n.git)}catch(e){s.error(`Could not get git information: ${e.message}`)}}}]},Dt="datadog-injection-plugin",Et=/^https?:\/\//,xt=async(e,t=process.cwd())=>(e=>o.readFile(e,{encoding:"utf-8"}))(Ve(t,e)),Mt=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(Et)?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 xt(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} - ${I(o)}`;e.fallback?(t.info(`Fallback for "${i}": ${r.toString()}`),s=await Mt(e.fallback,t,n)):t.warn(`Failed "${i}": ${r.toString()}`)}return s},Pt=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`},jt=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 Mt(r,t,n);e&&s.set(o,{value:e,position:r.position||ue.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},Tt=r.promises,Ot=(e,t,n)=>({setup(s){const{onStart:o,onResolve:a,onLoad:u,onEnd:c,esbuild:p,initialOptions:l}=s,d=[],m=`${q()}.${ue.MIDDLE}.${$}.js`,f=r.realpathSync(w.tmpdir()),h=i.resolve(f,m),g=new RegExp(`${m}$`),y=l.inject;l.inject=y?[...y]:[],l.inject.push(h),o((async()=>{d.push(...await Je(s,t,e)),s.initialOptions.inject=y;try{await M(h,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:g},(async e=>({path:e.path,namespace:Dt}))),u({filter:g,namespace:Dt},(async()=>({contents:Pt(n[ue.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),c((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=Pt(n[ue.BEFORE]),r=Pt(n[ue.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)))?Ve(t.cwd,e):void 0})).filter(Boolean).map((async e=>{const t=await Tt.readFile(e,"utf-8"),n=await p.transform(t,{loader:"default",banner:o,footer:r});await Tt.writeFile(e,n.code)}));await Promise.all(i)}))}}),zt=$,Nt="?inject-proxy",Rt=e=>({banner:t=>t.isEntry?Pt(e[ue.BEFORE]):"",async resolveId(t,n,s){if(N(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&Pt(e[ue.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${Nt}`}return null},load(t){if(N(t))return Pt(e[ue.MIDDLE]);if(t.endsWith(Nt)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(zt)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?Pt(e[ue.AFTER]):""}),It=(e,t,n,s,o)=>a=>{const u=new WeakMap,c=(e=>{if(!e?.sources?.ConcatSource)return b.createRequire(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),p=i.resolve(n.bundler.outDir,`${q()}.${ue.MIDDLE}.${$}.js`);P(p,"");const l=()=>{var e;e=p,r.rmSync(e,{force:!0,maxRetries:3,recursive:!0})};a.hooks.shutdown?a.hooks.shutdown.tap(Dt,l):(a.hooks.done.tap(Dt,l),a.hooks.failed.tap(Dt,l));a.hooks.beforeRun.tapPromise(Dt,(async()=>{await jt(t,s,o,n.cwd)})),a.hooks.compilation.tap(Dt,(t=>{const n=()=>{const e=Pt(o[ue.BEFORE]),n=Pt(o[ue.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:Dt,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:Dt},n)}));const d=(e=>{const s="webpack4"===n.bundler.fullName?p:{import:[p]},o=e=>{for(const[n,s]of Object.entries(e))"object"==typeof s?(s.import=s.import||[],s.import.unshift(p)):"string"==typeof s?e[n]=[p,s]:Array.isArray(s)?s.unshift(p):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=d},At=e=>{const{bundler:t,context:n}=e,s=n.getLogger(Dt),o=new Map,r={[ue.BEFORE]:new Map,[ue.MIDDLE]:new Map,[ue.AFTER]:new Map};n.inject=e=>{o.set(q(),e)};const i={name:Dt,enforce:"post",esbuild:Ot(s,n,r),webpack:It(t,s,n,o,r),rspack:It(t,s,n,o,r),rollup:Rt(r),vite:{...Rt(r),enforce:"pre"}};var a;return a=n.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(a)?(i.loadInclude=e=>!!N(e)||null,i.load=e=>N(e)?{code:Pt(r[ue.MIDDLE])}:null):i.buildStart=async()=>{await jt(s,o,r,n.cwd)},[i]},Ft="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(Ft,o):(e.hooks.done.tapPromise(Ft,o),e.hooks.failed.tap(Ft,s))},i={async writeBundle(){},async closeBundle(){await o()}};return[{name:Ft,enforce:"post",webpack:r,esbuild:{setup(e){e.onEnd((async()=>{await n()})),e.onDispose((()=>{s()}))}},vite:i,rollup:i,rspack:r}]},Ct={[ye]:He};var Lt="2.6.3-dev-5";const _t=(({bundler:n,version:s})=>{const o=Date.now();return e.createUnplugin(((e,r)=>{const i=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",metadata:{},...e}))(e);"esbuild"===r.framework&&(r.esbuildHostName=S);const a=process.env.BUILD_PLUGINS_ENV||"production",u=k.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:H(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:x(n),start:e,version:n.version}})({start:o,options:i,data:d,stores:m}),h=f.getLogger("factory").time("Plugins initialization",{start:o});f.pluginNames.push(S);const g=[];g.push(["analytics",Ke],["async-queue",Ge],["build-report",ut],["bundler-report",lt],["custom-hooks",mt],["git",St],["injection",At],["true-end",qt]),i.customPlugins&&g.push(["custom",i.customPlugins]),g.push(["error-tracking",ae],["rum",ge],["telemetry",Be]);for(const[e,t]of g)f.plugins.push(...K(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),h.end(),f.plugins}))})({bundler:v,version:Lt}).rollup,Ht=Lt,Bt=Ct;exports.datadogRollupPlugin=_t,exports.helpers=Bt,exports.version=Ht;
5
5
  //# sourceMappingURL=index.js.map