@metricinsights/pp-dev 0.15.1 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # [0.16.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v0.15.1...v0.16.0-beta.1) (2026-03-23)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **version-plugin:** hash concatenated digests without hex input encoding ([1ea5e5a](https://github.com/mi-examples/pp-dev/commit/1ea5e5aed6b78b3bd67110d173a5195b75434e9c))
7
+
8
+
9
+ ### Features
10
+
11
+ * version manifest plugin and upgrade to Vite 8 ([ad8c4ac](https://github.com/mi-examples/pp-dev/commit/ad8c4ac5b6bc7813d04947b418a5d3b77d2d75fb))
12
+
1
13
  ## [0.15.1-beta.1](https://github.com/mi-examples/pp-dev/compare/v0.15.0...v0.15.1-beta.1) (2026-03-12)
2
14
 
3
15
 
package/dist/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # [0.16.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v0.15.1...v0.16.0-beta.1) (2026-03-23)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **version-plugin:** hash concatenated digests without hex input encoding ([1ea5e5a](https://github.com/mi-examples/pp-dev/commit/1ea5e5aed6b78b3bd67110d173a5195b75434e9c))
7
+
8
+
9
+ ### Features
10
+
11
+ * version manifest plugin and upgrade to Vite 8 ([ad8c4ac](https://github.com/mi-examples/pp-dev/commit/ad8c4ac5b6bc7813d04947b418a5d3b77d2d75fb))
12
+
1
13
  ## [0.15.1-beta.1](https://github.com/mi-examples/pp-dev/compare/v0.15.0...v0.15.1-beta.1) (2026-03-12)
2
14
 
3
15
 
package/dist/cjs/cli.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("path"),o=require("fs"),t=require("node:perf_hooks"),n=require("chokidar"),i=require("cac"),r=require("vite"),s=require("./index-4BMbdu0V.js"),a=require("./plugin-nVTTdbnD.js"),l=require("url"),c=require("dir-compare"),d=require("diff-match-patch"),p=require("isbinaryfile"),f=require("os"),h=require("crypto"),g=require("extract-zip"),u=require("svgtofont");require("ejs"),require("http-proxy-middleware"),require("picocolors"),require("axios"),require("jsdom"),require("https"),require("memory-cache"),require("process"),require("child_process"),require("console"),require("zlib"),require("express");const m=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function b(e){if(e&&"object"==typeof e&&"default"in e)return e;const o=Object.create(null);if(e)for(const t in e)o[t]=e[t];return o.default=e,Object.freeze(o)}const w=b(e),v=b(o),y=b(c),x=m(d),P=b(f),T=b(h),L=m(g),$=m(u);function S(e){return null!=e&&!1!==e}const F=[{key:"r",description:"restart the server",async action(e){await e.restart()}},{key:"u",description:"show server url",action(e){e.config.logger.info(""),e.printUrls()}},{key:"o",description:"open in browser",action(e){e.openBrowser()}},{key:"c",description:"clear console",action(e){e.config.logger.clearScreen("error")}},{key:"q",description:"quit",async action(e){await e.close().finally(()=>process.exit())}},{key:"C",description:"clear proxy cache",action(e){e.cache&&(e.cache.clear(),e.config.logger.info("Proxy cache cleared"))}}];const C=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class E{oldAssetsPath;newAssetsPath;destinationPath;changelogFilename;changelogTemplate='<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>Changelog Diff</title>\n <style>\n tr,\n td {\n padding: 0;\n }\n .diff-file {\n margin-top: 20px;\n border: 1px solid #e1e4e8;\n border-radius: 6px;\n }\n .diff-file-title {\n padding: 10px 20px;\n background-color: #f6f8fa;\n border-bottom: 1px solid #e1e4e8;\n border-radius: 6px 6px 0 0;\n font-weight: bold;\n }\n .diff-file-title .renamed {\n font-weight: normal;\n }\n .diff-file-title .renamed .from {\n color: #cb2431;\n }\n .diff-file-title .renamed .to {\n color: #22863a;\n }\n .diff-file-title .added {\n color: #22863a;\n }\n .diff-file-title .deleted {\n color: #cb2431;\n }\n .diff-file-content {\n }\n .diff-table {\n tab-size: 8;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n }\n .blob-num {\n position: relative;\n color: #1f2328;\n width: 1%;\n min-width: 50px;\n padding: 0 10px;\n font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n font-size: 12px;\n line-height: 20px;\n text-align: right;\n white-space: nowrap;\n vertical-align: top;\n cursor: pointer;\n -webkit-user-select: none;\n user-select: none;\n }\n .blob-num.addition {\n background-color: #ccffd8;\n border-color: #1f883e;\n }\n .blob-num.deletion {\n background-color: #ffd7d5;\n border-color: #cf222e;\n }\n .blob-num::before {\n content: attr(data-line-number);\n }\n .blob-code {\n position: relative;\n padding: 0 10px 0 22px;\n vertical-align: top;\n color: #1f2329;\n }\n .blob-code.code-addition {\n background-color: #e6ffec;\n }\n .blob-code.code-deletion {\n background-color: #ffebe9;\n }\n .blob-code.skip,\n .blob-code.message {\n text-align: center;\n }\n .blob-code.skip .blob-code-inner,\n .blob-code.message .blob-code-inner {\n font-weight: bold;\n color: #6a737d;\n padding: 10px 0;\n }\n .blob-code-inner {\n display: table-cell;\n overflow: visible;\n font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n font-size: 12px;\n word-wrap: anywhere;\n white-space: pre-wrap;\n }\n .blob-code-inner::before {\n content: attr(data-code-prefix);\n position: absolute;\n top: 1px;\n left: 8px;\n padding-right: 8px;\n }\n </style>\n </head>\n <body>\n <h1>Changelog Diff</h1>\n\n %FILES%\n </body>\n </html>';diffFileTemplateHandler;diffLineTemplateHandler;contextLines=3;logger;constructor(e){const{oldAssetsPath:o,newAssetsPath:t,destinationPath:n,changelogTemplate:i,diffFileTemplateHandler:r,diffLineTemplateHandler:s,changelogFilename:l,contextLines:c}=e;if(this.logger=a.createLogger(),!o||!t||!n)throw new Error("Previous assets path, current assets path and destination path are required");if(o===t)throw new Error("Previous and current assets paths must be different");if(!this.isExists(o))throw new Error(`Previous assets path ${o} does not exist`);if(!this.isExists(t))throw new Error(`Current assets path ${t} does not exist`);if(this.isZipFile(o)){const e=w.resolve(P.tmpdir(),T.createHash("md5").update(o).digest("hex"));this.oldAssetsPath=this.unzipFile(o,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(o))throw new Error(`Invalid previous assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(t)){const e=w.resolve(P.tmpdir(),T.createHash("md5").update(t).digest("hex"));this.newAssetsPath=this.unzipFile(t,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e})}else{if(!this.isFolder(t))throw new Error(`Invalid current assets path ${t}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(t);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${t} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=n,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",i&&(this.templateIsValid(i)?this.changelogTemplate=i:this.logger.warn(a.colors.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof s&&(this.diffLineTemplateHandler=s),c&&(this.contextLines=c)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return v.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return v.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===v.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){v.existsSync(e)||v.mkdirSync(e,{recursive:!0})}async unzipFile(e,o){return v.rmSync(o,{force:!0,recursive:!0}),L(e,{dir:o})}normalizeAssetFolderPath(e){const o=v.readdirSync(e);return 1===o.length&&v.lstatSync(w.join(e,o[0])).isDirectory()?this.normalizeAssetFolderPath(w.join(e,o[0])):e}pathToPosix(e){return e.replace(/\\/g,"/")}diffTableTemplate(e){return`<table class="diff-table">\n <tbody>\n ${e}\n </tbody>\n </table>`}getDiffTableHTML(e){const o=e.filter((e,o,t)=>0!==e.lineType||(o>=0&&o<this.contextLines||o>t.length-(this.contextLines+1)&&o<=t.length-1||t.slice(o-this.contextLines,o+this.contextLines+1).some(e=>0!==e.lineType))).map((e,o,t)=>{if(o>0){const n=t[o-1];if(e.lineNumber-n.lineNumber>1)return[{lineNumber:-1,lineContent:"",lineType:0},e]}return[e]}).flat().map(e=>this.diffLineHTML(e)).join("");return this.diffTableTemplate(o)}diffLineMessageTemplate(e){return`<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code message">\n <span class="blob-code-inner">${e}</span>\n </td>\n </tr>`}diffLineSkipTemplate(){return'<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code skip">\n <span class="blob-code-inner">Skip</span>\n </td>\n </tr>'}diffLineTemplate(e){const{lineNumber:o,lineContent:t,lineType:n}=e,i=1===n?"addition":-1===n?"deletion":"";return`<tr>\n <td\n class="blob-num ${i}${"addition"===i?" empty":""}"\n ${"addition"!==i?` data-line-number="${o}"`:""}\n ></td>\n <td\n class="blob-num ${i}${"deletion"===i?" empty":""}"\n ${"deletion"!==i?` data-line-number="${o}"`:""}\n ></td>\n <td class="blob-code ${1===n?"code-addition":-1===n?"code-deletion":""}">\n <span class="blob-code-inner" data-code-prefix="${1===n?"+":-1===n?"-":" "}">${r=t??"",r.replace(/[\u00A0-\u9999<>&]/g,e=>"&#"+e.charCodeAt(0)+";")}</span>\n </td>\n </tr>`;var r}diffLineHTML(e){if(this.diffLineTemplateHandler)return this.diffLineTemplateHandler(e);const{lineNumber:o}=e;return-1===o?this.diffLineSkipTemplate():this.diffLineTemplate(e)}diffFileTemplate(e,o){return this.diffFileTemplateHandler?this.diffFileTemplateHandler(e,o):`<div class="diff-file">\n <div class="diff-file-title">${e}</div>\n <div class="diff-file-content">${o}</div>\n </div>`}async generateAssetFoldersDiff(){this.logger.info(a.colors.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await y.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,o)=>(C.test(e)&&(e=e.replace(C,"$1$3")),C.test(o)&&(o=o.replace(C,"$1$3")),0===e.localeCompare(o)?0:e.localeCompare(o)>0?1:-1)});return e.diffSet?.filter(e=>"equal"!==e.state||e.name1!==e.name2)||[]}async generateAssetFilesDiff(e,o){const t=new x,n=t.diff_linesToChars_(e,o),i=t.diff_main(n.chars1,n.chars2,!1);t.diff_charsToLines_(i,n.lineArray);let r=0;return i.map(e=>{const[o,t]=e,n=t.endsWith("\n")?t.split("\n").length-1:t.split("\n").length,i=t.split("\n").map((e,t)=>({lineContent:e,lineNumber:r+t+1,lineType:o})).slice(0,n);return-1!==o&&(r+=n),i}).flat()}async generateFilesDiff(e){if("equal"===e.state){const o=this.pathToPosix(w.join(".",e.relativePath,e.name1??"")),t=this.pathToPosix(w.join(".",e.relativePath,e.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${o}</span> -> <span class="to">${t}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const o=e.path1&&e.name1?w.join(e.path1,e.name1):null,t=e.path2&&e.name2?w.join(e.path2,e.name2):null,n=this.pathToPosix(w.join(".",e.relativePath,(e.name1||e.name2)??""));if("left"===e.state&&o)return this.diffFileTemplate(`<span class="removed">Removed ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===e.state&&t)return this.diffFileTemplate(`<span class="added">Added ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===e.state&&o&&t){const i=this.pathToPosix(w.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(w.join(".",e.relativePath,e.name2??"")),s=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${r}</span></span\n >`:n;return this.diffFileTemplate(s,await p.isBinaryFile(o)||await p.isBinaryFile(t)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(v.readFileSync(o,"utf-8"),v.readFileSync(t,"utf-8"))))}return""}async generateChangelog(){this.logger.info(a.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),o=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(a.colors.green("Writing changelog file"));const t=this.changelogTemplate.split("%FILES%");t.splice(1,0,o);const n=t.join("");v.writeFileSync(w.join(this.destinationPath,this.changelogFilename),n),this.logger.info(a.colors.green(`Changelog file written to ${w.join(this.destinationPath,this.changelogFilename)}`))}}class j{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await $({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}const A=i.cac("pp-dev");function I(e,o,t){const i=[...s.PP_DEV_CONFIG_NAMES,...s.PP_WATCH_CONFIG_NAMES,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"].map(o=>w.join(e,o)),r=n.watch(i,{ignored:e=>{const o=w.basename(e);return/(^|[\/\\])\../.test(e)&&!o.startsWith(".env")&&!o.startsWith(".pp-dev")&&!o.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let l=null;return r.on("change",n=>{t(a.colors.blue(`šŸ”§ Config file changed: ${w.relative(e,n)}`)),l&&clearTimeout(l),l=setTimeout(async()=>{try{t(a.colors.yellow("šŸ”„ Restarting dev server due to config change...")),await o()}catch(e){t(a.colors.red(`āŒ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{t(a.colors.red(`āŒ Config watcher error: ${e}`))}),{watcher:r,restartCallback:o,logger:t}}function D(e){e.watcher&&e.watcher.close()}let k=global.__pp_dev_profile_session,_=0;const N=e=>{if(k)return new Promise((o,t)=>{k.post("Profiler.stop",(n,{profile:i})=>{if(n)t(n);else{const t=w.resolve(`./pp-dev-profile-${_++}.cpuprofile`);v.writeFileSync(t,JSON.stringify(i)),e(a.colors.yellow(`CPU profile written to ${a.colors.white(a.colors.dim(t))}`)),k=void 0,o()}})})},R=e=>{for(const[o,t]of Object.entries(e))Array.isArray(t)&&(e[o]=t[t.length-1])};function q(e){const o={...e};return delete o["--"],delete o.c,delete o.config,delete o.base,delete o.l,delete o.logLevel,delete o.clearScreen,delete o.d,delete o.debug,delete o.f,delete o.filter,delete o.m,delete o.mode,o}A.option("-c, --config <file>","[string] use specified config file").option("--base <path>","[string] public base path (default: /)").option("-l, --logLevel <level>","[string] info | warn | error | silent").option("--clearScreen","[boolean] allow/disable clear screen when logging").option("-d, --debug [feat]","[string | boolean] show debug logs").option("-f, --filter <filter>","[string] filter debug logs").option("-m, --mode <mode>","[string] set env mode"),A.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{R(o);let n=null,i=null,l=!1;const c=e?w.resolve(process.cwd(),e):process.cwd(),d=a.createLogger(o.logLevel),p=async()=>{if(!l){l=!0;try{n&&(d.info(a.colors.yellow("šŸ›‘ Stopping existing dev server...")),await n.close(),n=null);const{clearConfigCache:f}=await Promise.resolve().then(()=>require("./index-4BMbdu0V.js")).then(e=>e.config);f();const{createServer:h}=await import("vite"),g=await r.loadConfigFromFile({mode:o.mode||"development",command:"serve"},o.config,e,o.logLevel);let u=await s.getViteConfig();const m=r.loadEnv(o.mode||"development",e??process.cwd(),"");if(m&&Object.keys(m).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=m[e])}),g){const{plugins:e,...o}=g.config;u=r.mergeConfig(u,o)}if(n=await h(r.mergeConfig(u,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},server:q(o),customLogger:d},!0)),!n.config.base||"/"===n.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!n.httpServer)throw new Error("HTTP server not available");await n.listen();const b=global.__pp_dev_start_time??!1,w=b?a.colors.dim(`ready in ${a.colors.reset(a.colors.bold(Math.ceil(t.performance.now()-b)))} ms`):"";d.info(`\n ${a.colors.green(`${a.colors.bold("PP-DEV")} v${s.VERSION}`)} ${w}\n`),n.printUrls(),function(e,o){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=o;const t=a.createLogger();o.print&&t.info(a.colors.dim(a.colors.green(" āžœ"))+a.colors.dim(" press ")+a.colors.bold("h")+a.colors.dim(" to show help"));const n=(o.customShortcuts??[]).filter(S).concat(F);let i=!1;const r=async o=>{if(""===o||""===o)return void await e.close().finally(()=>process.exit(1));if(i)return;"h"===o&&t.info(["",a.colors.bold(" Shortcuts"),...n.map(e=>a.colors.dim(" press ")+a.colors.bold(e.key)+a.colors.dim(` to ${e.description}`))].join("\n"));const r=n.find(e=>e.key===o);r&&(i=!0,await r.action(e),i=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume(),e.httpServer.on("close",()=>{process.stdin.off("data",r).pause()})}(n,{print:!0,customShortcuts:[...k?[{key:"p",description:"start/stop the profiler",async action(e){if(k)await N(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(o=>{k=new e.Session,k.connect(),k.post("Profiler.enable",()=>{k?.post("Profiler.start",()=>{d.info("Profiler started"),o()})})})}}}]:[],{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]}),i||(i=I(c,p,d.info),d.info(a.colors.blue("šŸ”§ Config file watcher started"))),l=!1}catch(e){l=!1,d.error(a.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),N(d.info),process.exit(1)}}},f=async e=>{d.info(a.colors.yellow(`\nšŸ›‘ Received ${e}, shutting down gracefully...`));try{i&&(D(i),i=null),n&&(await n.close(),n=null),N(d.info),d.info(a.colors.green("āœ… Graceful shutdown completed")),process.exit(0)}catch(e){d.error(a.colors.red(`āŒ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),process.on("uncaughtException",e=>{d.error(a.colors.red(`āŒ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,o)=>{d.error(a.colors.red(`āŒ Unhandled Rejection at: ${o}, reason: ${e}`)),f("unhandledRejection")}),await p()}),A.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{R(o);let t=null,n=null,i=null,c=!1;const d=a.createLogger(),p=async()=>{if(!c){c=!0;try{const{next:h,constants:g}=await s.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:u}=g;n&&(d.info(a.colors.yellow("šŸ›‘ Stopping existing Next.js server...")),await new Promise(e=>{n.close(()=>{n=null,e()})})),t&&"function"==typeof t.close&&(await t.close(),t=null);const{clearConfigCache:m}=await Promise.resolve().then(()=>require("./index-4BMbdu0V.js")).then(e=>e.config);m();const{join:b,basename:w}=await import("path"),{createServer:v}=await import("http"),y=await import("next/dist/server/config.js"),x=y.default.default||y["module.exports"].default||y.default,P=q(o),T=r.loadEnv(o.mode||"development",e??process.cwd(),"");T&&Object.keys(T).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=T[e])});const L=e?b(process.cwd(),e):process.cwd();d.info(L);const $=await x(u,L);let S=$?.ppDev||{};if(0===Object.keys(S).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-4BMbdu0V.js")).then(e=>e.config),o=await e();Object.keys(o).length>0?(S=o,d.info(a.colors.blue("šŸ”§ Loaded pp-dev config from standalone config file"))):d.info(a.colors.yellow("āš ļø No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){d.info(a.colors.yellow("āš ļø Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else d.info(a.colors.blue("šŸ”§ Loaded pp-dev config from Next.js config"));const{backendBaseURL:F=process.env.MI_BACKEND_URL||"http://localhost:8080",appId:C,portalPageId:E,templateLess:j=!0,v7Features:A=!0,disableSSLValidation:k=!1,enableProxyCache:_=!0,proxyCacheTTL:N=6e5,personalAccessToken:R=process.env.MI_ACCESS_TOKEN,miHudLess:M=!1}=S,z=C??E??(process.env.MI_APP_ID&&parseInt(process.env.MI_APP_ID,10)||void 0)??(process.env.MI_PORTAL_PAGE_ID&&parseInt(process.env.MI_PORTAL_PAGE_ID,10)||void 0)??1;let H=null;if(!H)try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-4BMbdu0V.js")).then(e=>e.config);H=e().name}catch(e){H=w(L)}const G="/p",O="/pl",U=$?.basePath;let W="";if(U?W=U:(W=j?G:A?O:"/pt",W+=`/${H}`),t=h({dev:!0,hostname:P.host||"localhost",port:P.port,dir:L,conf:{...$,basePath:W,assetPrefix:`${j?G:"/pt"}/${H}`}}),await t.prepare(),W.endsWith("/")||(W+="/"),"/"===W)throw new Error('basePath cannot be equal to "/" or equal to empty string');d.info(a.colors.green("āœ… Next.js app prepared successfully")),d.info(a.colors.blue(`šŸ”§ pp-dev plugin configured for template: ${H}`)),d.info(a.colors.blue(`šŸ”§ Base path configured: ${W}`)),F&&(d.info(a.colors.blue(`🌐 Backend URL: ${F}`)),d.info(a.colors.blue(`šŸ†” Custom App ID: ${z}`)));const V=t.getRequestHandler(),B="number"==typeof P.port?P.port:3e3,Z="string"==typeof P.host?P.host||"0.0.0.0":"localhost",K=new Set;n=v(async(e,o)=>{try{const t=e.url||"/",n=t.split("?")[0];let i=l.parse(t,!0);if(J.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(Q.length>0){let c=0;const d=()=>{if(c>=Q.length)return void r();const t=Q[c];c++,t(e,o,d)};return void d()}return void r()}let s=0;const a=()=>{if(s>=J.length)return void r();const t=J[s];s++,t(e,o,a)};return void a()}async function r(){if(n.startsWith(W))i=l.parse(t,!0);else{if(n===W.replace(/\/$/,"")){const e=t.replace(n,W);return o.writeHead(302,{Location:e}),void o.end()}if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_"));else if("/"===n)return o.writeHead(302,{Location:W}),void o.end()}await V(e,o,i)}r()}catch(p){console.error("[DEBUG] Error:",p),o.statusCode=500,o.end("Internal Server Error")}});let Y=null,J=[],Q=[];if(F){const e=new URL(F).host,o={headers:{host:e,referer:F,origin:F.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},portalPageId:z,appId:z,templateLess:j,disableSSLValidation:k,v7Features:A,personalAccessToken:R??process.env.MI_ACCESS_TOKEN};Y=new a.MiAPI(F,o);const t=a.initPPRedirect(W,H),n=(e,o,n)=>{t(e,o,n)};if(Q.push(n),J.push(n),_){let e=+N;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const o={devServer:{middlewares:{use:e=>e},config:{logger:console}},ttl:e},t=a.initProxyCache(o),n=(e,o,n)=>{t(e,o,n)};J.push(n),d.info(a.colors.blue(`šŸ”§ Proxy cache middleware added with TTL: ${e}ms`))}const i=W.endsWith("/")?W.substring(0,W.length-1):W,r={middlewares:{use:e=>e},config:{logger:console}},s=a.initProxy({devServer:r,baseURL:F,proxyIgnore:["/@vite","/@metricinsights","/@",i,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:k,miAPI:Y}),l=(e,o,t)=>{s(e,o,t)};J.push(l);const c=new RegExp(`^((${f=W,f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),p=a.initLoadPPData(c,Y,Object.assign({base:W},o)),h=(e,o,t)=>{p(e,o,t)};J.push(h);const g=a.internalServer,u=(e,o,t)=>{if(e.url?.startsWith("/@api/")){return void g(e,o,()=>{})}t()};Q.push(u),J.push(u);const m=a.initRewriteResponse(e=>{const o=e.split("?")[0];return o.startsWith(W)&&!o.includes("/_next/")},(o,t)=>Buffer.from(a.urlReplacer(e,t.headers.host??"",Y.buildPage(o,M)))),b=(e,o,t)=>{m(e,o,t)};J.push(b),d.info(a.colors.blue(`šŸ”§ ${J.length} pp-dev middlewares initialized`)),d.info(a.colors.blue(`šŸ”§ ${Q.length} essential middlewares for internal routes`)),d.info(a.colors.blue(`šŸ”§ MiAPI initialized for backend: ${F}`)),d.info(a.colors.blue(`šŸ”§ Custom App ID: ${z}`))}n.listen(B,Z,()=>{d.info(a.colors.green(`āœ… pp-dev Next.js server running at http://${Z}:${B}`)),d.info(a.colors.blue(`šŸ“± Next.js app accessible at http://${Z}:${B}${W}`)),d.info(a.colors.blue("šŸ”§ Base path handling active")),i||(i=I(L,p,d.info),d.info(a.colors.blue("šŸ”§ Config file watcher started"))),n.on("connection",e=>{K.add(e),e.on("close",()=>K.delete(e))});const e=async e=>{d.info(a.colors.yellow(`\nšŸ›‘ Received ${e}, shutting down gracefully...`));const o=setTimeout(()=>{d.info(a.colors.yellow("ā° Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{i&&(D(i),i=null);for(const e of Array.from(K))e.destroy();K.clear(),await new Promise(e=>{n.close(()=>{d.info(a.colors.yellow("šŸ›‘ HTTP server closed")),e()})}),t&&"function"==typeof t.close&&(await t.close(),d.info(a.colors.yellow("šŸ›‘ Next.js app closed"))),clearTimeout(o),d.info(a.colors.green("āœ… Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(o),d.error(a.colors.red(`āŒ Error during graceful shutdown: ${e}`)),process.exit(1)}};let o=process;if("function"!=typeof process.on){const e=globalThis.process||global.process;e&&"function"==typeof e.on&&(o=e,d.info(a.colors.green("āœ… Using global process object for event handlers")))}if("function"==typeof o.on)try{o.on("SIGINT",()=>e("SIGINT")),o.on("SIGTERM",()=>e("SIGTERM")),o.on("uncaughtException",o=>{d.error(a.colors.red(`āŒ Uncaught Exception: ${o}`)),e("uncaughtException")}),o.on("unhandledRejection",(o,t)=>{d.error(a.colors.red(`āŒ Unhandled Rejection at: ${t}, reason: ${o}`)),e("unhandledRejection")}),d.info(a.colors.green("āœ… Process event handlers registered successfully"))}catch(e){d.warn(a.colors.yellow(`āš ļø Failed to register process event handlers: ${e}`))}else d.warn(a.colors.yellow("āš ļø process.on is not available, graceful shutdown handlers will not be registered")),d.info(a.colors.blue("šŸ’” This might be due to bundling or environment constraints"))}),c=!1}catch(e){c=!1,d.error(a.colors.red(`āŒ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(d.error(a.colors.red("āŒ Next.js Peer Dependency Error:")),d.error(a.colors.red(e.message)),d.error(a.colors.yellow("\nšŸ’” To fix this issue:")),d.error(a.colors.blue(" 1. Install Next.js in your project:")),d.error(a.colors.white(" npm install next@^16")),d.error(a.colors.blue(" 2. Or use yarn:")),d.error(a.colors.white(" yarn add next@^16")),d.error(a.colors.blue(" 3. Or use pnpm:")),d.error(a.colors.white(" pnpm add next@^16")),d.error(a.colors.yellow("\nšŸ“– For more information, see:")),d.error(a.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var f}},f=async e=>{d.info(a.colors.yellow(`\nšŸ›‘ Received ${e}, shutting down gracefully...`));try{i&&(D(i),i=null),n&&await new Promise(e=>{n.close(()=>{n=null,e()})}),t&&"function"==typeof t.close&&(await t.close(),t=null),d.info(a.colors.green("āœ… Graceful shutdown completed")),process.exit(0)}catch(e){d.error(a.colors.red(`āŒ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),process.on("uncaughtException",e=>{d.error(a.colors.red(`āŒ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,o)=>{d.error(a.colors.red(`āŒ Unhandled Rejection at: ${o}, reason: ${e}`)),f("unhandledRejection")}),await p()}),A.command("build [root]","build for production").option("--target <target>","[string] transpile target (default: 'modules')").option("--outDir <dir>","[string] output directory (default: dist)").option("--assetsDir <dir>","[string] directory under outDir to place assets in (default: assets)").option("--assetsInlineLimit <number>","[number] static asset base64 inline threshold in bytes (default: 4096)").option("--ssr [entry]","[string] build specified entry for server-side rendering").option("--sourcemap [output]",'[boolean | "inline" | "hidden"] output source maps for build (default: false)').option("--minify [minifier]",'[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)').option("--manifest [name]","[boolean | string] emit build manifest json").option("--ssrManifest [name]","[boolean | string] emit ssr manifest json").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle (experimental)").option("--emptyOutDir","[boolean] force empty outDir when it's outside of root").option("-w, --watch","[boolean] rebuilds when modules have changed on disk").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").action(async(e,o)=>{R(o);const t=q(o);try{const n=await r.loadConfigFromFile({mode:o.mode||"production",command:"build"},o.config,e,o.logLevel);let i=await s.getViteConfig();if(n){const{plugins:e,...o}=n.config;i=r.mergeConfig(i,o)}const l=r.mergeConfig(i,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},build:t},!0);if(await r.build(l),t.changelog){const n=e||process.cwd(),i=l.build?.outDir||"dist";let r="";if("string"==typeof t.changelog)r=w.resolve(n,t.changelog);else{const e=w.resolve(n,l.ppDevConfig?.syncBackupsDir||"backups");if(!v.existsSync(e))return void a.createLogger(o.logLevel).warn(a.colors.yellow("backups directory not found, skipping changelog generation"));const t=v.readdirSync(e,{withFileTypes:!0});if(!t.length)return void a.createLogger(o.logLevel).warn(a.colors.yellow("no backups found, skipping changelog generation"));const i=t.filter(e=>e.isFile()&&e.name.endsWith(".zip")).reduce((o,t)=>v.statSync(w.resolve(e,o.name)).mtimeMs>v.statSync(w.resolve(e,t.name)).mtimeMs?o:t,t[0]).name;r=w.resolve(e,i)}const s=w.resolve(n,i);let c="dist-zip";l.ppDevConfig&&(!1===l.ppDevConfig.distZip?c=l.build?.outDir||"dist":"object"==typeof l.ppDevConfig.distZip&&"string"==typeof l.ppDevConfig.distZip.outDir&&(c=l.ppDevConfig.distZip.outDir));const d=new E({oldAssetsPath:r,newAssetsPath:s,destinationPath:w.resolve(n,c)});await d.generateChangelog()}}catch(e){a.createLogger(o.logLevel).error(a.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{N(e=>a.createLogger(o.logLevel).info(e))}}),A.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action(async(e,o,t)=>{R(t);const{oldAssetsPath:n=e,newAssetsPath:i=o,destination:r=".",filename:s="CHANGELOG.html",logLevel:l}=t,c=process.cwd();n&&i||(a.createLogger(l).error(a.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=w.resolve(c,n),p=w.resolve(c,i),f=w.resolve(c,r),h=new E({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:s});await h.generateChangelog()}),A.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(e,o,t)=>{R(t);const{source:n=e,destination:i=o,fontName:r="icon-font"}=t,s=process.cwd(),l=w.resolve(s,n),c=w.resolve(s,i),d=new j({sourceDir:l,outputDir:c,fontName:r}),p=a.createLogger(t.logLevel);p.info(`Generating icon font from SVG files in ${a.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${a.colors.dim(c)}`)}),A.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{R(o);try{const t=await r.loadConfigFromFile({mode:o.mode||"production",command:"build"},o.config,e,o.logLevel);let n=await s.getViteConfig();if(t){const{plugins:e,...o}=t.config;n=r.mergeConfig(n,o)}const i=await r.resolveConfig(r.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode}),"serve");await r.optimizeDeps(i,o.force,!0)}catch(e){a.createLogger(o.logLevel).error(a.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),A.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,o)=>{R(o);try{const t=await r.loadConfigFromFile({mode:o.mode||"production",command:"build"},o.config,e,o.logLevel);let n=await s.getViteConfig();if(t){const{plugins:e,...o}=t.config;n=r.mergeConfig(n,o)}(await r.preview(r.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode,build:{outDir:o.outDir},preview:{port:o.port,strictPort:o.strictPort,host:o.host,https:o.https,open:o.open}}))).printUrls()}catch(e){a.createLogger(o.logLevel).error(a.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{N(e=>a.createLogger(o.logLevel).info(e))}}),A.help(),A.version(s.VERSION),A.parse(),exports.stopProfiler=N;
1
+ "use strict";const e=require("path"),o=require("fs"),t=require("node:perf_hooks"),n=require("chokidar"),i=require("cac"),r=require("vite"),s=require("./index-Bu8AM2lb.js"),a=require("./plugin-D-TIdILy.js"),l=require("url"),c=require("dir-compare"),d=require("diff-match-patch"),p=require("isbinaryfile"),f=require("os"),h=require("crypto"),g=require("extract-zip"),u=require("svgtofont");require("ejs"),require("http-proxy-middleware"),require("picocolors"),require("axios"),require("jsdom"),require("https"),require("memory-cache"),require("process"),require("child_process"),require("console"),require("zlib"),require("express");const m=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function b(e){if(e&&"object"==typeof e&&"default"in e)return e;const o=Object.create(null);if(e)for(const t in e)o[t]=e[t];return o.default=e,Object.freeze(o)}const w=b(e),v=b(o),y=b(c),x=m(d),P=b(f),T=b(h),L=m(g),$=m(u);function S(e){return null!=e&&!1!==e}const F=[{key:"r",description:"restart the server",async action(e){await e.restart()}},{key:"u",description:"show server url",action(e){e.config.logger.info(""),e.printUrls()}},{key:"o",description:"open in browser",action(e){e.openBrowser()}},{key:"c",description:"clear console",action(e){e.config.logger.clearScreen("error")}},{key:"q",description:"quit",async action(e){await e.close().finally(()=>process.exit())}},{key:"C",description:"clear proxy cache",action(e){e.cache&&(e.cache.clear(),e.config.logger.info("Proxy cache cleared"))}}];const C=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class E{oldAssetsPath;newAssetsPath;destinationPath;changelogFilename;changelogTemplate='<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>Changelog Diff</title>\n <style>\n tr,\n td {\n padding: 0;\n }\n .diff-file {\n margin-top: 20px;\n border: 1px solid #e1e4e8;\n border-radius: 6px;\n }\n .diff-file-title {\n padding: 10px 20px;\n background-color: #f6f8fa;\n border-bottom: 1px solid #e1e4e8;\n border-radius: 6px 6px 0 0;\n font-weight: bold;\n }\n .diff-file-title .renamed {\n font-weight: normal;\n }\n .diff-file-title .renamed .from {\n color: #cb2431;\n }\n .diff-file-title .renamed .to {\n color: #22863a;\n }\n .diff-file-title .added {\n color: #22863a;\n }\n .diff-file-title .deleted {\n color: #cb2431;\n }\n .diff-file-content {\n }\n .diff-table {\n tab-size: 8;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n }\n .blob-num {\n position: relative;\n color: #1f2328;\n width: 1%;\n min-width: 50px;\n padding: 0 10px;\n font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n font-size: 12px;\n line-height: 20px;\n text-align: right;\n white-space: nowrap;\n vertical-align: top;\n cursor: pointer;\n -webkit-user-select: none;\n user-select: none;\n }\n .blob-num.addition {\n background-color: #ccffd8;\n border-color: #1f883e;\n }\n .blob-num.deletion {\n background-color: #ffd7d5;\n border-color: #cf222e;\n }\n .blob-num::before {\n content: attr(data-line-number);\n }\n .blob-code {\n position: relative;\n padding: 0 10px 0 22px;\n vertical-align: top;\n color: #1f2329;\n }\n .blob-code.code-addition {\n background-color: #e6ffec;\n }\n .blob-code.code-deletion {\n background-color: #ffebe9;\n }\n .blob-code.skip,\n .blob-code.message {\n text-align: center;\n }\n .blob-code.skip .blob-code-inner,\n .blob-code.message .blob-code-inner {\n font-weight: bold;\n color: #6a737d;\n padding: 10px 0;\n }\n .blob-code-inner {\n display: table-cell;\n overflow: visible;\n font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n font-size: 12px;\n word-wrap: anywhere;\n white-space: pre-wrap;\n }\n .blob-code-inner::before {\n content: attr(data-code-prefix);\n position: absolute;\n top: 1px;\n left: 8px;\n padding-right: 8px;\n }\n </style>\n </head>\n <body>\n <h1>Changelog Diff</h1>\n\n %FILES%\n </body>\n </html>';diffFileTemplateHandler;diffLineTemplateHandler;contextLines=3;logger;constructor(e){const{oldAssetsPath:o,newAssetsPath:t,destinationPath:n,changelogTemplate:i,diffFileTemplateHandler:r,diffLineTemplateHandler:s,changelogFilename:l,contextLines:c}=e;if(this.logger=a.createLogger(),!o||!t||!n)throw new Error("Previous assets path, current assets path and destination path are required");if(o===t)throw new Error("Previous and current assets paths must be different");if(!this.isExists(o))throw new Error(`Previous assets path ${o} does not exist`);if(!this.isExists(t))throw new Error(`Current assets path ${t} does not exist`);if(this.isZipFile(o)){const e=w.resolve(P.tmpdir(),T.createHash("md5").update(o).digest("hex"));this.oldAssetsPath=this.unzipFile(o,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(o))throw new Error(`Invalid previous assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(t)){const e=w.resolve(P.tmpdir(),T.createHash("md5").update(t).digest("hex"));this.newAssetsPath=this.unzipFile(t,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e})}else{if(!this.isFolder(t))throw new Error(`Invalid current assets path ${t}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(t);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${t} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=n,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",i&&(this.templateIsValid(i)?this.changelogTemplate=i:this.logger.warn(a.colors.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof s&&(this.diffLineTemplateHandler=s),c&&(this.contextLines=c)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return v.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return v.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===v.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){v.existsSync(e)||v.mkdirSync(e,{recursive:!0})}async unzipFile(e,o){return v.rmSync(o,{force:!0,recursive:!0}),L(e,{dir:o})}normalizeAssetFolderPath(e){const o=v.readdirSync(e);return 1===o.length&&v.lstatSync(w.join(e,o[0])).isDirectory()?this.normalizeAssetFolderPath(w.join(e,o[0])):e}pathToPosix(e){return e.replace(/\\/g,"/")}diffTableTemplate(e){return`<table class="diff-table">\n <tbody>\n ${e}\n </tbody>\n </table>`}getDiffTableHTML(e){const o=e.filter((e,o,t)=>0!==e.lineType||(o>=0&&o<this.contextLines||o>t.length-(this.contextLines+1)&&o<=t.length-1||t.slice(o-this.contextLines,o+this.contextLines+1).some(e=>0!==e.lineType))).map((e,o,t)=>{if(o>0){const n=t[o-1];if(e.lineNumber-n.lineNumber>1)return[{lineNumber:-1,lineContent:"",lineType:0},e]}return[e]}).flat().map(e=>this.diffLineHTML(e)).join("");return this.diffTableTemplate(o)}diffLineMessageTemplate(e){return`<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code message">\n <span class="blob-code-inner">${e}</span>\n </td>\n </tr>`}diffLineSkipTemplate(){return'<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code skip">\n <span class="blob-code-inner">Skip</span>\n </td>\n </tr>'}diffLineTemplate(e){const{lineNumber:o,lineContent:t,lineType:n}=e,i=1===n?"addition":-1===n?"deletion":"";return`<tr>\n <td\n class="blob-num ${i}${"addition"===i?" empty":""}"\n ${"addition"!==i?` data-line-number="${o}"`:""}\n ></td>\n <td\n class="blob-num ${i}${"deletion"===i?" empty":""}"\n ${"deletion"!==i?` data-line-number="${o}"`:""}\n ></td>\n <td class="blob-code ${1===n?"code-addition":-1===n?"code-deletion":""}">\n <span class="blob-code-inner" data-code-prefix="${1===n?"+":-1===n?"-":" "}">${r=t??"",r.replace(/[\u00A0-\u9999<>&]/g,e=>"&#"+e.charCodeAt(0)+";")}</span>\n </td>\n </tr>`;var r}diffLineHTML(e){if(this.diffLineTemplateHandler)return this.diffLineTemplateHandler(e);const{lineNumber:o}=e;return-1===o?this.diffLineSkipTemplate():this.diffLineTemplate(e)}diffFileTemplate(e,o){return this.diffFileTemplateHandler?this.diffFileTemplateHandler(e,o):`<div class="diff-file">\n <div class="diff-file-title">${e}</div>\n <div class="diff-file-content">${o}</div>\n </div>`}async generateAssetFoldersDiff(){this.logger.info(a.colors.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await y.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,o)=>(C.test(e)&&(e=e.replace(C,"$1$3")),C.test(o)&&(o=o.replace(C,"$1$3")),0===e.localeCompare(o)?0:e.localeCompare(o)>0?1:-1)});return e.diffSet?.filter(e=>"equal"!==e.state||e.name1!==e.name2)||[]}async generateAssetFilesDiff(e,o){const t=new x,n=t.diff_linesToChars_(e,o),i=t.diff_main(n.chars1,n.chars2,!1);t.diff_charsToLines_(i,n.lineArray);let r=0;return i.map(e=>{const[o,t]=e,n=t.endsWith("\n")?t.split("\n").length-1:t.split("\n").length,i=t.split("\n").map((e,t)=>({lineContent:e,lineNumber:r+t+1,lineType:o})).slice(0,n);return-1!==o&&(r+=n),i}).flat()}async generateFilesDiff(e){if("equal"===e.state){const o=this.pathToPosix(w.join(".",e.relativePath,e.name1??"")),t=this.pathToPosix(w.join(".",e.relativePath,e.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${o}</span> -> <span class="to">${t}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const o=e.path1&&e.name1?w.join(e.path1,e.name1):null,t=e.path2&&e.name2?w.join(e.path2,e.name2):null,n=this.pathToPosix(w.join(".",e.relativePath,(e.name1||e.name2)??""));if("left"===e.state&&o)return this.diffFileTemplate(`<span class="removed">Removed ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===e.state&&t)return this.diffFileTemplate(`<span class="added">Added ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===e.state&&o&&t){const i=this.pathToPosix(w.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(w.join(".",e.relativePath,e.name2??"")),s=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${r}</span></span\n >`:n;return this.diffFileTemplate(s,await p.isBinaryFile(o)||await p.isBinaryFile(t)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(v.readFileSync(o,"utf-8"),v.readFileSync(t,"utf-8"))))}return""}async generateChangelog(){this.logger.info(a.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),o=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(a.colors.green("Writing changelog file"));const t=this.changelogTemplate.split("%FILES%");t.splice(1,0,o);const n=t.join("");v.writeFileSync(w.join(this.destinationPath,this.changelogFilename),n),this.logger.info(a.colors.green(`Changelog file written to ${w.join(this.destinationPath,this.changelogFilename)}`))}}class j{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await $({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}const A=i.cac("pp-dev");function I(e,o,t){const i=[...s.PP_DEV_CONFIG_NAMES,...s.PP_WATCH_CONFIG_NAMES,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"].map(o=>w.join(e,o)),r=n.watch(i,{ignored:e=>{const o=w.basename(e);return/(^|[\/\\])\../.test(e)&&!o.startsWith(".env")&&!o.startsWith(".pp-dev")&&!o.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let l=null;return r.on("change",n=>{t(a.colors.blue(`šŸ”§ Config file changed: ${w.relative(e,n)}`)),l&&clearTimeout(l),l=setTimeout(async()=>{try{t(a.colors.yellow("šŸ”„ Restarting dev server due to config change...")),await o()}catch(e){t(a.colors.red(`āŒ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{t(a.colors.red(`āŒ Config watcher error: ${e}`))}),{watcher:r,restartCallback:o,logger:t}}function D(e){e.watcher&&e.watcher.close()}let k=global.__pp_dev_profile_session,_=0;const N=e=>{if(k)return new Promise((o,t)=>{k.post("Profiler.stop",(n,{profile:i})=>{if(n)t(n);else{const t=w.resolve(`./pp-dev-profile-${_++}.cpuprofile`);v.writeFileSync(t,JSON.stringify(i)),e(a.colors.yellow(`CPU profile written to ${a.colors.white(a.colors.dim(t))}`)),k=void 0,o()}})})},R=e=>{for(const[o,t]of Object.entries(e))Array.isArray(t)&&(e[o]=t[t.length-1])};function q(e){const o={...e};return delete o["--"],delete o.c,delete o.config,delete o.base,delete o.l,delete o.logLevel,delete o.clearScreen,delete o.d,delete o.debug,delete o.f,delete o.filter,delete o.m,delete o.mode,o}A.option("-c, --config <file>","[string] use specified config file").option("--base <path>","[string] public base path (default: /)").option("-l, --logLevel <level>","[string] info | warn | error | silent").option("--clearScreen","[boolean] allow/disable clear screen when logging").option("-d, --debug [feat]","[string | boolean] show debug logs").option("-f, --filter <filter>","[string] filter debug logs").option("-m, --mode <mode>","[string] set env mode"),A.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{R(o);let n=null,i=null,l=!1;const c=e?w.resolve(process.cwd(),e):process.cwd(),d=a.createLogger(o.logLevel),p=async()=>{if(!l){l=!0;try{n&&(d.info(a.colors.yellow("šŸ›‘ Stopping existing dev server...")),await n.close(),n=null);const{clearConfigCache:f}=await Promise.resolve().then(()=>require("./index-Bu8AM2lb.js")).then(e=>e.config);f();const{createServer:h}=await import("vite"),g=await r.loadConfigFromFile({mode:o.mode||"development",command:"serve"},o.config,e,o.logLevel);let u=await s.getViteConfig();const m=r.loadEnv(o.mode||"development",e??process.cwd(),"");if(m&&Object.keys(m).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=m[e])}),g){const{plugins:e,...o}=g.config;u=r.mergeConfig(u,o)}if(n=await h(r.mergeConfig(u,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},server:q(o),customLogger:d},!0)),!n.config.base||"/"===n.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!n.httpServer)throw new Error("HTTP server not available");await n.listen();const b=global.__pp_dev_start_time??!1,w=b?a.colors.dim(`ready in ${a.colors.reset(a.colors.bold(Math.ceil(t.performance.now()-b)))} ms`):"";d.info(`\n ${a.colors.green(`${a.colors.bold("PP-DEV")} v${s.VERSION}`)} ${w}\n`),n.printUrls(),function(e,o){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=o;const t=a.createLogger();o.print&&t.info(a.colors.dim(a.colors.green(" āžœ"))+a.colors.dim(" press ")+a.colors.bold("h")+a.colors.dim(" to show help"));const n=(o.customShortcuts??[]).filter(S).concat(F);let i=!1;const r=async o=>{if(""===o||""===o)return void await e.close().finally(()=>process.exit(1));if(i)return;"h"===o&&t.info(["",a.colors.bold(" Shortcuts"),...n.map(e=>a.colors.dim(" press ")+a.colors.bold(e.key)+a.colors.dim(` to ${e.description}`))].join("\n"));const r=n.find(e=>e.key===o);r&&(i=!0,await r.action(e),i=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume(),e.httpServer.on("close",()=>{process.stdin.off("data",r).pause()})}(n,{print:!0,customShortcuts:[...k?[{key:"p",description:"start/stop the profiler",async action(e){if(k)await N(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(o=>{k=new e.Session,k.connect(),k.post("Profiler.enable",()=>{k?.post("Profiler.start",()=>{d.info("Profiler started"),o()})})})}}}]:[],{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]}),i||(i=I(c,p,d.info),d.info(a.colors.blue("šŸ”§ Config file watcher started"))),l=!1}catch(e){l=!1,d.error(a.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),N(d.info),process.exit(1)}}},f=async e=>{d.info(a.colors.yellow(`\nšŸ›‘ Received ${e}, shutting down gracefully...`));try{i&&(D(i),i=null),n&&(await n.close(),n=null),N(d.info),d.info(a.colors.green("āœ… Graceful shutdown completed")),process.exit(0)}catch(e){d.error(a.colors.red(`āŒ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),process.on("uncaughtException",e=>{d.error(a.colors.red(`āŒ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,o)=>{d.error(a.colors.red(`āŒ Unhandled Rejection at: ${o}, reason: ${e}`)),f("unhandledRejection")}),await p()}),A.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{R(o);let t=null,n=null,i=null,c=!1;const d=a.createLogger(),p=async()=>{if(!c){c=!0;try{const{next:h,constants:g}=await s.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:u}=g;n&&(d.info(a.colors.yellow("šŸ›‘ Stopping existing Next.js server...")),await new Promise(e=>{n.close(()=>{n=null,e()})})),t&&"function"==typeof t.close&&(await t.close(),t=null);const{clearConfigCache:m}=await Promise.resolve().then(()=>require("./index-Bu8AM2lb.js")).then(e=>e.config);m();const{join:b,basename:w}=await import("path"),{createServer:v}=await import("http"),y=await import("next/dist/server/config.js"),x=y.default.default||y["module.exports"].default||y.default,P=q(o),T=r.loadEnv(o.mode||"development",e??process.cwd(),"");T&&Object.keys(T).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=T[e])});const L=e?b(process.cwd(),e):process.cwd();d.info(L);const $=await x(u,L);let S=$?.ppDev||{};if(0===Object.keys(S).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-Bu8AM2lb.js")).then(e=>e.config),o=await e();Object.keys(o).length>0?(S=o,d.info(a.colors.blue("šŸ”§ Loaded pp-dev config from standalone config file"))):d.info(a.colors.yellow("āš ļø No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){d.info(a.colors.yellow("āš ļø Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else d.info(a.colors.blue("šŸ”§ Loaded pp-dev config from Next.js config"));const{backendBaseURL:F=process.env.MI_BACKEND_URL||"http://localhost:8080",appId:C,portalPageId:E,templateLess:j=!0,v7Features:A=!0,disableSSLValidation:k=!1,enableProxyCache:_=!0,proxyCacheTTL:N=6e5,personalAccessToken:R=process.env.MI_ACCESS_TOKEN,miHudLess:M=!1}=S,z=C??E??(process.env.MI_APP_ID&&parseInt(process.env.MI_APP_ID,10)||void 0)??(process.env.MI_PORTAL_PAGE_ID&&parseInt(process.env.MI_PORTAL_PAGE_ID,10)||void 0)??1;let H=null;if(!H)try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-Bu8AM2lb.js")).then(e=>e.config);H=e().name}catch(e){H=w(L)}const G="/p",O="/pl",U=$?.basePath;let W="";if(U?W=U:(W=j?G:A?O:"/pt",W+=`/${H}`),t=h({dev:!0,hostname:P.host||"localhost",port:P.port,dir:L,conf:{...$,basePath:W,assetPrefix:`${j?G:"/pt"}/${H}`}}),await t.prepare(),W.endsWith("/")||(W+="/"),"/"===W)throw new Error('basePath cannot be equal to "/" or equal to empty string');d.info(a.colors.green("āœ… Next.js app prepared successfully")),d.info(a.colors.blue(`šŸ”§ pp-dev plugin configured for template: ${H}`)),d.info(a.colors.blue(`šŸ”§ Base path configured: ${W}`)),F&&(d.info(a.colors.blue(`🌐 Backend URL: ${F}`)),d.info(a.colors.blue(`šŸ†” Custom App ID: ${z}`)));const V=t.getRequestHandler(),B="number"==typeof P.port?P.port:3e3,Z="string"==typeof P.host?P.host||"0.0.0.0":"localhost",K=new Set;n=v(async(e,o)=>{try{const t=e.url||"/",n=t.split("?")[0];let i=l.parse(t,!0);if(J.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(Q.length>0){let c=0;const d=()=>{if(c>=Q.length)return void r();const t=Q[c];c++,t(e,o,d)};return void d()}return void r()}let s=0;const a=()=>{if(s>=J.length)return void r();const t=J[s];s++,t(e,o,a)};return void a()}async function r(){if(n.startsWith(W))i=l.parse(t,!0);else{if(n===W.replace(/\/$/,"")){const e=t.replace(n,W);return o.writeHead(302,{Location:e}),void o.end()}if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_"));else if("/"===n)return o.writeHead(302,{Location:W}),void o.end()}await V(e,o,i)}r()}catch(p){console.error("[DEBUG] Error:",p),o.statusCode=500,o.end("Internal Server Error")}});let Y=null,J=[],Q=[];if(F){const e=new URL(F).host,o={headers:{host:e,referer:F,origin:F.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},portalPageId:z,appId:z,templateLess:j,disableSSLValidation:k,v7Features:A,personalAccessToken:R??process.env.MI_ACCESS_TOKEN};Y=new a.MiAPI(F,o);const t=a.initPPRedirect(W,H),n=(e,o,n)=>{t(e,o,n)};if(Q.push(n),J.push(n),_){let e=+N;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const o={devServer:{middlewares:{use:e=>e},config:{logger:console}},ttl:e},t=a.initProxyCache(o),n=(e,o,n)=>{t(e,o,n)};J.push(n),d.info(a.colors.blue(`šŸ”§ Proxy cache middleware added with TTL: ${e}ms`))}const i=W.endsWith("/")?W.substring(0,W.length-1):W,r={middlewares:{use:e=>e},config:{logger:console}},s=a.initProxy({devServer:r,baseURL:F,proxyIgnore:["/@vite","/@metricinsights","/@",i,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:k,miAPI:Y}),l=(e,o,t)=>{s(e,o,t)};J.push(l);const c=new RegExp(`^((${f=W,f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),p=a.initLoadPPData(c,Y,Object.assign({base:W},o)),h=(e,o,t)=>{p(e,o,t)};J.push(h);const g=a.internalServer,u=(e,o,t)=>{if(e.url?.startsWith("/@api/")){return void g(e,o,()=>{})}t()};Q.push(u),J.push(u);const m=a.initRewriteResponse(e=>{const o=e.split("?")[0];return o.startsWith(W)&&!o.includes("/_next/")},(o,t)=>Buffer.from(a.urlReplacer(e,t.headers.host??"",Y.buildPage(o,M)))),b=(e,o,t)=>{m(e,o,t)};J.push(b),d.info(a.colors.blue(`šŸ”§ ${J.length} pp-dev middlewares initialized`)),d.info(a.colors.blue(`šŸ”§ ${Q.length} essential middlewares for internal routes`)),d.info(a.colors.blue(`šŸ”§ MiAPI initialized for backend: ${F}`)),d.info(a.colors.blue(`šŸ”§ Custom App ID: ${z}`))}n.listen(B,Z,()=>{d.info(a.colors.green(`āœ… pp-dev Next.js server running at http://${Z}:${B}`)),d.info(a.colors.blue(`šŸ“± Next.js app accessible at http://${Z}:${B}${W}`)),d.info(a.colors.blue("šŸ”§ Base path handling active")),i||(i=I(L,p,d.info),d.info(a.colors.blue("šŸ”§ Config file watcher started"))),n.on("connection",e=>{K.add(e),e.on("close",()=>K.delete(e))});const e=async e=>{d.info(a.colors.yellow(`\nšŸ›‘ Received ${e}, shutting down gracefully...`));const o=setTimeout(()=>{d.info(a.colors.yellow("ā° Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{i&&(D(i),i=null);for(const e of Array.from(K))e.destroy();K.clear(),await new Promise(e=>{n.close(()=>{d.info(a.colors.yellow("šŸ›‘ HTTP server closed")),e()})}),t&&"function"==typeof t.close&&(await t.close(),d.info(a.colors.yellow("šŸ›‘ Next.js app closed"))),clearTimeout(o),d.info(a.colors.green("āœ… Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(o),d.error(a.colors.red(`āŒ Error during graceful shutdown: ${e}`)),process.exit(1)}};let o=process;if("function"!=typeof process.on){const e=globalThis.process||global.process;e&&"function"==typeof e.on&&(o=e,d.info(a.colors.green("āœ… Using global process object for event handlers")))}if("function"==typeof o.on)try{o.on("SIGINT",()=>e("SIGINT")),o.on("SIGTERM",()=>e("SIGTERM")),o.on("uncaughtException",o=>{d.error(a.colors.red(`āŒ Uncaught Exception: ${o}`)),e("uncaughtException")}),o.on("unhandledRejection",(o,t)=>{d.error(a.colors.red(`āŒ Unhandled Rejection at: ${t}, reason: ${o}`)),e("unhandledRejection")}),d.info(a.colors.green("āœ… Process event handlers registered successfully"))}catch(e){d.warn(a.colors.yellow(`āš ļø Failed to register process event handlers: ${e}`))}else d.warn(a.colors.yellow("āš ļø process.on is not available, graceful shutdown handlers will not be registered")),d.info(a.colors.blue("šŸ’” This might be due to bundling or environment constraints"))}),c=!1}catch(e){c=!1,d.error(a.colors.red(`āŒ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(d.error(a.colors.red("āŒ Next.js Peer Dependency Error:")),d.error(a.colors.red(e.message)),d.error(a.colors.yellow("\nšŸ’” To fix this issue:")),d.error(a.colors.blue(" 1. Install Next.js in your project:")),d.error(a.colors.white(" npm install next@^16")),d.error(a.colors.blue(" 2. Or use yarn:")),d.error(a.colors.white(" yarn add next@^16")),d.error(a.colors.blue(" 3. Or use pnpm:")),d.error(a.colors.white(" pnpm add next@^16")),d.error(a.colors.yellow("\nšŸ“– For more information, see:")),d.error(a.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var f}},f=async e=>{d.info(a.colors.yellow(`\nšŸ›‘ Received ${e}, shutting down gracefully...`));try{i&&(D(i),i=null),n&&await new Promise(e=>{n.close(()=>{n=null,e()})}),t&&"function"==typeof t.close&&(await t.close(),t=null),d.info(a.colors.green("āœ… Graceful shutdown completed")),process.exit(0)}catch(e){d.error(a.colors.red(`āŒ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),process.on("uncaughtException",e=>{d.error(a.colors.red(`āŒ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,o)=>{d.error(a.colors.red(`āŒ Unhandled Rejection at: ${o}, reason: ${e}`)),f("unhandledRejection")}),await p()}),A.command("build [root]","build for production").option("--target <target>","[string] transpile target (default: 'modules')").option("--outDir <dir>","[string] output directory (default: dist)").option("--assetsDir <dir>","[string] directory under outDir to place assets in (default: assets)").option("--assetsInlineLimit <number>","[number] static asset base64 inline threshold in bytes (default: 4096)").option("--ssr [entry]","[string] build specified entry for server-side rendering").option("--sourcemap [output]",'[boolean | "inline" | "hidden"] output source maps for build (default: false)').option("--minify [minifier]",'[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)').option("--manifest [name]","[boolean | string] emit build manifest json").option("--ssrManifest [name]","[boolean | string] emit ssr manifest json").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle (experimental)").option("--emptyOutDir","[boolean] force empty outDir when it's outside of root").option("-w, --watch","[boolean] rebuilds when modules have changed on disk").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").action(async(e,o)=>{R(o);const t=q(o);try{const n=await r.loadConfigFromFile({mode:o.mode||"production",command:"build"},o.config,e,o.logLevel);let i=await s.getViteConfig();if(n){const{plugins:e,...o}=n.config;i=r.mergeConfig(i,o)}const l=r.mergeConfig(i,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},build:t},!0);if(await r.build(l),t.changelog){const n=e||process.cwd(),i=l.build?.outDir||"dist";let r="";if("string"==typeof t.changelog)r=w.resolve(n,t.changelog);else{const e=w.resolve(n,l.ppDevConfig?.syncBackupsDir||"backups");if(!v.existsSync(e))return void a.createLogger(o.logLevel).warn(a.colors.yellow("backups directory not found, skipping changelog generation"));const t=v.readdirSync(e,{withFileTypes:!0});if(!t.length)return void a.createLogger(o.logLevel).warn(a.colors.yellow("no backups found, skipping changelog generation"));const i=t.filter(e=>e.isFile()&&e.name.endsWith(".zip")).reduce((o,t)=>v.statSync(w.resolve(e,o.name)).mtimeMs>v.statSync(w.resolve(e,t.name)).mtimeMs?o:t,t[0]).name;r=w.resolve(e,i)}const s=w.resolve(n,i);let c="dist-zip";l.ppDevConfig&&(!1===l.ppDevConfig.distZip?c=l.build?.outDir||"dist":"object"==typeof l.ppDevConfig.distZip&&"string"==typeof l.ppDevConfig.distZip.outDir&&(c=l.ppDevConfig.distZip.outDir));const d=new E({oldAssetsPath:r,newAssetsPath:s,destinationPath:w.resolve(n,c)});await d.generateChangelog()}}catch(e){a.createLogger(o.logLevel).error(a.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{N(e=>a.createLogger(o.logLevel).info(e))}}),A.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action(async(e,o,t)=>{R(t);const{oldAssetsPath:n=e,newAssetsPath:i=o,destination:r=".",filename:s="CHANGELOG.html",logLevel:l}=t,c=process.cwd();n&&i||(a.createLogger(l).error(a.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=w.resolve(c,n),p=w.resolve(c,i),f=w.resolve(c,r),h=new E({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:s});await h.generateChangelog()}),A.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(e,o,t)=>{R(t);const{source:n=e,destination:i=o,fontName:r="icon-font"}=t,s=process.cwd(),l=w.resolve(s,n),c=w.resolve(s,i),d=new j({sourceDir:l,outputDir:c,fontName:r}),p=a.createLogger(t.logLevel);p.info(`Generating icon font from SVG files in ${a.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${a.colors.dim(c)}`)}),A.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{R(o);try{const t=await r.loadConfigFromFile({mode:o.mode||"production",command:"build"},o.config,e,o.logLevel);let n=await s.getViteConfig();if(t){const{plugins:e,...o}=t.config;n=r.mergeConfig(n,o)}const i=await r.resolveConfig(r.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode}),"serve");await r.optimizeDeps(i,o.force,!0)}catch(e){a.createLogger(o.logLevel).error(a.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),A.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,o)=>{R(o);try{const t=await r.loadConfigFromFile({mode:o.mode||"production",command:"build"},o.config,e,o.logLevel);let n=await s.getViteConfig();if(t){const{plugins:e,...o}=t.config;n=r.mergeConfig(n,o)}(await r.preview(r.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode,build:{outDir:o.outDir},preview:{port:o.port,strictPort:o.strictPort,host:o.host,https:o.https,open:o.open}}))).printUrls()}catch(e){a.createLogger(o.logLevel).error(a.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{N(e=>a.createLogger(o.logLevel).info(e))}}),A.help(),A.version(s.VERSION),A.parse(),exports.stopProfiler=N;
2
2
  //# sourceMappingURL=cli.js.map
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./plugin-nVTTdbnD.js"),t=require("fs"),n=require("path"),i=require("url"),s=require("vite"),a=require("ejs");var r="undefined"!=typeof document?document.currentScript:null;const o=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function c(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const n in e)t[n]=e[n];return t.default=e,Object.freeze(t)}const l=c(t),p=c(n),u=o(n),f=o(a),d=n.resolve("undefined"!=typeof __filename&&__filename||i.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-4BMbdu0V.js",document.baseURI).href),"../../.."),m=n.resolve("undefined"!=typeof __filename&&__filename||i.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-4BMbdu0V.js",document.baseURI).href),"../.."),h=t.existsSync(n.resolve(d,"package.json"))?d:m,g=n.resolve(h,"dist/client/client.js"),{version:j,name:y}=JSON.parse(t.readFileSync(n.resolve(h,"package.json")).toString()),v=j,w=y,x=[".pp-watch.config.js",".pp-watch.config.ts",".pp-watch.config.json"],_=[".pp-dev.config.js",".pp-dev.config.cjs",".pp-dev.config.mjs",".pp-dev.config.ts",".pp-dev.config.cts",".pp-dev.config.mts",".pp-dev.config.json","pp-dev.config.js","pp-dev.config.cjs","pp-dev.config.mjs","pp-dev.config.ts","pp-dev.config.cts","pp-dev.config.mts","pp-dev.config.json"];const S=new class{cache;_maxSize;constructor(e=10){this._maxSize=e,this.cache=new Map}get maxSize(){return this._maxSize}set maxSize(e){this._maxSize=e}get(e){if(this.cache.has(e)){const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this._maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}clear(){this.cache.clear()}has(e){return this.cache.has(e)}}(5),R=new Map;let b;try{b="undefined"!=typeof __filename&&__filename?p.resolve(p.dirname(__filename),".."):void 0!=={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-4BMbdu0V.js",document.baseURI).href}&&("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-4BMbdu0V.js",document.baseURI).href,1)&&("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-4BMbdu0V.js",document.baseURI).href)?p.resolve(i.fileURLToPath(new URL(".","undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-4BMbdu0V.js",document.baseURI).href)),".."):process.cwd()}catch{b=process.cwd()}const P=`/${w}/client`,$=`/${P}`,C=new RegExp(`^\\/?${w}\\/client\\/(.*)$`);const U={templateCompilations:0,cacheHits:0,totalRequests:0};function T(e){let t="",n=!1,i=null;return{name:"pp-dev:client",apply:"serve",config:e=>(e.optimizeDeps?.exclude?.push(`${w}/client`),e),resolveId(e){if(C.test(e))return{id:s.normalizePath(p.join(h,"dist/client",e.replace(C,"$1")))}},transformIndexHtml:async(e,s)=>{U.totalRequests++;const a=s.server?.config.base||"";a!==t&&(t=a,n=!0,i=null),i&&!n||(S.has(t)?(i=S.get(t),U.cacheHits++):(i=function(e,t=!0){const n=e;if(t&&S.has(n))return S.get(n);const i=p.resolve(b,"client","index.html");let s;R.has(i)?s=R.get(i):(s=l.readFileSync(i,{encoding:"utf8"}),R.set(i,s));const a=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=f.compile(s.replace(new RegExp(a,"g"),p.posix.join(e,P)),{openDelimiter:"{",closeDelimiter:"}",async:!0,cache:!0,filename:i,rmWhitespace:!0,compileDebug:!1});return t&&S.set(n,r),r}(t,true),U.templateCompilations++),n=!1);const r=function(e){return{css:p.posix.join(e,w,"client/client.css"),js:p.posix.join(e,w,"client/client.js")}}(t),o={html:e,tags:[{tag:"link",injectTo:"head",attrs:{rel:"stylesheet",href:r.css}}]},{backendBaseURL:c,templateLess:u,portalPageId:d,canSync:m=!0}=s.server?.config.clientInjectionPlugin||{},h={PACKAGE_NAME:w,VERSION:v,backendBaseURL:c,templateLess:u,portalPageId:d,canSync:m};return o.tags.push({tag:"div",injectTo:"body-prepend",children:await i(h)}),o.tags.push({tag:"script",injectTo:"body-prepend",attrs:{src:r.js,type:"module"}}),o},configureServer(e){const t=s.normalizePath(p.resolve(e.config.root,p.dirname(g)));e.config.server?.fs?.allow&&e.config.server.fs.allow.push(t),e.middlewares.use("/@api/__pp-dev-metrics",(e,t)=>{t.setHeader("Content-Type","application/json"),t.end(JSON.stringify(U,null,2))})},closeBundle(){S.clear(),R.clear()}}}const I=(e,t)=>` * ${t}`;function L(e){return`/*!\n${"***** DO NOT EDIT THIS CODE! *****\n***** ------- *****".replace(/^(.*)$/gm,I)}\n */`}async function N(){try{const[e,t]=await Promise.all([import("next"),import("next/constants.js")]);return{next:e.default,constants:t}}catch(e){throw new Error(`Next.js is required but not available. Please install Next.js as a dependency:\nnpm install next@^15\n\nThis package requires Next.js >=15 <17 as a peer dependency.\n\nError: ${e}`)}}const D=new Map,E=3e4;let F=null;function O(){const e=Date.now();if(F&&e-F.timestamp<6e4)return F.data;const n=process.cwd();try{const i=JSON.parse(t.readFileSync(u.resolve(n,"package.json"),{encoding:"utf-8",flag:"r"}));return F={data:i,timestamp:e},i}catch{const t={};return F={data:t,timestamp:e},t}}let z=null;async function k(e){const n=process.cwd(),s=`ts:${e}`,a=D.get(s);if(a&&Date.now()-a.timestamp<E)return a.data;let r=!1;if(/\.m[jt]s$/.test(e))r=!0;else if(/\.c[jt]s$/.test(e))r=!1;else{const e=O();r=!!e&&"module"===e.type}const o=await async function(){return z||(z=await import("esbuild")),z}(),c=await o.build({absWorkingDir:n,entryPoints:[e],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,format:r?"esm":"cjs",mainFields:["main"],sourcemap:"inline",metafile:!0}),{text:l}=c.outputFiles[0],p=`${`pp-config.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.js`,f=i.pathToFileURL(u.resolve(n,p)).toString();t.writeFileSync(p,l);let d={};try{const t=(await import(f)).default;d=t?.default||t,D.set(s,{data:d,timestamp:Date.now(),filePath:e})}finally{t.existsSync(p)&&t.unlink(p,()=>{})}return d}async function q(e){const t=`js:${e}`,n=D.get(t);if(n&&Date.now()-n.timestamp<E)return n.data;const s=(await import(i.pathToFileURL(e).toString())).default;return D.set(t,{data:s,timestamp:Date.now(),filePath:e}),s}async function M(e){const n=`json:${e}`,i=D.get(n);if(i&&Date.now()-i.timestamp<E)return i.data;const s=JSON.parse(t.readFileSync(e,{encoding:"utf-8"}));return D.set(n,{data:s,timestamp:Date.now(),filePath:e}),s}let V=null;async function A(e,t){for(const n of t)if(e.includes(n)){if(/\.[cm]?ts$/i.test(n))return await k(n);if(/\.[cm]?js$/i.test(n))return await q(u.resolve(".",n));if(n.endsWith(".json"))return await M(u.resolve(".",n))}return null}function H(){return O()}async function B(){const e=function(){const e=Date.now();if(V&&e-V.timestamp<1e4)return V.files;const n=/\.config\.(([cm]?ts)|([cm]?js)|(json))$/,i=process.cwd(),s=t.readdirSync(i,{withFileTypes:!0}).filter(e=>e.isFile()&&n.test(e.name)).map(e=>e.name);return V={files:s,timestamp:e},s}();let n={},i=!1;const s=await A(e,_);if(s&&(n=s,i=!0),e.length&&!i){const t=await A(e,x);t&&(n={backendBaseURL:t.baseURL,portalPageId:t.portalPageId},i=!0)}const a=O();return i||"object"!=typeof a["pp-dev"]||(n=a["pp-dev"]),n}const J=Object.freeze({__proto__:null,clearConfigCache:function(){D.clear(),F=null,V=null},getConfig:B,getConfigCacheStats:function(){return{configEntries:D.size,packageJsonCached:!!F,dirContentCached:!!V}},getPkg:H}),W="/p",G="/pt";function K(e){return e?.ppDev||{}}function Z(e,t,n){return Object.assign({},e,t,n)}exports.PP_DEV_CONFIG_NAMES=_,exports.PP_WATCH_CONFIG_NAMES=x,exports.VERSION=v,exports.config=J,exports.getNextVersion=async function(){try{return(await import("next/package.json")).version}catch{return null}},exports.getPPDevConfigFromNextConfig=K,exports.getViteConfig=async function(){const t=H().name,n=await B(),i=e.normalizeVitePPDevConfig(Object.assign(n,{templateName:t})),{default:s}=await Promise.resolve().then(()=>require("./plugin.js")),a=[s(i),T()],{outDir:r,distZip:o,imageOptimizer:c,templateLess:l,integrateMiTopBar:p}=i;if(p&&a.push(function(e){return{name:"mi-topbar-plugin",transformIndexHtml(){const t=[];return(!0===e||"object"==typeof e&&!0===e.addRootElement)&&t.push({tag:"div",injectTo:"body-prepend",attrs:{id:"mi-react-root"}}),(!0===e||"object"==typeof e&&!0===e.addSharedComponentsScripts)&&t.push({tag:"script",injectTo:"head-prepend",attrs:{src:"/auth/info.js"}},{tag:"script",injectTo:"head-prepend",attrs:{src:"/js/main.js",defer:"defer"}},{tag:"link",injectTo:"head-prepend",attrs:{href:"/css/main.css",rel:"stylesheet"}}),t}}}(p)),c){const{ViteImageOptimizer:e}=await import("vite-plugin-image-optimizer");a.push(e("object"==typeof c?c:void 0))}if(o){const{default:e}=await import("vite-plugin-zip-pack");a.push({...e("object"==typeof o?o:{outFileName:`${t}.zip`}),enforce:"post"})}return{base:l?`${W}/${t}`:`${G}/${t}`,server:{port:3e3},build:{minify:!1,assetsInlineLimit:4096,rollupOptions:{output:{banner:L}},outDir:r},css:{modules:{localsConvention:"dashes"},scss:{api:"modern"}},ppDevConfig:i,plugins:a}},exports.isNextAvailable=async function(){try{return await import("next"),!0}catch(e){return!1}},exports.safeNextImport=N,exports.withPPDev=function(e,t){return async(n,i={})=>{try{const{constants:s}=await N(),{PHASE_DEVELOPMENT_SERVER:a}=s,r=await B(),o=H().name,c="function"==typeof e?await e(n,i):e,l=K(c),p=Object.assign({},r,l,t??{}),u=n===a,f=function(e,t,n,i){return n?i?t?`${W}/${e}`:`/pl/${e}`:t?`${W}/${e}`:`${G}/${e}`:`/p/${e}`}(o,p.templateLess??!1,u,p.v7Features??!1),d={basePath:f,trailingSlash:!!u||void 0};return p.templateLess||(d.assetPrefix=`${G}/${o}`),Z(d,c)}catch(t){console.error("Error in withPPDev:",t),console.warn("Falling back to original Next.js configuration");try{return"function"==typeof e?await e(n,i):e}catch(e){return console.error("Error in fallback configuration:",e),{}}}}};
2
- //# sourceMappingURL=index-4BMbdu0V.js.map
1
+ "use strict";const e=require("./plugin-D-TIdILy.js"),t=require("fs"),n=require("path"),i=require("url"),s=require("vite"),a=require("ejs");var r="undefined"!=typeof document?document.currentScript:null;const o=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function c(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const n in e)t[n]=e[n];return t.default=e,Object.freeze(t)}const l=c(t),p=c(n),u=o(n),f=o(a),d=n.resolve("undefined"!=typeof __filename&&__filename||i.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-Bu8AM2lb.js",document.baseURI).href),"../../.."),m=n.resolve("undefined"!=typeof __filename&&__filename||i.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-Bu8AM2lb.js",document.baseURI).href),"../.."),h=t.existsSync(n.resolve(d,"package.json"))?d:m,g=n.resolve(h,"dist/client/client.js"),{version:j,name:v}=JSON.parse(t.readFileSync(n.resolve(h,"package.json")).toString()),y=j,w=v,x=[".pp-watch.config.js",".pp-watch.config.ts",".pp-watch.config.json"],_=[".pp-dev.config.js",".pp-dev.config.cjs",".pp-dev.config.mjs",".pp-dev.config.ts",".pp-dev.config.cts",".pp-dev.config.mts",".pp-dev.config.json","pp-dev.config.js","pp-dev.config.cjs","pp-dev.config.mjs","pp-dev.config.ts","pp-dev.config.cts","pp-dev.config.mts","pp-dev.config.json"];const P=new class{cache;_maxSize;constructor(e=10){this._maxSize=e,this.cache=new Map}get maxSize(){return this._maxSize}set maxSize(e){this._maxSize=e}get(e){if(this.cache.has(e)){const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this._maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}clear(){this.cache.clear()}has(e){return this.cache.has(e)}}(5),S=new Map;let b;try{b="undefined"!=typeof __filename&&__filename?p.resolve(p.dirname(__filename),".."):void 0!=={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-Bu8AM2lb.js",document.baseURI).href}&&("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-Bu8AM2lb.js",document.baseURI).href,1)&&("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-Bu8AM2lb.js",document.baseURI).href)?p.resolve(i.fileURLToPath(new URL(".","undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index-Bu8AM2lb.js",document.baseURI).href)),".."):process.cwd()}catch{b=process.cwd()}const R=`/${w}/client`,$=`/${R}`,C=new RegExp(`^\\/?${w}\\/client\\/(.*)$`);const U={templateCompilations:0,cacheHits:0,totalRequests:0};function T(e){let t="",n=!1,i=null;return{name:"pp-dev:client",apply:"serve",config:e=>(e.optimizeDeps?.exclude?.push(`${w}/client`),e),resolveId(e){if(C.test(e))return{id:s.normalizePath(p.join(h,"dist/client",e.replace(C,"$1")))}},transformIndexHtml:async(e,s)=>{U.totalRequests++;const a=s.server?.config.base||"";a!==t&&(t=a,n=!0,i=null),i&&!n||(P.has(t)?(i=P.get(t),U.cacheHits++):(i=function(e,t=!0){const n=e;if(t&&P.has(n))return P.get(n);const i=p.resolve(b,"client","index.html");let s;S.has(i)?s=S.get(i):(s=l.readFileSync(i,{encoding:"utf8"}),S.set(i,s));const a=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=f.compile(s.replace(new RegExp(a,"g"),p.posix.join(e,R)),{openDelimiter:"{",closeDelimiter:"}",async:!0,cache:!0,filename:i,rmWhitespace:!0,compileDebug:!1});return t&&P.set(n,r),r}(t,true),U.templateCompilations++),n=!1);const r=function(e){return{css:p.posix.join(e,w,"client/client.css"),js:p.posix.join(e,w,"client/client.js")}}(t),o={html:e,tags:[{tag:"link",injectTo:"head",attrs:{rel:"stylesheet",href:r.css}}]},{backendBaseURL:c,templateLess:u,portalPageId:d,canSync:m=!0}=s.server?.config.clientInjectionPlugin||{},h={PACKAGE_NAME:w,VERSION:y,backendBaseURL:c,templateLess:u,portalPageId:d,canSync:m};return o.tags.push({tag:"div",injectTo:"body-prepend",children:await i(h)}),o.tags.push({tag:"script",injectTo:"body-prepend",attrs:{src:r.js,type:"module"}}),o},configureServer(e){const t=s.normalizePath(p.resolve(e.config.root,p.dirname(g)));e.config.server?.fs?.allow&&e.config.server.fs.allow.push(t),e.middlewares.use("/@api/__pp-dev-metrics",(e,t)=>{t.setHeader("Content-Type","application/json"),t.end(JSON.stringify(U,null,2))})},closeBundle(){P.clear(),S.clear()}}}const I=(e,t)=>` * ${t}`;function L(e){return`/*!\n${"***** DO NOT EDIT THIS CODE! *****\n***** ------- *****".replace(/^(.*)$/gm,I)}\n */`}async function N(){try{const[e,t]=await Promise.all([import("next"),import("next/constants.js")]);return{next:e.default,constants:t}}catch(e){throw new Error(`Next.js is required but not available. Please install Next.js as a dependency:\nnpm install next@^15\n\nThis package requires Next.js >=15 <17 as a peer dependency.\n\nError: ${e}`)}}const D=new Map,E=3e4;let F=null;function O(){const e=Date.now();if(F&&e-F.timestamp<6e4)return F.data;const n=process.cwd();try{const i=JSON.parse(t.readFileSync(u.resolve(n,"package.json"),{encoding:"utf-8",flag:"r"}));return F={data:i,timestamp:e},i}catch{const t={};return F={data:t,timestamp:e},t}}let z=null;async function k(e){const n=process.cwd(),s=`ts:${e}`,a=D.get(s);if(a&&Date.now()-a.timestamp<E)return a.data;let r=!1;if(/\.m[jt]s$/.test(e))r=!0;else if(/\.c[jt]s$/.test(e))r=!1;else{const e=O();r=!!e&&"module"===e.type}const o=await async function(){return z||(z=await import("esbuild")),z}(),c=await o.build({absWorkingDir:n,entryPoints:[e],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,format:r?"esm":"cjs",mainFields:["main"],sourcemap:"inline",metafile:!0}),{text:l}=c.outputFiles[0],p=`${`pp-config.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.js`,f=i.pathToFileURL(u.resolve(n,p)).toString();t.writeFileSync(p,l);let d={};try{const t=(await import(f)).default;d=t?.default||t,D.set(s,{data:d,timestamp:Date.now(),filePath:e})}finally{t.existsSync(p)&&t.unlink(p,()=>{})}return d}async function q(e){const t=`js:${e}`,n=D.get(t);if(n&&Date.now()-n.timestamp<E)return n.data;const s=(await import(i.pathToFileURL(e).toString())).default;return D.set(t,{data:s,timestamp:Date.now(),filePath:e}),s}async function V(e){const n=`json:${e}`,i=D.get(n);if(i&&Date.now()-i.timestamp<E)return i.data;const s=JSON.parse(t.readFileSync(e,{encoding:"utf-8"}));return D.set(n,{data:s,timestamp:Date.now(),filePath:e}),s}let M=null;async function A(e,t){for(const n of t)if(e.includes(n)){if(/\.[cm]?ts$/i.test(n))return await k(n);if(/\.[cm]?js$/i.test(n))return await q(u.resolve(".",n));if(n.endsWith(".json"))return await V(u.resolve(".",n))}return null}function H(){return O()}async function B(){const e=function(){const e=Date.now();if(M&&e-M.timestamp<1e4)return M.files;const n=/\.config\.(([cm]?ts)|([cm]?js)|(json))$/,i=process.cwd(),s=t.readdirSync(i,{withFileTypes:!0}).filter(e=>e.isFile()&&n.test(e.name)).map(e=>e.name);return M={files:s,timestamp:e},s}();let n={},i=!1;const s=await A(e,_);if(s&&(n=s,i=!0),e.length&&!i){const t=await A(e,x);t&&(n={backendBaseURL:t.baseURL,portalPageId:t.portalPageId},i=!0)}const a=O();return i||"object"!=typeof a["pp-dev"]||(n=a["pp-dev"]),n}const J=Object.freeze({__proto__:null,clearConfigCache:function(){D.clear(),F=null,M=null},getConfig:B,getConfigCacheStats:function(){return{configEntries:D.size,packageJsonCached:!!F,dirContentCached:!!M}},getPkg:H}),W="/p",G="/pt";function K(e){return e?.ppDev||{}}function Z(e,t,n){return Object.assign({},e,t,n)}exports.PP_DEV_CONFIG_NAMES=_,exports.PP_WATCH_CONFIG_NAMES=x,exports.VERSION=y,exports.config=J,exports.getNextVersion=async function(){try{return(await import("next/package.json")).version}catch{return null}},exports.getPPDevConfigFromNextConfig=K,exports.getViteConfig=async function(){const t=H(),n=t.name,i=await B(),s=e.normalizeVitePPDevConfig(Object.assign(i,{templateName:n})),{default:a}=await Promise.resolve().then(()=>require("./plugin.js")),r=[a(s),T()],{outDir:o,distZip:c,versionPlugin:l,imageOptimizer:p,templateLess:u,integrateMiTopBar:f}=s;if(f&&r.push(function(e){return{name:"mi-topbar-plugin",transformIndexHtml(){const t=[];return(!0===e||"object"==typeof e&&!0===e.addRootElement)&&t.push({tag:"div",injectTo:"body-prepend",attrs:{id:"mi-react-root"}}),(!0===e||"object"==typeof e&&!0===e.addSharedComponentsScripts)&&t.push({tag:"script",injectTo:"head-prepend",attrs:{src:"/auth/info.js"}},{tag:"script",injectTo:"head-prepend",attrs:{src:"/js/main.js",defer:"defer"}},{tag:"link",injectTo:"head-prepend",attrs:{href:"/css/main.css",rel:"stylesheet"}}),t}}}(f)),p){const{ViteImageOptimizer:e}=await import("vite-plugin-image-optimizer");r.push(e("object"==typeof p?p:void 0))}if(l){const{versionPlugin:e}=await Promise.resolve().then(()=>require("./version-plugin-Cj4Pv-pw.js"));r.push(e({outDir:o,packageVersion:t.version??"0.0.0",..."object"==typeof l?l:{}}))}if(c){const{default:e}=await import("vite-plugin-zip-pack");r.push({...e("object"==typeof c?c:{outFileName:`${n}.zip`}),enforce:"post"})}return{base:u?`${W}/${n}`:`${G}/${n}`,server:{port:3e3},build:{minify:!1,assetsInlineLimit:4096,rollupOptions:{output:{banner:L}},outDir:o},css:{modules:{localsConvention:"dashes"}},ppDevConfig:s,plugins:r}},exports.isNextAvailable=async function(){try{return await import("next"),!0}catch(e){return!1}},exports.safeNextImport=N,exports.withPPDev=function(e,t){return async(n,i={})=>{try{const{constants:s}=await N(),{PHASE_DEVELOPMENT_SERVER:a}=s,r=await B(),o=H().name,c="function"==typeof e?await e(n,i):e,l=K(c),p=Object.assign({},r,l,t??{}),u=n===a,f=function(e,t,n,i){return n?i?t?`${W}/${e}`:`/pl/${e}`:t?`${W}/${e}`:`${G}/${e}`:`/p/${e}`}(o,p.templateLess??!1,u,p.v7Features??!1),d={basePath:f,trailingSlash:!!u||void 0};return p.templateLess||(d.assetPrefix=`${G}/${o}`),Z(d,c)}catch(t){console.error("Error in withPPDev:",t),console.warn("Falling back to original Next.js configuration");try{return"function"==typeof e?await e(n,i):e}catch(e){return console.error("Error in fallback configuration:",e),{}}}}};
2
+ //# sourceMappingURL=index-Bu8AM2lb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-Bu8AM2lb.js","sources":["../../../src/constants.ts","../../../src/plugins/client-injection-plugin.ts","../../../src/banner/header.ts","../../../src/lib/next-import.ts","../../../src/config.ts","../../../src/index.ts","../../../src/plugins/mi-topbar-plugin.ts"],"sourcesContent":[null,null,null,null,null,null,null],"names":["afterBundlePath","resolve","__filename","fileURLToPath","document","require","pathToFileURL","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","beforeBundlePath","PP_DEV_PACKAGE_DIR","existsSync","PP_DEV_CLIENT_ENTRY","version","name","JSON","parse","readFileSync","toString","VERSION","PACKAGE_NAME","PP_WATCH_CONFIG_NAMES","PP_DEV_CONFIG_NAMES","templateCache","cache","_maxSize","constructor","maxSize","this","Map","value","get","key","has","delete","set","size","firstKey","keys","next","undefined","clear","fileCache","DIRNAME","path","dirname","url","process","cwd","PACKAGE_IMPORT","CLIENT_PATH","PACKAGE_REGEXP","RegExp","performanceMetrics","templateCompilations","cacheHits","totalRequests","clientInjectionPlugin","opts","base","baseChanged","currentTemplate","apply","config","optimizeDeps","exclude","push","resolveId","source","test","id","normalizePath","join","replace","transformIndexHtml","async","html","ctx","serverBase","server","enableCache","cacheKey","templatePath","templateContent","fs","encoding","escapedClientPath","compiledTemplate","ejs","compile","posix","openDelimiter","closeDelimiter","filename","rmWhitespace","compileDebug","getTemplate","assetPaths","css","js","getAssetPaths","result","tags","tag","injectTo","attrs","rel","backendBaseURL","templateLess","portalPageId","canSync","templateData","children","type","configureServer","clientDir","root","allow","middlewares","use","req","res","setHeader","end","stringify","closeBundle","replacer","substring","$1","header","_chunk","safeNextImport","constants","Promise","all","import","default","error","Error","configCache","CACHE_TTL","packageJsonCache","getPackageJson","now","Date","timestamp","data","flag","empty","esbuildModule","loadTsConfig","filePath","cached","isESM","pkg","esbuild","getEsbuild","build","absWorkingDir","entryPoints","outfile","write","target","platform","bundle","format","mainFields","sourcemap","metafile","text","code","outputFiles","fileNameTmp","Math","random","slice","fileUrl","writeFileSync","conf","unlink","loadJsConfig","loadJSONConfig","dirContentCache","loadConfig","dirFiles","configNames","configName","includes","endsWith","getPkg","getConfig","dirContent","files","endsWithRegExp","readdirSync","withFileTypes","filter","isFile","map","getDirectoryContent","configFound","newConfig","length","watchConfig","baseURL","configEntries","packageJsonCached","dirContentCached","pathPagePrefix","pathTemplatePrefix","getPPDevConfigFromNextConfig","nextConfig","ppDev","mergeConfigs","baseConfig","nextConfiguration","additionalConfig","Object","assign","templateName","ppDevConfig","normalizedPPDevConfig","normalizeVitePPDevConfig","vitePPDev","then","plugins","outDir","distZip","versionPlugin","imageOptimizer","integrateMiTopBar","addRootElement","addSharedComponentsScripts","defer","miTopBarPlugin","ViteImageOptimizer","versionPluginFn","packageVersion","zipPack","outFileName","enforce","port","minify","assetsInlineLimit","rollupOptions","output","banner","modules","localsConvention","nextjsConfig","phase","PHASE_DEVELOPMENT_SERVER","nextConfigPPDev","mergedConfig","isDevelopment","basePath","v7Features","createBasePath","trailingSlash","assetPrefix","console","warn","fallbackError"],"mappings":"ucAIMA,EAAkBC,EAAAA,QAEC,oBAAfC,YAA8BA,YACpCC,gBAAc,oBAAAC,SAAAC,QAAA,OAAAC,cAAAJ,YAAAK,KAAAC,GAAA,WAAAA,EAAAC,QAAAC,eAAAF,EAAAG,KAAA,IAAAC,IAAA,oBAAAR,SAAAS,SAAAN,MAChB,YAGIO,EAAmBb,EAAAA,QAEA,oBAAfC,YAA8BA,YACpCC,gBAAc,oBAAAC,SAAAC,QAAA,OAAAC,cAAAJ,YAAAK,KAAAC,GAAA,WAAAA,EAAAC,QAAAC,eAAAF,EAAAG,KAAA,IAAAC,IAAA,oBAAAR,SAAAS,SAAAN,MAChB,SAGWQ,EAAqBC,EAAAA,WAChCf,UAAQD,EAAiB,iBAEvBA,EACAc,EAESG,EAAsBhB,EAAAA,QACjCc,EACA,0BAGIG,QAAEA,EAAOC,KAAEA,GAASC,KAAKC,MAC7BC,EAAAA,aAAarB,EAAAA,QAAQc,EAAoB,iBAAiBQ,YAG/CC,EAAUN,EACVO,EAAeN,EAEfO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J,QAAS,CAAEC,iBAAkB,WAE/B5B,YAAaC,EACbI,UAEJ,0BF/EOtJ,iBACL,IAGE,aAFM4D,OAAO,SAEN,CACT,CAAE,MAAOE,GAEP,OAAO,CACT,CACF,6CEsKM,SACJgH,EAMA7B,GAEA,OAAOjJ,MACL+K,EACAvC,EAAsC,MAEtC,IACE,MAAM/E,UAAEA,SAAoBD,KACtBwH,yBAAEA,GAA6BvH,EAE/BrE,QAAe+H,IAEf6B,EADM9B,IACa/K,KAGnByM,EACoB,mBAAjBkC,QACGA,EAAaC,EAAOvC,GAC1BsC,EAIAG,EAAkB1C,EAA6BK,GAC/CsC,EAAepC,OAAOC,OAC1B,CAAA,EACA3J,EACA6L,EACAhC,GAAe,IAIXkC,EAAgBJ,IAAUC,EAC1BI,EA5FZ,SACEpC,EACA/G,EACAkJ,EACAE,GAEA,OAAIF,EACEE,EACEpJ,EACK,GAAGoG,KAAkBW,IAErB,OAA8BA,IAGnC/G,EACK,GAAGoG,KAAkBW,IAErB,GAAGV,KAAsBU,IAK/B,MAAMA,GACf,CAqEuBsC,CACftC,EACAkC,EAAajJ,eAAgB,EAC7BkJ,EACAD,EAAaG,aAAc,GAGvB1C,EAAyB,CAC7ByC,WACAG,gBAAeJ,QAAuBtN,GAOxC,OAJKqN,EAAajJ,eAChB0G,EAAW6C,YAAc,GAAGlD,KAAsBU,KAO3CN,EAAaC,EAAYC,EAKpC,CAAE,MAAO9E,GACP2H,QAAQ3H,MAAM,sBAAuBA,GACrC2H,QAAQC,KAAK,kDAGb,IAKE,MAH0B,mBAAjBZ,QACGA,EAAaC,EAAOvC,GAC1BsC,CAER,CAAE,MAAOa,GAGP,OAFAF,QAAQ3H,MAAM,mCAAoC6H,GAE3C,CAAA,CACT,CACF,EAEJ"}
package/dist/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./plugin-nVTTdbnD.js"),r=require("./index-4BMbdu0V.js");require("http-proxy-middleware"),require("vite"),require("picocolors"),require("axios"),require("jsdom"),require("https"),require("memory-cache"),require("path"),require("fs"),require("url"),require("crypto"),require("process"),require("child_process"),require("console"),require("zlib"),require("express"),require("ejs"),exports.AuthProvider=e.AuthProvider,exports.authProvider=e.authProvider,exports.getNextVersion=r.getNextVersion,exports.getPPDevConfigFromNextConfig=r.getPPDevConfigFromNextConfig,exports.getViteConfig=r.getViteConfig,exports.isNextAvailable=r.isNextAvailable,exports.safeNextImport=r.safeNextImport,exports.withPPDev=r.withPPDev;
1
+ "use strict";const e=require("./plugin-D-TIdILy.js"),r=require("./index-Bu8AM2lb.js");require("http-proxy-middleware"),require("vite"),require("picocolors"),require("axios"),require("jsdom"),require("https"),require("memory-cache"),require("path"),require("fs"),require("url"),require("crypto"),require("process"),require("child_process"),require("console"),require("zlib"),require("express"),require("ejs"),exports.AuthProvider=e.AuthProvider,exports.authProvider=e.authProvider,exports.getNextVersion=r.getNextVersion,exports.getPPDevConfigFromNextConfig=r.getPPDevConfigFromNextConfig,exports.getViteConfig=r.getViteConfig,exports.isNextAvailable=r.isNextAvailable,exports.safeNextImport=r.safeNextImport,exports.withPPDev=r.withPPDev;
2
2
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@metricinsights/pp-dev",
3
3
  "type": "commonjs",
4
- "version": "0.15.1-beta.1",
4
+ "version": "0.16.0-beta.1",
5
5
  "description": "Portal Page dev build tool",
6
6
  "bin": {
7
7
  "pp-dev": "bin/pp-dev.js"
@@ -41,9 +41,11 @@
41
41
  },
42
42
  "overrides": {
43
43
  "chokidar": "^5.0.0",
44
+ "file-type": "^21.3.3",
44
45
  "minimatch": "10.2.4",
45
46
  "npm": ">=11.11.0",
46
- "serialize-javascript": ">=7.0.3"
47
+ "serialize-javascript": ">=7.0.3",
48
+ "undici": ">=6.24.0"
47
49
  },
48
50
  "peerDependencies": {
49
51
  "next": ">= 13 < 17"
@@ -56,30 +58,31 @@
56
58
  },
57
59
  "dependencies": {
58
60
  "axios": "^1.13.6",
59
- "cac": "^6.7.14",
61
+ "cac": "^7.0.0",
60
62
  "chokidar": "^5.0.0",
61
63
  "deepmerge-ts": "^7.1.5",
62
64
  "diff-match-patch": "^1.0.5",
63
65
  "dir-compare": "^5.0.0",
64
- "ejs": "^4.0.1",
66
+ "ejs": "^5.0.1",
67
+ "esbuild": "^0.27.4",
65
68
  "express": "^5.2.1",
66
69
  "extract-zip": "^2.0.1",
67
- "file-type": "^21.3.1",
70
+ "file-type": "^21.3.3",
68
71
  "formdata-node": "^6.0.3",
69
72
  "http-proxy-middleware": "^3.0.5",
70
- "isbinaryfile": "^5.0.7",
71
- "jsdom": "^25.0.1",
73
+ "isbinaryfile": "^6.0.0",
74
+ "jsdom": "^29.0.0",
72
75
  "memory-cache": "^0.2.0",
73
76
  "picocolors": "^1.1.1",
74
77
  "rollup": "^4.59.0",
75
- "sass": "^1.97.3",
78
+ "sass": "^1.98.0",
76
79
  "sharp": "^0.34.5",
77
80
  "source-map-support": "^0.5.21",
78
- "svgo": "^4.0.0",
81
+ "svgo": "^4.0.1",
79
82
  "svgtofont": "^6.5.1",
80
83
  "typescript": "^5.9.3",
81
- "vite": "^7.3.1",
82
- "vite-plugin-image-optimizer": "^1.1.9",
84
+ "vite": "^8.0.1",
85
+ "vite-plugin-image-optimizer": "^2.0.3",
83
86
  "vite-plugin-zip-pack": "^1.2.4",
84
87
  "winston": "^3.19.0"
85
88
  },
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("http-proxy-middleware"),t=require("vite"),r=require("picocolors"),s=require("axios"),n=require("jsdom"),a=require("https"),i=require("memory-cache"),o=require("path"),c=require("fs"),l=require("url"),p=require("crypto"),d=require("process"),h=require("child_process"),u=require("console"),g=require("zlib"),f=require("express");var m="undefined"!=typeof document?document.currentScript:null;const w=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function y(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const r in e)t[r]=e[r];return t.default=e,Object.freeze(t)}const v=w(s),b=y(i),k=y(o),x=y(p),P=y(d),T=y(h),A=y(u),S=w(f),$=(e,t,r)=>{const s=new RegExp(`(!!)?(https?(:(\\\\)?/(\\\\)?/)${e})`,"gi");return r.replace(s,(e,...r)=>e.startsWith("!!")?r[1]:`http${r[2]}${t}`)},I=(e,t,r)=>{e.setHeader("location",t),e.statusCode=r,e.end()};let E=new Map;const L="default",R=(e="info",r=L)=>{if(E&&"function"==typeof E.has||(E=new Map),E.has(r))return E.get(r);if(r===L){const s=t.createLogger(e);return E.set(r,s),s}const s=t.createLogger(e);return E.set(r,s),s},C=r.createColors(),D=function(){const e={personal:{placeholder:"API Token",caption:`You can get the API Token\n <a href="https://${host}/api-token" target="_blank" \n style="color: #007bff; text-decoration: none;">here</a>`,endpoint:"/@api/login"},regular:{placeholder:"Legacy Token",caption:`You can get the Legacy Token\n <a href="https://${host}/api/get_token" target="_blank" \n style="color: #007bff; text-decoration: none;">here</a>`,endpoint:"/@api/login"}};function t(t,r,s){const n=e[t];n&&(r.placeholder=n.placeholder,s.innerHTML=n.caption)}function r(e,t){t.textContent=e,t.classList.add("show")}function s(e){e.classList.remove("show")}function n(e,t,n,a){n.addEventListener("click",async n=>{if(n.preventDefault(),s(a),!t.value.trim())return r(`${t.placeholder} is required`,a),void t.focus();const i=document.getElementById("token-type-switcher"),o=i?.querySelector(".token-type-option.active"),c=o?.dataset.value||"personal";await async function(e,t,s,n){try{s.classList.add("loading");const a=await fetch("/@api/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,tokenType:t}),redirect:"follow"}),i=a.url&&new URL(a.url,window.location.origin);if(!i||i.pathname.startsWith("/login")||i.pathname.startsWith("/@api/"))try{const e=await a.json();r(`Login failed: ${e?.error||"Unknown error occurred"}`,n)}catch(e){r("Login failed: Unable to parse response",n)}else window.location.href=a.url}catch(e){r("Login failed: Network error. Please check your connection.",n)}finally{s.classList.remove("loading")}}(t.value.trim(),c,e,a)}),t.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),n.click())}),t.addEventListener("input",()=>{s(a)})}function a(e){const r=e.firstChild;if(!r)return;const s=r.lastChild?.cloneNode(!0);if(!s)return;s.innerHTML="";const a=s.cloneNode(!0);a.innerText="OR",a.setAttribute("role","separator"),a.setAttribute("aria-label","Alternative login method");const i=s.cloneNode(!0),o=document.createElement("div"),c=document.createElement("style");c.textContent="\n.helper-login-wrapper {\n font-family: Arial, sans-serif;\n color: #222;\n padding: 8px;\n background-color: #f8f9fa;\n border-radius: 8px;\n border: 1px solid #ddd;\n width: 100%;\n max-width: 400px;\n margin: 0 auto;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n}\n\n.helper-login-wrapper .title {\n font-weight: bold;\n font-size: 18px;\n margin-bottom: 12px;\n text-align: center;\n}\n\n.helper-login-wrapper .control {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.helper-login-wrapper .control input {\n border: 1px solid #ddd;\n border-radius: 4px;\n width: 100%;\n box-sizing: border-box;\n text-align: center;\n height: 26px;\n padding: 0 8px;\n font-size: 14px;\n}\n\n.helper-login-wrapper .control input:focus {\n outline: none;\n border-color: #007bff;\n box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);\n}\n\n.helper-login-wrapper .control .caption {\n font-size: 12px;\n color: #666;\n text-align: center;\n}\n\n.helper-login-wrapper .footer {\n margin-top: 16px;\n text-align: center;\n}\n\n.helper-login-wrapper .footer .btn.submit {\n background-color: #007bff;\n color: white;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n width: 100%;\n font-size: 14px;\n transition: background-color 0.3s;\n height: 26px;\n font-weight: 500;\n}\n\n.helper-login-wrapper .footer .btn.submit:hover {\n background-color: #0056b3;\n}\n\n.helper-login-wrapper .footer .btn.submit:disabled {\n background-color: #6c757d;\n cursor: not-allowed;\n}\n\n.helper-login-wrapper .token-type-switcher {\n display: flex;\n border: 1px solid #ccc;\n border-radius: 4px;\n overflow: hidden;\n margin-bottom: 12px;\n width: 100%;\n}\n\n.helper-login-wrapper .token-type-option {\n padding: 4px 8px;\n cursor: pointer;\n background-color: #f8f9fa;\n color: #666;\n font-size: 12px;\n text-align: center;\n transition: background-color 0.2s, color 0.2s;\n border-right: 1px solid #ccc;\n flex: 1;\n user-select: none;\n}\n\n.helper-login-wrapper .token-type-option:last-child {\n border-right: none;\n}\n\n.helper-login-wrapper .token-type-option.active {\n background-color: #007bff;\n color: white;\n font-weight: bold;\n}\n\n.helper-login-wrapper .token-type-option:not(.active):hover {\n background-color: #e9ecef;\n}\n\n.helper-login-wrapper .error-message {\n color: #dc3545;\n font-size: 12px;\n text-align: center;\n margin-top: 8px;\n display: none;\n}\n\n.helper-login-wrapper .error-message.show {\n display: block;\n}\n\n.helper-login-wrapper .loading {\n opacity: 0.6;\n pointer-events: none;\n}\n",document.head.appendChild(c),o.innerHTML=`\n<div class="helper-login-wrapper" role="form" aria-label="PP Dev Helper Login">\n <div class="title" role="heading" aria-level="2">PP Dev Helper</div>\n\n <div class="token-type-switcher" id="token-type-switcher" role="tablist" aria-label="Token type selection">\n <div class="token-type-option active" data-value="personal" role="tab" aria-selected="true" tabindex="0">\n API Token\n </div>\n <div class="token-type-option" data-value="regular" role="tab" aria-selected="false" tabindex="0">\n Legacy Token\n </div>\n </div>\n\n <div class="control">\n <input \n type="password" \n id="helper-token" \n placeholder="API Token"\n aria-label="Token input"\n aria-describedby="token-caption"\n >\n <span class="caption" id="token-caption">\n You can get the API Token\n <a href="https://${host}/api-token" target="_blank" style="color: #007bff; text-decoration: none;">here</a>\n </span>\n </div>\n\n <div class="error-message" id="error-message" role="alert" aria-live="polite"></div>\n\n <div class="footer">\n <button id="helper-token-submit" class="btn submit" type="button">\n Token Login\n </button>\n </div>\n</div>`,i.appendChild(o),r.appendChild(a),r.appendChild(i);const l=document.getElementById("token-type-switcher"),p=document.getElementById("helper-token"),d=document.getElementById("token-caption"),h=document.getElementById("helper-token-submit"),u=document.getElementById("error-message"),g=o.querySelector(".helper-login-wrapper");l&&p&&d&&h&&u&&g?(!function(e,r,s){const n=e.querySelectorAll(".token-type-option"),a=e=>{const a=e.dataset.value;n.forEach(e=>{e.classList.remove("active"),e.setAttribute("aria-selected","false"),e.setAttribute("tabindex","-1")}),e.classList.add("active"),e.setAttribute("aria-selected","true"),e.setAttribute("tabindex","0"),t(a,r,s)};n.forEach(e=>{e.addEventListener("click",e=>{const t=e.currentTarget;a(t)}),e.addEventListener("keydown",t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),a(e))})})}(l,p,d),n(g,p,h,u),t("personal",p,d)):console.error("Failed to find required form elements")}const i=new MutationObserver(e=>{for(const t of e)if("childList"===t.type){const e=document.querySelector("#mi-react-root form");if(e){i.disconnect(),a(e);break}}});i.observe(document.body,{childList:!0,subtree:!0});const o=document.querySelector("#mi-react-root form");o&&(i.disconnect(),a(o))},F=/^(https?:\/\/)([^/]+)(\/.*)?$/i,O="X-PP-Proxy";function N(t){const{rewritePath:r=/^\/(?!p[tl]).*/i,baseURL:s="",disableSSLValidation:n=!1,miAPI:a}=t;if(!s)throw new Error("Base url is required");const i=s.replace(F,"$2"),o=s.replace(F,"$1$2"),c=import("file-type"),l=R();return e.createProxyMiddleware({selfHandleResponse:!0,pathFilter:(e,s)=>!(t.proxyIgnore||[]).some(t=>"string"==typeof t?e.startsWith(t):"function"!=typeof t.test||t.test(e))&&("string"==typeof r?e.startsWith(r):Array.isArray(r)?r.some(t=>e.startsWith(t)):"function"==typeof r.test&&r.test(e)),target:s,changeOrigin:!0,autoRewrite:!0,cookieDomainRewrite:{[i]:"localhost"},logger:{info:()=>{},log:()=>{},error:()=>{},warn:()=>{}},secure:!n,headers:{host:i,origin:o},on:{proxyReq(e,t,r){const n=t.headers.host,i=e.getHeader("referer");return l.info(`${C.blue("Proxies request:")} ${C.green(t.method)} ${t.url} -> ${C.green(e.method)} ${e.protocol}//${e.host}${e.path}`),n&&i&&"string"==typeof i&&e.setHeader("referer",i.replace(new RegExp(`https?://${n}`),s)),a.personalAccessToken&&e.setHeader("Authorization",`Bearer ${a.personalAccessToken}`),t.socket.on("close",()=>{setTimeout(()=>{e.destroyed||e.destroy()},200)}),e},proxyRes:(t,r,s)=>{if(t.headers["content-type"]?.includes("text/event-stream")||t.headers["transfer-encoding"]?.includes("chunked")&&"no"===t.headers["x-accel-buffering"]){l.info(`${C.blue("Start streaming for request:")} ${C.green(r.method)} ${r.url}`);const e=async(e,t,r)=>{r.setHeader(O,1),r.setHeaders(new Map(Object.entries(e.headers))),e.pipe(r)};return e(t,r,s)}const n=e.responseInterceptor(async(e,t,r,s)=>{s.setHeader(O,1);if(await(await c).fileTypeFromBuffer(e))return e;{let t=e.toString("utf8");try{const e=new URL(r.url??"",`http://${i}`);if(e.searchParams&&e.searchParams.has("proxyRedirect")){const e=function(){const e="pp-dev::redirectCount",t="pp-dev::lastRedirect";let r=+(localStorage.getItem(e)??0);localStorage.getItem(t);Number.isNaN(r)&&(r=0);let s=window.location.href;const n=function(){const a=new URLSearchParams(window.location.search);if(!a.has("proxyRedirect"))return console.debug("No proxyRedirect param. Cleaning up."),void localStorage.removeItem(e);s!==window.location.href?(s=window.location.href,setTimeout(n,r<3?3e3:5e3)):window.location.href=a.get("proxyRedirect"),localStorage.setItem(e,""+ ++r),localStorage.setItem(t,(new Date).toISOString())};setTimeout(n,3e3)};t+=`<script>(${e.toString()})()<\/script>`}e.pathname.startsWith("/login")&&(s.setHeader("Cache-Control","no-cache, no-store, must-revalidate"),s.setHeader("Pragma","no-cache"),s.setHeader("Expires","0"));const n=t.slice(0,100);(n.includes("<html")||n.includes("<body")||n.includes("<head")||n.includes("html>"))&&(t+=`<script>const host = "${i}";\n(${D.toString()})()<\/script>`)}catch{}const n=r.headers.host??"";return((e,t,r)=>{const s=new RegExp(`${e.replace(/\\*\//gi,"\\\\/")}`,"gi"),n=new RegExp(`${e}`,"gi"),a=r.replace(s,t);return a===r?a.replace(n,t):a})("/auth/saml/login","/login",$(i,n,t))}});return n(t,r,s)},error(e,t,r){const s=`Proxy error: "${e.message}" when trying to "${t.method} ${t.url}"\n\n${e.stack}`;l.error(s),r.writable&&r.writeHead(500,{"Content-Type":"text/plain"}),r.end(s)}}})}class U{axios;constructor(e){this.axios=e}async checkAuth(e){return this.axios.get("/data/page/index/auth/info",{headers:Object.assign({},e,{accept:"text/html"}),maxRedirects:0}).then(()=>!0).catch(()=>!1)}}class j extends U{formdataModulePromise=import("formdata-node");constructor(e){super(e)}getDownloadUrl(e){return`/admin/page/downloadassets/id/${e}`}getDownloadTemplateUrl(e){return`/admin/pagetemplate/downloadassets/id/${e}`}getUploadUrl(e){return`/admin/page/uploadassets/id/${e}`}getUploadTemplateUrl(e){return`/admin/pagetemplate/uploadassets/id/${e}`}async downloadPageAssets(e,t){return this.axios.get(this.getDownloadUrl(e),{withCredentials:!0,headers:Object.assign({},t,{accept:"*/*"}),responseType:"arraybuffer"}).then(e=>e.data)}async uploadPageAssets(e,t,r){const s=new(await this.formdataModulePromise).FormData,{File:n}=await this.formdataModulePromise,a=new n([t],"file.zip",{type:"application/zip"});s.append("file",a);const i=this.getUploadUrl(e);return this.axios.post(i,s,{withCredentials:!0,headers:Object.assign({},r,{accept:"application/json","Content-Type":"multipart/form-data",Referer:this.axios.getUri({url:i})})}).then(e=>e.data)}async downloadTemplateAssets(e,t){return this.axios.get(this.getDownloadTemplateUrl(e),{withCredentials:!0,headers:Object.assign({},t,{accept:"*/*"}),responseType:"arraybuffer"}).then(e=>e.data)}async uploadTemplateAssets(e,t,r){const s=new(await this.formdataModulePromise).FormData,{File:n}=await this.formdataModulePromise,a=new n([t],"file.zip",{type:"application/zip"});s.append("file",a,"file.zip");const i=this.getUploadTemplateUrl(e);return this.axios.post(i,s,{withCredentials:!0,headers:Object.assign({},r,{accept:"application/json","Content-Type":"multipart/form-data",Referer:this.axios.getUri({url:i})})}).then(e=>e.data)}}class M extends j{getDownloadUrl(e){return`/api/page/id/${e}/asset/download`}getDownloadTemplateUrl(e){return`/api/page_template/id/${e}/asset/download`}getUploadUrl(e){return`/api/page/id/${e}/asset/upload`}getUploadTemplateUrl(e){return`/api/page_template/id/${e}/asset/upload`}}class H extends U{async getAll(e){return(await this.axios.get("/api/page",{withCredentials:!0,headers:Object.assign({},e,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"})})).data.pages}async get(e,t){return(await this.axios.get(`/api/page/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data.page}async getPageContent(e,t){return(await this.axios.get(`/p/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"text/html","content-type":"application/json"})})).data}async create(e,t){return(await this.axios.post("/api/page",e,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data.page}}class B extends U{async getAll(e,t){return(await this.axios.get("/api/page_template",{withCredentials:!0,headers:Object.assign({},t,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"}),params:{internal_name:e}})).data.page_templates}async get(e,t){return(await this.axios.get(`/api/page_template/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data.page_template}}function z(e){const t=e.response?.status||0,r=e.response?.data?.message||e.message||"Unknown error";switch(t){case 412:const e=r.toLowerCase();return e.includes("session expired")||e.includes("session has expired")?{status:t,message:r,code:"SESSION_EXPIRED",userFriendlyMessage:"Your session has expired",suggestions:["Refresh your token in the portal","Re-authenticate with the portal","Check if your token has been revoked","Ensure your token has the correct permissions"]}:{status:t,message:r,code:"AUTH_FAILED",userFriendlyMessage:"Authentication failed",suggestions:["Verify your token is correct","Check token permissions","Ensure the token hasn't expired","Try generating a new token"]};case 401:return{status:t,message:r,code:"UNAUTHORIZED",userFriendlyMessage:"Unauthorized access",suggestions:["Check if your token is valid","Verify you have the required permissions","Ensure the token hasn't been revoked","Try logging in again"]};case 403:return{status:t,message:r,code:"FORBIDDEN",userFriendlyMessage:"Access forbidden",suggestions:["Check your user permissions","Verify the portal page ID is correct","Ensure your token has the right scope","Contact your administrator"]};default:return{status:t,message:r,code:"UNKNOWN_ERROR",userFriendlyMessage:"An unexpected error occurred",suggestions:["Check your network connection","Verify the portal URL is correct","Try again in a few moments","Check the portal status"]}}}const V="[DEV PAGE. DO NOT DELETE]",_=new Map;class q{#e;#t;#r=null;#s;#n;#a;#i;#o;#c;#l;internalPageName;portalPageId;templateLess;assetsApi;pageApi;pageTemplateApi;logger;constructor(e,t){const{headers:r={},portalPageId:s,templateLess:n=!0,disableSSLValidation:i=!1,v7Features:o=!1,personalAccessToken:c}=t||{};this.#e=r,this.#n=[],this.#s="",this.#a=o,this.#i=c,this.#o=!1,this.#c=Promise.resolve(!1);const l=`${e}:${i}`;_.has(l)?this.#t=_.get(l):(i&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",v.defaults.httpsAgent=new a.Agent({rejectUnauthorized:!1})),this.#t=v.create({baseURL:e,headers:r,timeout:3e4,maxRedirects:5,httpAgent:new a.Agent({keepAlive:!0,maxSockets:10}),httpsAgent:new a.Agent({keepAlive:!0,maxSockets:10})}),_.set(l,this.#t)),this.portalPageId=s,this.templateLess=n,this.assetsApi=new(o?M:j)(this.#t),this.pageApi=new H(this.#t),this.pageTemplateApi=new B(this.#t),this.logger=R()}async isTemplateLoaded(){return this.#c}get isV710OrHigher(){return this.#o}#p(e){const t=Object.assign({},e,{host:void 0,referer:void 0});return Object.keys(t).forEach(e=>void 0===t[e]&&delete t[e]),this.#e=t,!t.authorization&&this.#i&&(t.authorization=`Bearer ${this.#i}`),t}get personalAccessToken(){return this.#i}set personalAccessToken(e){this.#i=e}updateHeaders(e){this.#p(e)}get localTemplateHTML(){return'<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>%%PAGE TITLE%%</title>\n <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>\n <meta name="theme-color" content="rgba(255, 255, 255, 1)"/>\n <link rel="shortcut icon" type="image/x-icon" sizes="any" href="/img/favicon/favicon.ico"/>\n <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon/favicon-16x16.png"/>\n <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon/favicon-32x32.png"/>\n <link rel="icon" type="image/png" sizes="48x48" href="/img/favicon/favicon-48x48.png"/>\n <meta name="msapplication-config" content="/auth/browserconfig.xml"/>\n <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon/apple-touch-icon.png"/>\n <link rel="manifest" href="/auth/site.webmanifest"/>\n <link rel="manifest" href="/auth/manifest.json"/>\n <link rel="stylesheet" type="text/css" href="/auth/theme-vars.css"/>\n <link rel="icon" type="image/svg+xml" href="/favicon.ico" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <script src="/js/libs/underscore-latest.min.js" charset="utf-8"><\/script>\n <script src="/js/jquery/jquery-latest.min.js" charset="utf-8"><\/script>\n <script src="/js/application/rating_component.js" charset="utf-8"><\/script>\n </head>\n <body>\n <div id="mi-react-root"></div>\n <script src="/auth/info.js"><\/script>\n <script src="/js/main.js" defer><\/script>\n <link rel="stylesheet" href="/css/main.css" />\n </body>\n </html>'}async getPageTemplate(e){if(await this.#c||this.#r||(this.#c=new Promise(e=>{this.#l=e})),this.#r)return Promise.resolve(this.#r);if(void 0===this.templateLess&&(this.templateLess=!1),this.#a){const t=await this.pageApi.get(this.portalPageId,this.#p(e)).then(e=>(this.logger.info(C.green("Page fetched")),e)).catch(async t=>{throw this.#l(!1),await this.pageApi.checkAuth(this.#p(e))?(this.logger.error(C.red(`Error fetching page data: ${t.message}\n${t.stack}`)),new Error("The current user does not have access to this page. Check your configuration to ensure the portalPageId is correct.")):t});return void 0!==t.template_id&&(this.#o=!0),this.internalPageName=t.internal_name,this.#r=this.localTemplateHTML,this.#r=this.#r.replace(/%%PAGE TITLE%%/g,t.name||"Local template"),this.logger.info(C.green("Local page template fetched")),this.#l(!0),this.#r}let t=(await this.pageApi.getAll(this.#p(e)).then(e=>(this.logger.info(C.green("Page list fetched")),e)).catch(async t=>{throw this.#l(!1),await this.pageApi.checkAuth(this.#p(e))?(this.logger.error(C.red(`Error fetching page list: ${t.message}\n${t.stack}`)),new Error("Current user does not have access to page list")):t})).find(e=>e.name===V);return t||(this.logger.warn(C.yellow("Creating dev page template...")),t=await this.pageApi.create({enabled:"Y",name:V,internal_name:"dev-page-template",visible_in_homepage:"Y"},this.#p(e)).then(e=>(this.logger.info(C.green("Dev page created")),e)).catch(e=>{throw this.logger.error(C.red(`Error creating dev page: ${e.message}`)),this.#l(!1),new Error(`Error when creating dev page.\n That can be caused by missing permissions or page with name "${V}" already exists`)})),await this.pageApi.getPageContent(t.internal_name,this.#p(e)).then(e=>(this.#r=e,e)).then(e=>(this.#l(!0),this.logger.info(C.green("Page template fetched")),e)).catch(e=>{throw this.#l(!1),this.logger.error(C.red(`Error fetching page template: ${e.message}`)),new Error("Error fetching page template")})}async getPageVariables(e,t){return this.#r=await this.getPageTemplate(t),this.portalPageId||(this.portalPageId=e,this.templateLess=!1),await this.pageApi.get(e,this.#p(t)).then(e=>{const{tags:t="[]",name:r,template:s}=e;if(s&&t){const e=JSON.parse(t);return this.#n=e,this.#s=r,e}return this.#n=[],this.#s=r,[]}).catch(t=>{if(this.logger.error(C.red(`Error fetching page variables: ${t.message}`)),404===t.response?.status)throw new Error(`Portal Page with id "${e}" not found on instance ${this.#t.getUri()}`);if(401===t.response?.status)throw new Error(`Current user does not have access to page with id "${e}" on instance ${this.#t.getUri()}`);throw t})}async getPageInfo(e,t){this.portalPageId||(this.portalPageId=e);const r=this.#p(t),s=this.portalPageId;try{return this.#a?await this.#d(s,r):await this.#h(s,r)}catch(e){this.#u(e,s)}}async#d(e,t){const r=await this.pageApi.get(e,t);return this.logger.info(C.green("Page fetched")),void 0!==r.template_id&&(this.#o=!0),r}async#h(e,t){return await this.pageApi.get(e,t)}#u(e,t){if(this.#a&&e.message?.includes("access"))throw new Error("The current user does not have access to this page. Check your configuration to ensure the portalPageId is correct.");if(404===e.response?.status)throw new Error(`Portal Page with id "${t}" not found on instance ${this.#t.getUri()}`);throw 401===e.response?.status&&this.logger.error(C.red(`Current user does not have access to page with id "${t}" on instance ${this.#t.getUri()}`)),e}buildPage(e,t=!1){let r="string"==typeof e?e:e.toString("utf-8");for(const e of this.#n)r=r.replace(new RegExp(`\\[${e.name}\\]`,"g"),e.value);const s=new n.JSDOM(t?r:this.#r),a="%%PLACEHOLDER%%";if(!t){const e=s.window.document.createElement("div");e.innerHTML=a;const t=s.window.document.querySelector(".main-side");if(t){const r=t.querySelectorAll("script");r.length?t.insertBefore(e,r.item(r.length-1)):t.append(e)}else{const t=s.window.document.createElement("div");t.append(e),s.window.document.body.append(t)}const r=s.window.document.querySelector("head"),n=r.querySelector("title");n?n.text=this.#s:r.innerHTML+=`<title>${this.#s}</title>`}return s.serialize().replace(new RegExp(`<div>\\s*${a}\\s*<\\/div>`,"i"),r)}async getAssets(){if(this.portalPageId){if(this.templateLess)return await this.assetsApi.downloadPageAssets(this.portalPageId,this.#e);{const e=await this.pageApi.get(this.portalPageId,this.#e);if(this.#o){const t=await this.pageTemplateApi.get(e.template_id,this.#e);return await this.assetsApi.downloadTemplateAssets(t.id,this.#e)}if(e.template)return await this.assetsApi.downloadTemplateAssets(e.template,this.#e)}}}async updateAssets(e){if(this.portalPageId){if(this.templateLess)return await this.assetsApi.uploadPageAssets(this.portalPageId,e,this.#e);{const t=await this.pageApi.get(this.portalPageId,this.#e);if(this.#o){const r=await this.pageTemplateApi.get(t.template_id,this.#e);return await this.assetsApi.uploadTemplateAssets(r.id,e,this.#e)}if(t.template)return await this.assetsApi.uploadTemplateAssets(t.template,e,this.#e)}}}async validateCredentials(e){try{const t=e||this.#e;return await this.get("/api/user",t,!0),{isValid:!0}}catch(e){const t=z(e);return{isValid:!1,error:t.userFriendlyMessage,code:t.code}}}async get(e,t,r=!1){const s=r?t:Object.assign({},this.#p(this.#e),t);try{return await this.#t.get(e,{headers:s})}catch(e){if("UNKNOWN_ERROR"!==z(e).code){const t=z(e);throw this.logger.error(C.red(`API request failed: ${t.userFriendlyMessage}`)),function(e,t,r){const s=z(t),n=`[${r}] `;e.error(C.red(`${n}${s.userFriendlyMessage}`)),e.error(C.red(`Status: ${s.status} (${s.code})`)),e.error(C.red(`Details: ${s.message}`)),s.suggestions.length>0&&(e.info(C.yellow("Suggestions:")),s.suggestions.forEach((t,r)=>{e.info(C.yellow(` ${r+1}. ${t}`))}))}(this.logger,e,"API Request"),e.response||(e.response={status:t.status,data:{message:t.message}}),e.tokenErrorInfo=t,e}throw e}}}class Z{server;opts;eventMap;logger;constructor(e,t){this.server=e,this.opts=t||{},this.eventMap=new Map,this.eventMap.set("info-data:request",this.onInfoDataRequest.bind(this)),this.eventMap.set("template:sync",this.onTemplateSync.bind(this)),this.logger=R(),this.init()}init(){const{ws:e}=this.server;for(const[t,r]of this.eventMap)e.on(t,r)}onInfoDataRequest(){this.server.ws.send({type:"custom",event:"info-data:response",data:{}})}async onTemplateSync(){if(!this.opts.distService||!this.opts.miAPI)return this.server.ws.send("template:sync:response",{error:"Dist service or MiAPI is not defined"}),void this.logger.error(C.red("Dist service or MiAPI is not defined"));{const{distService:e,miAPI:t}=this.opts;if(this.server.config.clientInjectionPlugin?.v7Features){if(!t?.isV710OrHigher)return void this.server.ws.send("template:sync:response",{error:"This feature is available only for MI v7.1.0 or higher",config:{canSync:!1}});this.server.ws.send("client:config:update",{config:{canSync:!0}})}const r=await(t?.getAssets().catch(async e=>{if(s.isAxiosError(e)){if("SESSION_EXPIRED"===z(e).code){this.logger.info(C.yellow("Session expired - attempting to validate credentials"));try{const e=await(t?.validateCredentials());e&&!e.isValid?(this.logger.error(C.red(`Authentication error: ${e.error}`)),this.server.ws.send("template:sync:response",{error:e.error,code:e.code,refresh:!0})):(this.logger.info(C.yellow("Session expired")),this.server.ws.send("template:sync:response",{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0}))}catch(e){this.logger.info(C.yellow("Session expired")),this.server.ws.send("template:sync:response",{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0})}return e}if(e.cause instanceof Error&&("ECONNRESET"===e.cause.code||"ENOTFOUND"===e.cause.code))return this.logger.info(C.yellow("Server in maintenance mode, VPN connection is needed or no internet connection")),this.server.ws.send("template:sync:response",{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e}throw e}));if(r instanceof Error)return;const n=r?await(e?.saveBackupAndBuild(r).catch(e=>{if("Backup file is not a ZIP file"===e.message)return this.logger.error(C.red("Backup file is not a ZIP file")),e})):await(e?.buildNewAssets());if(!(n&&n instanceof Buffer))return n instanceof Error?(this.server.ws.send("template:sync:response",{error:n.message}),void this.logger.error(C.red(n.message))):(this.server.ws.send("template:sync:response",{error:"Failed to build new assets"}),void this.logger.error(C.red("Failed to build new assets")));{const r=await(t?.updateAssets(n));if("OK"===r?.status){const t=e?.getBackupMeta(),{lastBackupName:r,lastBackupHash:s,lastBackupDate:n}=t||{lastBackupName:"",lastBackupHash:"",lastBackupDate:(new Date).toISOString()};this.server.ws.send("template:sync:response",{syncedAt:new Date(n),currentHash:s,backupFilename:r}),this.logger.info(C.green("Template synced"))}else this.server.ws.send("template:sync:response",{error:"Failed to update assets"}),this.logger.error(C.red("Failed to update assets"))}}}}const W=/\.(?:[a-z0-9]+)$/i,X=6e5,Y=104857600,K=1e3;class J extends b.Cache{totalSize=0;maxSize;maxItems;constructor(e,t){super(),this.maxSize=e,this.maxItems=t}put(e,t,r){const s=this.get(e);s&&(this.totalSize-=s.size);const n=super.put(e,t,r);return this.totalSize+=t.size,this.cleanup(),n}cleanup(){const e=this.keys();if(e.length>this.maxItems){const t=e.length-this.maxItems,r=e.sort((e,t)=>{const r=this.get(e),s=this.get(t);return(r?.timestamp||0)-(s?.timestamp||0)});for(let e=0;e<t;e++){const t=r[e],s=this.get(t);s&&(this.totalSize-=s.size,this.del(t))}}for(;this.totalSize>this.maxSize&&e.length>0;){const t=e.sort((e,t)=>{const r=this.get(e),s=this.get(t);return(r?.timestamp||0)-(s?.timestamp||0)})[0];if(t){const e=this.get(t);e&&(this.totalSize-=e.size,this.del(t))}}}getTotalSize(){return this.totalSize}getItemCount(){return this.keys().length}}const G=new J(Y,K);function Q(e){if(0===e.length)return Buffer.alloc(0);if(1===e.length)return e[0];const t=e.reduce((e,t)=>Buffer.byteLength(t)+e,0);return Buffer.concat(e,t)}function ee(e){const{devServer:t,ttl:r=X,maxSize:s=Y,maxItems:n=K}=e,a=R();return s===Y&&n===K||(G.maxSize=s,G.maxItems=n),t.cache=G,(e,t,s)=>{const n=e.originalUrl||e.url||"",i=function(e){const t=e.split("?")[0];return W.test(t)?t.includes("/auth/info.js")?"":e:""}(n);if(!i)return s();const o=G.get(i);if(o)return a.info(`${C.blue("Proxies request:")} ${C.green(e.method)} ${n} -> ${C.blue("Cache")} ${i}`),function(e,t){try{for(const[r,s]of Object.entries(t))null!=s&&e.setHeader(r,s)}catch(e){console.warn("Failed to set some response headers:",e)}}(t,o.headers),t.write(o.content),void t.end();const c=t.end,l=t.write,p=[];t.write=function(e,r,s){if(!t.hasHeader(O))return l.call(this,e,r,s);if("string"==typeof e){const t=r||"utf8";p.push(Buffer.from(e,t))}else Buffer.isBuffer(e)?p.push(e):null!=e&&p.push(Buffer.from(String(e),"utf8"));return!0},t.end=function(e,s,n){if(!t.hasHeader(O))return c.call(this,e,s,n);if(null!=e)if("string"==typeof e){const t=s||"utf8";p.push(Buffer.from(e,t))}else Buffer.isBuffer(e)?p.push(e):p.push(Buffer.from(String(e),"utf8"));let o;try{o=Q(p);const e=Buffer.byteLength(o);if(e>0&&e<10485760){const s={headers:t.getHeaders(),content:o,timestamp:Date.now(),size:e};G.put(i,s,r),a.info(`${C.blue("[Cached]")} ${i} (${(e/1024).toFixed(1)}KB)`)}}catch(e){a.error(`Failed to cache response for ${i}: ${e}`),o=Q(p)}const l=s||"utf8";return c.call(this,o,l,n)},s()}}const te="pageName",re="date",se=k.dirname("undefined"!=typeof __filename&&__filename||l.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("plugin-D-TIdILy.js",document.baseURI).href)),ne=k.resolve(se,"..",".."),ae=k.resolve(ne,"..",".."),ie=k.resolve(ae,".pp-dev-meta"),oe=k.resolve(ie,"sync-service.meta.json");class ce{backupFolder;backupNameTemplate;dateFormat;pageName;currentMeta=null;distZipFolder;distZipFilename;logger;constructor(e,t){this.pageName=e;const{backupFolder:r=k.resolve(P.cwd(),"backups"),distZipFolder:s=k.resolve(P.cwd(),"dist-zip"),distZipFilename:n=`${this.pageName}.zip`,backupNameTemplate:a=`{${te}}-{${re}}.zip`,dateFormat:i=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,"")}=t||{};this.backupFolder=r,this.backupNameTemplate=a,this.dateFormat=i,this.distZipFolder=s,this.distZipFilename=n,this.syncMeta(),this.logger=R()}async checkMeta(){try{await c.promises.stat(ie)}catch{await c.promises.mkdir(ie)}try{await c.promises.stat(this.backupFolder)}catch{await c.promises.mkdir(this.backupFolder)}}async readMetaFile(){return await this.checkMeta(),await c.promises.readFile(oe,{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await c.promises.writeFile(oe,JSON.stringify(e,null,2),{encoding:"utf-8"})}async syncMeta(){this.currentMeta?await this.writeMetaFile(this.currentMeta):this.currentMeta=JSON.parse(await this.readMetaFile())}async getLatestSavedBackup(){const{lastBackupName:e}=this.currentMeta;if(!e)return null;const t=k.resolve(this.backupFolder,e);try{return await c.promises.stat(t),t}catch{return null}}backupName(e,t=new Date){return this.backupNameTemplate.replace(`{${te}}`,e).replace(`{${re}}`,this.dateFormat(t))}getBackupMeta(){return this.currentMeta}async saveBackup(e){if("PK"!==e.toString("utf-8").slice(0,4))throw new Error("Backup file is not a ZIP file");const t=x.createHash("md5").update(e).digest("hex");if(await this.getLatestSavedBackup()){const{lastBackupHash:e}=this.currentMeta;if(e===t)return}const r=new Date,s=this.backupName(this.pageName,r);return this.currentMeta.lastBackupName=s,this.currentMeta.lastBackupHash=t,this.currentMeta.lastBackupDate=r.toISOString(),await this.syncMeta(),await c.promises.writeFile(k.resolve(this.backupFolder,s),e).finally(()=>{this.logger.info(`Backup saved to ${s}`)})}async buildNewAssets(){const e=new Promise((e,t)=>{let r="";this.logger.info(C.cyan("[DistService] Build started"));const s=T.spawn("node",[k.resolve(ne,"./bin/pp-dev.js"),"build"],{cwd:P.cwd(),env:Object.assign({},P.env,{NODE_ENV:"production"}),stdio:"inherit"});s.on("message",e=>{r+=e}),s.on("close",s=>{0===s?e(r):t(new Error(`build command exited with code ${s}`))}),s.on("error",e=>{t(e)})});try{await e.finally(()=>{this.logger.info(C.cyan("[DistService] Build finished"))});const t=k.resolve(P.cwd(),this.distZipFolder,this.distZipFilename);if(!await c.promises.stat(t))throw new Error(`File ${t} not found`);return await c.promises.readFile(t)}catch(e){throw A.log(e),e}}async saveBackupAndBuild(e){return await this.saveBackup(e),await this.buildNewAssets()}}function le(e,t){return async(r,s,n)=>{if(await e(r.url??"",r,s)){R().info(`Rewrite response for ${r.url}`);const e=s.end,n=[];s.write=function(e){return n.push(e),!0},s.end=function(a,i,o){"string"==typeof a&&n.push(Buffer.from(a));const c=s.getHeader("content-encoding"),l=function(e,t){switch(t){case"gzip":return g.unzipSync(e);case"br":return g.brotliDecompressSync(e);case"deflate":return g.inflateSync(e);default:return e}}(Buffer.from(Buffer.concat(n)),c),p="function"!=typeof i&&i?i:"utf-8",d="function"==typeof i?i:o;return e.call(this,function(e,t){switch(t){case"gzip":return g.gzipSync(e);case"br":return g.brotliCompressSync(e);case"deflate":return g.deflateSync(e);default:return e}}(t(l,r,s),c),p,d),this}}n()}}function pe(e,t){const r=(e=(e=e.startsWith("/")?e:`/${e}`).endsWith("/")?e:`${e}/`).endsWith("/")?e.slice(0,-1):e,s=R();return(n,a,i)=>{const o=new l.URL(n.url??"","http://localhost"),{pathname:c,search:p}=o,d=["/",r];if(t&&(d.push(`/pt/${t}`),d.push(`/pl/${t}`)),d.includes(c)){const t=`${e}${p}`;return s.info(C.yellow(`Redirecting to: ${t}`)),I(a,t,302)}i()}}class de{state={isAuthenticated:!1,isRedirected:!1,lastChecked:0};listeners=new Set;getState(){return{...this.state}}isAuthenticated(){return this.state.isAuthenticated}isRedirected(){return this.state.isRedirected}setAuthenticated(e){this.state.isAuthenticated=e,this.state.lastChecked=Date.now(),this.notifyListeners()}setRedirected(e){this.state.isRedirected=e,this.notifyListeners()}updateState(e){void 0!==e.isAuthenticated&&(this.state.isAuthenticated=e.isAuthenticated),void 0!==e.isRedirected&&(this.state.isRedirected=e.isRedirected),this.state.lastChecked=Date.now(),this.notifyListeners()}reset(){this.state={isAuthenticated:!1,isRedirected:!1,lastChecked:0},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>{try{e(this.getState())}catch(e){console.error("Error in auth state listener:",e)}})}getDebugInfo(){return{...this.getState(),listenerCount:this.listeners.size}}}const he=new de,ue=new Map;function ge(e){const t=ue.get(e);return t?Date.now()-t.timestamp>18e4?(ue.delete(e),null):t.data:null}function fe(e,t){ue.set(e,{timestamp:Date.now(),data:t})}const me="/home?proxyRedirect=";function we(e,t,r){const{templateLess:s=!1,miHudLess:n=!1,appId:a,base:i,v7Features:o}=r,c=R();if(s&&n&&void 0===a)throw new Error("Custom App ID is required when both templateLess and miHudLess are true");let l=he.getState();return he.subscribe(e=>{l=e}),async(r,p,d)=>{try{const h=!(s&&n),u=e.test(function(e){return e.split("?")[0]}(r.url??""));if(!l.isAuthenticated&&!l.isRedirected&&r.url?.startsWith("/home")&&!r.url?.startsWith(me)){c.info(C.blue("Trying to authenticate and redirect to base"));try{return h?await ve(t,{templateLess:s,miHudLess:n,appId:a,redirectUrl:o&&i?`${i}`:`${me}${encodeURIComponent("/")}`},r,p,()=>{},c):await ye(t,{templateLess:s,miHudLess:n,appId:a,redirectUrl:o&&i?`${i}`:`${me}${encodeURIComponent("/")}`},r,p,()=>{},c),he.setRedirected(!0),c.info(C.blue("Successfully authenticated. Redirecting to base")),I(p,i??"/",302)}catch(e){return d()}}if(!u)return d();if(!h){return await ye(t,{templateLess:s,miHudLess:n,appId:a,redirectUrl:o&&i?`${i}`:`${me}${encodeURIComponent("/")}`},r,p,d,c)}return await ve(t,{templateLess:s,miHudLess:n,appId:a,redirectUrl:o&&i?`${i}`:`${me}${encodeURIComponent("/")}`},r,p,d,c)}catch(e){return c.error(C.red(`Unexpected error in load-pp-data middleware: ${e instanceof Error?e.message:String(e)}`)),he.reset(),d(e)}}}async function ye(e,t,r,s,n,a){const{appId:i,redirectOnAuthFailure:o,redirectUrl:c}=t;if(void 0===i){const e=new Error("Custom App ID is required for page info only mode");return a.error(C.red(e.message)),n(e)}const l=r.headers??{};a.info(C.green("Start loading page info"));try{const t=`pageInfo:${i}`;return ge(t)?(a.info(C.green("Page info loaded from cache")),n()):(await e.getPageInfo(i,l),a.info(C.blue("Clearing proxy cache after successful login")),G.clear(),fe(t,{success:!0}),he.updateState({isAuthenticated:!0}),a.info(C.green("Page info loaded successfully")),n())}catch(e){return he.reset(),be(e,o??!0,c||`${me}${encodeURIComponent("/")}`,s,n,a,"Page info")}}async function ve(e,t,r,s,n,a){const{templateLess:i,appId:o,redirectOnAuthFailure:c,redirectUrl:l}=t,p=r.headers??{};a.info(C.green("Start loading page data"));try{const t=`pageData:${i}:${o}`;if(ge(t))return a.info(C.green("Page data loaded from cache")),n();const r=i||void 0===o?e.getPageTemplate(p):e.getPageVariables(o,p);return await r,a.info(C.blue("Clearing proxy cache after successful login")),G.clear(),fe(t,{success:!0}),a.info(C.green("Page data loaded successfully")),n()}catch(e){return he.reset(),be(e,c??!0,l||`${me}${encodeURIComponent("/")}`,s,n,a,"Page data")}}function be(e,t,r,s,n,a,i){if(function(e){return null!==e&&"object"==typeof e&&"response"in e&&void 0!==e.response}(e)&&(a.info(C.red(`${i} loading failed. Not authorized`)),t)){const e=`${r}`;return a.info(C.yellow(`Redirecting to: ${e}`)),I(s,e,302)}const o=e instanceof Error?e.message:String(e);return a.info(C.red(`${i} loading failed. Error: ${o}`)),n(e)}function ke(){const e=S();return e.use(S.json()),e.use(S.urlencoded({extended:!0})),e}const xe=ke();function Pe(e,t,r){return t(e)?{isValid:!0}:{isValid:!1,error:r}}exports.AuthProvider=de,exports.MiAPI=q,exports.authProvider=he,exports.colors=C,exports.createLogger=R,exports.initLoadPPData=we,exports.initPPRedirect=pe,exports.initProxy=N,exports.initProxyCache=ee,exports.initRewriteResponse=le,exports.internalServer=xe,exports.normalizeVitePPDevConfig=function(e){const t=function(e){const t=[Pe(e,e=>"object"==typeof e&&null!==e,"VitePPDevOptions must be an object"),Pe(e.templateName,e=>"string"==typeof e&&e.length>0,"VitePPDevOptions.templateName must be a non-empty string"),Pe(e.backendBaseURL,e=>void 0===e||"string"==typeof e&&e.length>0,"VitePPDevOptions.backendBaseURL must be a non-empty string if provided"),Pe(e.portalPageId,e=>void 0===e||"number"==typeof e&&e>0,"VitePPDevOptions.portalPageId must be a positive number if provided"),Pe(e.appId,e=>void 0===e||"number"==typeof e&&e>0,"VitePPDevOptions.appId must be a positive number if provided"),Pe(e.proxyCacheTTL,e=>void 0===e||"number"==typeof e&&e>0,"VitePPDevOptions.proxyCacheTTL must be a positive number if provided"),Pe(e.integrateMiTopBar,t=>{if(void 0===t)return!0;if(null===t)return!1;if("boolean"!=typeof t&&"object"!=typeof t)return!1;if(!0===t&&!0!==e.miHudLess)return!1;if("object"==typeof t&&null!==t){if(void 0!==t.addRootElement&&"boolean"!=typeof t.addRootElement)return!1;if(void 0!==t.addSharedComponentsScripts&&"boolean"!=typeof t.addSharedComponentsScripts)return!1;if(!0!==e.miHudLess&&(!0===t.addRootElement||!0===t.addSharedComponentsScripts))return!1}return!0},"VitePPDevOptions.integrateMiTopBar must be a boolean or an object with addRootElement and addSharedComponentsScripts booleans")];return t.find(e=>!e.isValid)||{isValid:!0}}(e);if(!t.isValid)throw new Error(t.error);const r=e.appId??e.portalPageId,{enableProxyCache:s=!0,proxyCacheTTL:n=6e5,disableSSLValidation:a=!1,imageOptimizer:i=!0,miHudLess:o=!1,integrateMiTopBar:c=!1,templateLess:l=!1,outDir:p="dist",distZip:d=!0,versionPlugin:h=!0,syncBackupsDir:u="backups",v7Features:g=!1,personalAccessToken:f=process.env.MI_ACCESS_TOKEN}=e||{};let m=d;m=!0===m?{outFileName:`${e.templateName}.zip`,outDir:"dist-zip"}:"object"==typeof d&&{outFileName:"string"==typeof d.outFileName?d.outFileName.replace("[templateName]",e.templateName):`${e.templateName}.zip`,outDir:d.outDir??"dist-zip"};let w=i;"boolean"==typeof i?!0===w&&(w={}):"object"!=typeof i&&(w=!1);const y="VERSION-v{packageversion}-{currentDate}.json";let v;return v=!1!==h&&(!0===h?{versionFileTemplate:y,enabled:!0}:{versionFileTemplate:h.versionFileTemplate??y,enabled:h.enabled??!0}),{enableProxyCache:s,proxyCacheTTL:n,disableSSLValidation:a,imageOptimizer:w,templateLess:l,miHudLess:o,outDir:p,distZip:m,versionPlugin:v,syncBackupsDir:u,v7Features:g,personalAccessToken:f,portalPageId:r,integrateMiTopBar:c,...e}},exports.urlReplacer=$,exports.vitePPDev=function(e){const{templateName:t,templateLess:r,backendBaseURL:s,miHudLess:n,portalPageId:a,appId:i,enableProxyCache:o,proxyCacheTTL:c,disableSSLValidation:l,distZip:p,syncBackupsDir:d,v7Features:h,personalAccessToken:u}=e||{};let g=!0;process.cwd();const f=i??a;return{name:"vite-pp-dev",apply:"serve",config:e=>{const n=function(e){return[Pe(e.base,e=>"string"==typeof e&&e.length>0&&"/"!==e,'Server base path cannot be empty or "/"'),Pe(e.port,e=>void 0===e||"number"==typeof e&&e>0&&e<65536,"Server port must be a valid port number (1-65535)")].find(e=>!e.isValid)||{isValid:!0}}({base:e.base||"",...e.server});if(!n.isValid)throw new Error(n.error);return e.clientInjectionPlugin={backendBaseURL:s,portalPageId:f,templateLess:r,v7Features:h},h&&(e.base=`/pl/${t}`),e},transformIndexHtml:async(e,t)=>{const r={html:e,tags:[]};return g&&(g=!1,r.tags.push({tag:"script",injectTo:"body",children:`${Math.random()}`})),r},configureServer:a=>{let i=a.config.base;i.endsWith("/")||(i+="/");const g=i.substring(0,i.lastIndexOf("/"));if(a.middlewares.use(pe(i,t)),s){const w=new URL(s).host,y={headers:{host:w,referer:s,origin:s.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},portalPageId:f,appId:f,templateLess:r,disableSSLValidation:l,v7Features:h,personalAccessToken:u??process.env.MI_ACCESS_TOKEN},v=[Pe((m=y).headers,e=>"object"==typeof e&&"string"==typeof e.host&&"string"==typeof e.referer&&"string"==typeof e.origin,"MiAPI headers must be properly configured"),Pe(m.portalPageId,e=>void 0===e||"number"==typeof e&&e>0,"MiAPI portalPageId must be a positive number if provided"),Pe(m.appId,e=>void 0===e||"number"==typeof e&&e>0,"MiAPI appId must be a positive number if provided"),Pe(m.personalAccessToken,e=>void 0===e||"string"==typeof e,"MiAPI personalAccessToken must be a string if provided")].find(e=>!e.isValid)||{isValid:!0};if(!v.isValid)throw new Error(v.error);const b=new q(s,y);if(o){let e=+c;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const t={devServer:a,ttl:e},r=function(e){return[Pe(e.ttl,e=>"number"==typeof e&&e>0,"Proxy cache TTL must be a positive number")].find(e=>!e.isValid)||{isValid:!0}}(t);if(!r.isValid)throw new Error(r.error);a.middlewares.use(ee(t))}const k=new RegExp(`^((${i})|/)$`);a.middlewares.use(we(k,b,Object.assign({},e,{appId:f,portalPageId:f}))),a.middlewares.use(N({baseURL:s,proxyIgnore:["/@vite","/@metricinsights","/@",g],disableSSLValidation:l,miAPI:b}));const x=(e,t,r,s,n)=>{const a={error:r};s&&(a.details=s),n&&(a.code=n),e.status(t).json(a).end()},P=(e,t,r)=>{a.config.logger.error(`${r} token validation error:`,t);const s=z(t);if(t.tokenErrorInfo){const r=t.tokenErrorInfo;a.config.logger.info(`Using enhanced error info: ${r.code} - ${r.userFriendlyMessage}`);const s=r.status||500,n=r.code,i=r.userFriendlyMessage,o=r.message;x(e,s,i,o,n)}else{let t,n,i;switch(a.config.logger.info(`Using original error info: ${s.code} - ${s.userFriendlyMessage}`),s.code){case"SESSION_EXPIRED":t=412,n="personal"===r?"Personal access token expired":"Session expired",i="personal"===r?"PAT_EXPIRED":"SESSION_EXPIRED";break;case"UNAUTHORIZED":t=401,n="Unauthorized",i="UNAUTHORIZED";break;case"FORBIDDEN":t=403,n="Access forbidden",i="FORBIDDEN";break;default:t=500,n="Internal server error",i=s.code}const o="personal"===r&&"PAT_EXPIRED"===i?"Your personal access token has expired. Please generate a new token from the portal.":"regular"===r&&"SESSION_EXPIRED"===i?"Your portal session has expired. Please refresh your token or re-authenticate.":s.userFriendlyMessage;x(e,t,n,o,i)}return null},T=ke();T.post("/@api/login",async(e,t,r)=>{const{token:s,tokenType:n}=e.body;if(s){if(a.config.logger.info(`Attempting to validate ${n} token...`),"personal"===n){if(!await b.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${s}`},!0).then(async e=>"number"==typeof e.data?.user?.user_id?(b.personalAccessToken=s,a.config.logger.info(`Personal access token validated successfully for user ${e.data.user.user_id}`),e):(x(t,400,"Token expired or invalid"),null)).catch(e=>P(t,e,"personal")))return;I(t,"/",302)}else if("regular"===n){if(!await b.get("/api/user",{"Content-Type":"application/json",Accept:"application/json",Token:s},!0).then(e=>e.data?.users?.length?(b.personalAccessToken=void 0,a.config.logger.info(`Regular token validated successfully for ${e.data.users.length} user(s)`),t.setHeader("set-cookie",e.headers["set-cookie"]??""),e):(x(t,400,"Token expired or invalid"),null)).catch(e=>P(t,e,"regular")))return;I(t,"/",302)}}else x(t,400,"Token is required")}),a.middlewares.use(T);const A=!1!==p?new ce(t,Object.assign({backupDir:d},"object"==typeof p?{distZipFolder:p.outDir,distZipFilename:p.outFileName}:void 0)):void 0;return new Z(a,{distService:A,miAPI:b}),()=>{a.middlewares.use(le(e=>e.split("?")[0].endsWith("index.html"),(e,t)=>Buffer.from($(w,t.headers.host??"",b.buildPage(e,n)))))}}var m}}};
2
+ //# sourceMappingURL=plugin-D-TIdILy.js.map