hud-sdk
Version:
Hud's Node SDK
2 lines • 14.2 kB
JavaScript
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1244:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withHud=i;const a=r(o(6760));function i(e,t){const r=e=>{const r=e.webpack;return{...e,webpack:(a,i)=>(r&&(a=r(a,i)),function(e,t,r){const{dev:a,isServer:i,nextRuntime:n}=t;if(a||!i||"edge"===n)return e;const{logger:s}=o(5449),{hudWebpackPlugin:u}=o(9017),l=e.devtool&&("source-map"===e.devtool||"inline-source-map"===e.devtool||"nosources-source-map"===e.devtool);return!l&&r.accessToken&&(s.debug("No source maps detected, temporarily enabling source-map"),e.devtool="source-map"),e.plugins=e.plugins||[],e.plugins.push(...u({...r,projectDir:t.dir,initFilePath:r.initFilePath,cleanupTempSourceMaps:!l})),e.module||(e.module={}),e.module.rules||(e.module.rules=[]),e.module.rules.unshift({test:/\.[jt]sx?$/,enforce:"pre",exclude:/node_modules/,loader:"hud-sdk/nextServerLoader"}),e}(a,i,{...t,distDir:e.distDir}))}};if("function"!=typeof e){const t=e;return process.argv.some(e=>"next"===e||e.endsWith(`${a.default.sep}next`))&&process.argv.includes("build")?r(t):t}const i=e;return(e,t,...o)=>{const a="phase-production-build"===e,n=i(e,t,...o);return Promise.resolve(n).then(e=>a?r(e):e)}}t.default=i},1351:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(o(1620));class i extends a.default{savedLogs;constructor(e){super(e),this.savedLogs=[]}log(e,t){this.savedLogs.push(e),setImmediate(()=>this.emit("logged",e)),t()}}t.default=i},1455:e=>{e.exports=require("node:fs/promises")},1620:e=>{e.exports=require("winston-transport")},2305:e=>{e.exports=require("form-data")},2546:e=>{e.exports=require("./lib")},3024:e=>{e.exports=require("node:fs")},3903:e=>{e.exports=require("uuid")},4409:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.tempSourceMapFiles=void 0,t.createSourceMapUploadPlugin=function({accessToken:e,apiEndpoint:o=l.HUD_API_ENDPOINT,cleanupTempSourceMaps:r=!1}){return o.endsWith("/")&&(o=o.slice(0,-1)),async a=>{c.logger.debug("Recieved artifacts",{artifacts:a});const i=a.filter(e=>e.endsWith(".js")||e.endsWith(".mjs")||e.endsWith(".cjs"));if(0===i.length)return c.logger.warn("No build artifacts to upload"),!1;if(c.logger.debug("Uploading build artifacts",{artifacts:i}),r)for(const e of i){const o=`${e}.map`;try{await(0,s.access)(o),t.tempSourceMapFiles.add(o),c.logger.debug("Tracked source map for cleanup",{sourceMapPath:o})}catch{c.logger.debug("Source map doesn't exist, nothing to track",{sourceMapPath:o})}}const l=(await Promise.all(i.map(async t=>{try{const r=await async function(e){let t;try{t=await(0,s.readFile)(e,"utf-8")}catch{return void c.logger.error("Could not read file. File will not be source mapped: ",{uploadFilePath:e})}const o=await async function(e,t){const o=t.match(/^\s*\/\/# sourceMappingURL=(.*)$/m);if(o){const t=f(e,o[1]);if(t)try{return await(0,s.access)(t,n.default.constants.R_OK),t}catch{}}try{const t=`${e}.map`;return await(0,s.access)(t,n.default.constants.R_OK),t}catch{}c.logger.debug("Could not determine source map path - Did you turn on source map generation in your bundler?",{file:e})}(e,t);if(void 0===o)return void c.logger.debug("Could not find source map for artifact. File will not be source mapped: ",{uploadFilePath:e});const r=d(t);if(void 0!==r)return{buildID:r,sourceMapPath:o};c.logger.error("Could not find build ID in artifact. File will not be source mapped: ",{uploadFilePath:e})}(t);if(void 0===r)return;if(c.logger.debug("Uploading source map",{path:r.sourceMapPath,buildID:r.buildID}),await p(r.buildID,r.sourceMapPath,o,e))return c.logger.debug("Source map uploaded successfully",{path:r.sourceMapPath,buildID:r.buildID}),{sourceMapPath:r.sourceMapPath,buildID:r.buildID,sourceFilePath:t}}catch(e){c.logger.error("Error uploading source map",e)}}))).filter(Boolean);if(c.logger.info("Source Map Upload Report"),0===l.length)c.logger.info(" No source maps uploaded");else for(const e of l)e&&c.logger.info(` ${u.default.basename(e.sourceFilePath)} -> ${u.default.basename(e.sourceMapPath)} (build-id: ${e.buildID})`);return l.length>0}},t.cleanupTemporarySourceMaps=async function(){const e=Array.from(t.tempSourceMapFiles);if(t.tempSourceMapFiles.clear(),0===e.length)return;const o=e.map(async e=>{try{await(0,s.unlink)(e)}catch(t){throw c.logger.error("Failed to clean up temporary source map",{filePath:e,error:t}),t}});await Promise.all(o)},t.getBuildIDForArtifact=d,t.resolveSourceMapUrl=f;const a=r(o(8938)),i=r(o(2305)),n=r(o(3024)),s=o(1455),u=r(o(6760)),l=o(8805),c=o(5449);async function p(e,t,o,r,u=!0){const d=new i.default;let f;d.append("build_id",e),d.append("token",r);try{f=await(0,s.readFile)(t,"utf-8")}catch(o){return c.logger.error("Failed to upload source map due file read failure",{error:o,path:t,buildID:e}),!1}try{const e=JSON.parse(f);delete e.sourcesContent,d.append("sourcemap",JSON.stringify(e),{filename:"sourcemap",contentType:"application/json"})}catch(o){c.logger.warn("Failed to parse the sourcemap as JSON",{error:o,path:t,buildID:e}),d.append("sourcemap",n.default.createReadStream(t))}try{await a.default.post(`${o}${l.HUD_API_URI}`,d,{headers:{"Content-Type":"multipart/form-data"},timeout:1e4})}catch(a){const i=a;return 401===i.response?.status?(c.logger.error("Failed to upload source map: Unauthorized. Please check your access token."),!1):(c.logger.error("Failed to upload source map",{error:i.message,status:i.response?.status,path:t,buildID:e}),u?(c.logger.debug("Retrying source map upload"),await new Promise(e=>setTimeout(e,1e3)),p(e,t,o,r,!1)):(c.logger.error("Failed to upload source map: Retries exhausted"),!1))}return!0}function d(e){const t=e.match(`${l.BUILD_ID_VAR_NAME}="([0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12})"`);return t?t[1]:void 0}function f(e,t){const o=u.default.normalize(t);try{if("file:"===new URL(o).protocol)return o}catch{return u.default.isAbsolute(o)?o:u.default.join(u.default.dirname(e),o)}}t.tempSourceMapFiles=new Set},5449:function(e,t,o){var r,a=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var a=Object.getOwnPropertyDescriptor(t,o);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,a)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=t[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[t.length]=o);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o=r(e),n=0;n<o.length;n++)"default"!==o[n]&&a(t,e,o[n]);return i(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.getLogPath=h,t.flushLogs=async function(e){t.logger.end();let o=[];if(e)for(const r of t.logger.transports)r instanceof f.default&&(r.savedLogs.map(t=>(t.accessToken=e,t)),o=o.concat(r.savedLogs));const r=t.logger.transports.map(e=>new Promise(t=>{e.on("finish",t)}));if(await Promise.all(r),e&&o.length>0)try{await l.default.post(d.HUD_API_LOG_ENDPOINT,{messages:o},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}catch{}};const u=o(523),l=s(o(8938)),c=n(o(8161)),p=n(o(6760)),d=o(8805),f=s(o(1351));let g;function h(){const e=new Date,t=`bundler-plugin-${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}-${String(e.getHours()).padStart(2,"0")}${String(e.getMinutes()).padStart(2,"0")}${String(e.getSeconds()).padStart(2,"0")}.log`;return g??=p.join(function(){const e=c.homedir();switch(c.platform()){case"darwin":return p.join(e,"Library","Logs","hud");case"win32":return p.join(e,"AppData","hud","Logs");default:return p.join(e,".hud","logs")}}(),t)}t.logger=u.winston.createLogger({level:d.DEFAULT_LOG_LEVEL,transports:[new u.winston.transports.File({filename:h(),format:u.winston.format.combine(u.winston.format.label({label:"hud-bundler-plugin"}),u.winston.format.timestamp({format:()=>(new Date).toISOString()}),u.winston.format.json())}),new u.winston.transports.Console({level:d.USER_CONSOLE_LOG_LEVEL,format:u.winston.format.printf(({message:e,...t})=>(delete t.level,`Hud: ${e} ${Object.keys(t).length>0?` ${JSON.stringify(t)}`:""}`))}),new f.default({level:d.DEFAULT_LOG_LEVEL,format:u.winston.format.combine(u.winston.format.timestamp(),u.winston.format.json())})]})},6760:e=>{e.exports=require("node:path")},6807:e=>{e.exports=require("webpack")},8161:e=>{e.exports=require("node:os")},8805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HUD_API_LOG_ENDPOINT=t.HUD_API_URI=t.HUD_API_ENDPOINT=t.BUILD_ID_VAR_NAME=t.HUD_UUID_NAMESPACE=t.USER_CONSOLE_LOG_LEVEL=t.DEFAULT_LOG_LEVEL=void 0,t.DEFAULT_LOG_LEVEL="info",t.USER_CONSOLE_LOG_LEVEL="error",t.HUD_UUID_NAMESPACE="00c1e90b-af75-4d8e-9935-68485877f759",t.BUILD_ID_VAR_NAME="hudFileBuildID",t.HUD_API_ENDPOINT="https://api-prod.hud.io",t.HUD_API_URI="/sink/sourcemap",t.HUD_API_LOG_ENDPOINT="https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/"},8938:e=>{e.exports=require("axios")},9017:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.hudWebpackPlugin=void 0;const a=o(2546),i=o(523),n=o(1455),s=r(o(6760)),u=r(o(9899)),l=o(3903),c=o(8805),p=o(4409),d=o(5449);class f{apply(e){const t=e?.webpack?.BannerPlugin||o(6807).BannerPlugin;e.options.plugins=e.options.plugins||[],e.options.plugins.push(new t({raw:!0,footer:!0,include:/\.(js|ts|jsx|tsx|mjs|cjs|mts|cts)$/,banner:e=>{return t=e?.chunk?.hash?(0,l.v5)(e.chunk.hash,c.HUD_UUID_NAMESPACE):(0,l.v4)(),`;!function(){try{globalThis? globalThis.${c.BUILD_ID_VAR_NAME}="${t}":null}catch(e){}}();`;var t}}))}}class g{upload;constructor(e){this.upload=e}apply(e){e.hooks.afterEmit.tapPromise("hud-webpack-build-id-source-map-upload-plugin",async e=>{try{const t=e.outputOptions.path??s.default.resolve(),o=Object.keys(e.assets).map(e=>s.default.join(t,e));await this.upload(o)?i.customer_logger.log(a.UserLogs.WebpackUploadedSourcemapSuccess()):i.customer_logger.log(a.UserErrorLogs.WebpackFailedUploadingSourcemap())}catch{d.logger.error("Source map upload failed - terminating plugin"),i.customer_logger.log(a.UserErrorLogs.WebpackFailedUploadingSourcemap())}})}}class h{projectDir;initFilePath;distDir;constructor(e,t="hud.ts",o){this.projectDir=e,this.initFilePath=t,this.distDir=o}apply(e){this.projectDir?e.hooks.afterEmit.tapPromise("hud-init-file-copy-plugin",async()=>{try{const e=s.default.join(this.projectDir,this.initFilePath);try{await(0,n.access)(e)}catch{return void d.logger.warn("Init file not found, skipping copy",{sourcePath:e,initFile:this.initFilePath})}const t=this.distDir?s.default.join(this.projectDir,this.distDir):s.default.join(this.projectDir,".next"),o=this.initFilePath.endsWith(".ts")||this.initFilePath.endsWith(".tsx");let r,a;if(o){d.logger.debug("Compiling TypeScript init file",{sourcePath:e,initFile:this.initFilePath});try{r=await async function(e){const t=await(0,n.readFile)(e,"utf-8"),o={target:u.default.ScriptTarget.ES2018,module:u.default.ModuleKind.CommonJS,esModuleInterop:!0,allowSyntheticDefaultImports:!0,skipLibCheck:!0,strict:!1,declaration:!1,sourceMap:!1};return u.default.transpileModule(t,{compilerOptions:o,fileName:e}).outputText}(e),a=s.default.basename(this.initFilePath).replace(/\.tsx?$/,".js")}catch(t){return void d.logger.error("Failed to compile TypeScript init file",{error:t,sourcePath:e,initFile:this.initFilePath})}}else r=await(0,n.readFile)(e,"utf-8"),a=s.default.basename(this.initFilePath);const i=s.default.join(t,a);await(0,n.writeFile)(i,r,"utf-8"),d.logger.info("Successfully copied init file to output directory",{from:e,to:i,initFile:this.initFilePath,compiled:o})}catch(e){d.logger.error("Failed to copy init file",{error:e,initFile:this.initFilePath})}}):d.logger.info("No project directory provided, skipping init file copy")}}class m{cleanupTempSourceMaps;accessToken;constructor(e,t){this.cleanupTempSourceMaps=e,this.accessToken=t}apply(e){this.cleanupTempSourceMaps&&e.hooks.shutdown.tapPromise({name:"hud-webpack-cleanup-plugin",stage:Number.MAX_SAFE_INTEGER},async()=>{try{const e=p.tempSourceMapFiles.size;await(0,p.cleanupTemporarySourceMaps)(),e>0&&d.logger.info(`Cleaned up ${e} temporary source map files`)}catch{d.logger.error("Source map cleanup failed - terminating plugin"),i.customer_logger.log(a.UserErrorLogs.SourceMapCleanupFailed()),await(0,d.flushLogs)(this.accessToken),process.exit(1)}await(0,d.flushLogs)(this.accessToken)})}}t.hudWebpackPlugin=e=>{const t=[];return e.silent&&(d.logger.silent=!0),e.verbose&&(d.logger.transports[1].level="info"),e.accessToken||(d.logger.transports[1].level="info",d.logger.info("No access token provided. Source maps and logs will not be uploaded to Hud.")),e.accessToken&&(t.push(new f),t.push(new g((0,p.createSourceMapUploadPlugin)({accessToken:e.accessToken,apiEndpoint:e.apiEndpoint,cleanupTempSourceMaps:e.cleanupTempSourceMaps}))),t.push(new m(e.cleanupTempSourceMaps||!1,e.accessToken))),t.push(new h(e.projectDir,e.initFilePath,e.distDir)),t},t.default=t.hudWebpackPlugin},9899:e=>{e.exports=require("typescript")}},t={};return function o(r){var a=t[r];if(void 0!==a)return a.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,o),i.exports}(1244)})());
//# sourceMappingURL=nextjsPlugin.js.map