UNPKG

hud-sdk

Version:

Hud's Node SDK

2 lines 13.9 kB
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1244:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withHud=u;const i=r(1427),a=o(r(3024)),s=o(r(6760)),n=r(8448);function u(e,t){const o=e=>{const o=e.webpack;return{...e,webpack:(i,a)=>(o&&(i=o(i,a)),function(e,t,o){const{dev:i,isServer:a,nextRuntime:s}=t;if(i||!a||"edge"===s)return e;const{logger:n,hudWebpackPlugin:u}=o.__testOverrides??(()=>{const{logger:e}=r(5449),{hudWebpackPlugin:t}=r(9017);return{logger:e,hudWebpackPlugin:t}})(),l=e.devtool&&("source-map"===e.devtool||"inline-source-map"===e.devtool||"nosources-source-map"===e.devtool);return!l&&o.accessToken&&(n.debug("No source maps detected, temporarily enabling source-map"),e.devtool="source-map"),e.plugins=e.plugins||[],e.plugins.push(...u({...o,projectDir:t.dir,initFilePath:o.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}(i,a,{...t,distDir:e.distDir}))}};if("function"!=typeof e){const r=e,i=l();return i&&d(r.distDir||".next",t),i?o(c(r)):r}const i=e;return(e,r,...a)=>{const s=i(e,r,...a);return Promise.resolve(s).then(r=>(l(e)&&d(r.distDir||".next",t),l(e)?o(c(r)):r))}}function l(e){return!(!e||"phase-production-build"!==e)||(!(!process.argv.some(e=>"next"===e||e.endsWith(`${s.default.sep}next`))||!process.argv.includes("build"))||!!process.argv.some(e=>e.endsWith(`${s.default.sep}threadChild.js`)))}function c(e){const t=function(){try{const e=i.myRequire.resolve("next/package.json",{paths:[process.cwd()]}),t=a.default.readFileSync(e,"utf8"),r=JSON.parse(t),o=parseInt(r.version.split(".")[0],10);return isNaN(o)?null:o}catch{}return null}();if(null!==t&&t<16)return e;const r={loader:i.myRequire.resolve("hud-sdk/nextServerLoader"),options:{addDebugSnippet:!0}},o=e.turbopack?.rules??{},s={...o};for(const e of["*.ts","*.tsx","*.cts","*.mts","*.js","*.jsx","*.cjs","*.mjs"]){const t={condition:{all:["production",{not:"foreign"},{not:"browser"},{not:"edge-light"}]},loaders:[r]},i=o[e];s[e]=i?[t,...Array.isArray(i)?i:[i]]:t}return{...e,turbopack:{...e.turbopack??{},rules:s}}}let p=!1;function d(e,t){if(!p){p=!0;try{const r=t.initFilePath??"hud.ts",o=process.cwd(),i=s.default.join(o,r);if(!a.default.existsSync(i))return;const u=s.default.resolve(o,e);a.default.mkdirSync(u,{recursive:!0});const{isTypeScript:l,destinationFileName:c}=(0,n.getInitFileDestination)(r),p=l?(0,n.transpileTypeScript)(a.default.readFileSync(i,"utf8"),i):a.default.readFileSync(i,"utf8");a.default.writeFileSync(s.default.join(u,c),p,"utf8")}catch{}}}t.default=u},1427:e=>{e.exports=require("./nativerequire")},1455:e=>{e.exports=require("node:fs/promises")},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,r){var o=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:r=l.HUD_API_ENDPOINT,cleanupTempSourceMaps:o=!1}){return r.endsWith("/")&&(r=r.slice(0,-1)),async i=>{c.logger.debug("Recieved artifacts",{artifacts:i});const a=i.filter(e=>e.endsWith(".js")||e.endsWith(".mjs")||e.endsWith(".cjs"));if(0===a.length)return c.logger.warn("No build artifacts to upload"),!1;if(c.logger.debug("Uploading build artifacts",{artifacts:a}),o)for(const e of a){const r=`${e}.map`;try{await(0,n.access)(r),t.tempSourceMapFiles.add(r),c.logger.debug("Tracked source map for cleanup",{sourceMapPath:r})}catch{c.logger.debug("Source map doesn't exist, nothing to track",{sourceMapPath:r})}}const l=(await Promise.all(a.map(async t=>{try{const o=await async function(e){let t;try{t=await(0,n.readFile)(e,"utf-8")}catch{return void c.logger.error("Could not read file. File will not be source mapped: ",{uploadFilePath:e})}const r=await async function(e,t){const r=t.match(/^\s*\/\/# sourceMappingURL=(.*)$/m);if(r){const t=f(e,r[1]);if(t)try{return await(0,n.access)(t,s.default.constants.R_OK),t}catch{}}try{const t=`${e}.map`;return await(0,n.access)(t,s.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===r)return void c.logger.debug("Could not find source map for artifact. File will not be source mapped: ",{uploadFilePath:e});const o=d(t);if(void 0!==o)return{buildID:o,sourceMapPath:r};c.logger.error("Could not find build ID in artifact. File will not be source mapped: ",{uploadFilePath:e})}(t);if(void 0===o)return;if(c.logger.debug("Uploading source map",{path:o.sourceMapPath,buildID:o.buildID}),await p(o.buildID,o.sourceMapPath,r,e))return c.logger.debug("Source map uploaded successfully",{path:o.sourceMapPath,buildID:o.buildID}),{sourceMapPath:o.sourceMapPath,buildID:o.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 r=e.map(async e=>{try{await(0,n.unlink)(e)}catch(t){throw c.logger.error("Failed to clean up temporary source map",{filePath:e,error:t}),t}});await Promise.all(r)},t.getBuildIDForArtifact=d,t.resolveSourceMapUrl=f;const i=o(r(8938)),a=o(r(2305)),s=o(r(3024)),n=r(1455),u=o(r(6760)),l=r(8805),c=r(5449);async function p(e,t,r,o,u=!0){const d=new a.default;let f;d.append("build_id",e),d.append("token",o);try{f=await(0,n.readFile)(t,"utf-8")}catch(r){return c.logger.error("Failed to upload source map due file read failure",{error:r,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(r){c.logger.warn("Failed to parse the sourcemap as JSON",{error:r,path:t,buildID:e}),d.append("sourcemap",s.default.createReadStream(t))}try{await i.default.post(`${r}${l.HUD_API_URI}`,d,{headers:{"Content-Type":"multipart/form-data"},timeout:1e4})}catch(i){const a=i;return 401===a.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:a.message,status:a.response?.status,path:t,buildID:e}),u?(c.logger.debug("Retrying source map upload"),await new Promise(e=>setTimeout(e,1e3)),p(e,t,r,o,!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 r=u.default.normalize(t);try{if("file:"===new URL(r).protocol)return r}catch{return u.default.isAbsolute(r)?r:u.default.join(u.default.dirname(e),r)}}t.tempSourceMapFiles=new Set},5449:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.flushLogs=async function(e){try{let r=[];if(e)for(const o of t.logger.transports)if(o instanceof i.WorkerPortTransport){const t=o.getLogs().map(t=>({...t,accessToken:e}));r=r.concat(t)}if(e&&r.length>0)try{await a.default.post(s.HUD_API_LOG_ENDPOINT,{messages:r},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}catch{}}catch{}};const i=r(523),a=o(r(8938)),s=r(8805);t.logger=function(){const e=[new i.ConsoleTransport({isCustomerLogger:!0,enabled:!0,minLevel:s.USER_CONSOLE_LOG_LEVEL}),new i.WorkerPortTransport({messagesLimit:1e4})];return new i.Logger("hud-bundler-plugin",s.DEFAULT_LOG_LEVEL,e)}()},6760:e=>{e.exports=require("node:path")},6807:e=>{e.exports=require("webpack")},8448:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getInitFileDestination=function(e){const t=[".ts",".tsx",".mts",".cts"],r=t.some(t=>e.endsWith(t));return{isTypeScript:r,destinationFileName:r?i.default.basename(e).replace(new RegExp(`(${t.map(e=>e.replace(".","\\.")).join("|")})$`),".js"):i.default.basename(e)}},t.transpileTypeScript=function(e,t){const o=r(9899),i={target:o.ScriptTarget.ES2018,module:o.ModuleKind.CommonJS,esModuleInterop:!0,allowSyntheticDefaultImports:!0,skipLibCheck:!0,strict:!1,declaration:!1,sourceMap:!1};return o.transpileModule(e,{compilerOptions:i,fileName:t}).outputText};const i=o(r(6760))},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.getDebugIdSnippet=function(e){return`;!function(){try{globalThis? globalThis.${t.BUILD_ID_VAR_NAME}="${e}":null}catch(e){}}();`},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,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.hudWebpackPlugin=void 0;const i=r(2546),a=r(523),s=r(1455),n=o(r(6760)),u=r(3903),l=r(8805),c=r(4409),p=r(5449),d=r(8448);class f{apply(e){const t=e?.webpack?.BannerPlugin||r(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=>{const t=e?.chunk?.hash?(0,u.v5)(e.chunk.hash,l.HUD_UUID_NAMESPACE):(0,u.v4)();return(0,l.getDebugIdSnippet)(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??n.default.resolve(),r=Object.keys(e.assets).map(e=>n.default.join(t,e));await this.upload(r)?a.customer_logger.logEntry(i.UserLogs.WebpackUploadedSourcemapSuccess()):a.customer_logger.logEntry(i.UserErrorLogs.WebpackFailedUploadingSourcemap())}catch{p.logger.error("Source map upload failed - terminating plugin"),a.customer_logger.logEntry(i.UserErrorLogs.WebpackFailedUploadingSourcemap())}})}}class h{projectDir;initFilePath;distDir;constructor(e,t="hud.ts",r){this.projectDir=e,this.initFilePath=t,this.distDir=r}apply(e){this.projectDir?e.hooks.afterEmit.tapPromise("hud-init-file-copy-plugin",async()=>{try{const e=n.default.join(this.projectDir,this.initFilePath);try{await(0,s.access)(e)}catch{return void p.logger.warn("Init file not found, skipping copy",{sourcePath:e,initFile:this.initFilePath})}const t=this.distDir?n.default.join(this.projectDir,this.distDir):n.default.join(this.projectDir,".next"),{isTypeScript:r,destinationFileName:o}=(0,d.getInitFileDestination)(this.initFilePath);let i;if(r){p.logger.debug("Compiling TypeScript init file",{sourcePath:e,initFile:this.initFilePath});try{const t=await(0,s.readFile)(e,"utf-8");i=(0,d.transpileTypeScript)(t,e)}catch(t){return void p.logger.error("Failed to compile TypeScript init file",{error:t,sourcePath:e,initFile:this.initFilePath})}}else i=await(0,s.readFile)(e,"utf-8");const a=n.default.join(t,o);await(0,s.writeFile)(a,i,"utf-8"),p.logger.info("Successfully copied init file to output directory",{from:e,to:a,initFile:this.initFilePath,compiled:r})}catch(e){p.logger.error("Failed to copy init file",{error:e,initFile:this.initFilePath})}}):p.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=c.tempSourceMapFiles.size;await(0,c.cleanupTemporarySourceMaps)(),e>0&&p.logger.info(`Cleaned up ${e} temporary source map files`)}catch{p.logger.error("Source map cleanup failed - terminating plugin"),a.customer_logger.logEntry(i.UserErrorLogs.SourceMapCleanupFailed()),await(0,p.flushLogs)(this.accessToken),process.exit(1)}await(0,p.flushLogs)(this.accessToken)})}}t.hudWebpackPlugin=e=>{const t=[],r=p.logger.transports.find(e=>e instanceof a.ConsoleTransport);return r&&e.silent&&(r.enabled=!1),!e.verbose&&e.accessToken||r&&(r.minLevel="info"),e.accessToken||p.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,c.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 r(o){var i=t[o];if(void 0!==i)return i.exports;var a=t[o]={exports:{}};return e[o].call(a.exports,a,a.exports,r),a.exports}(1244)})()); //# sourceMappingURL=nextjsPlugin.js.map