@metricinsights/pp-dev 1.5.0-beta.33 → 1.5.0-beta.34

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.
Files changed (46) hide show
  1. package/dist/cjs/auth.provider-6rZUaR33.js +2 -0
  2. package/dist/cjs/auth.provider-6rZUaR33.js.map +1 -0
  3. package/dist/cjs/cli.js +1 -1
  4. package/dist/cjs/cli.js.map +1 -1
  5. package/dist/cjs/index-Cc-bAhnE.js +2 -0
  6. package/dist/cjs/index-Cc-bAhnE.js.map +1 -0
  7. package/dist/cjs/index.js +1 -1
  8. package/dist/cjs/internal.middleware-BlM7gqkq.js +2 -0
  9. package/dist/cjs/internal.middleware-BlM7gqkq.js.map +1 -0
  10. package/dist/cjs/{migrate-oVYAMhLH.js → migrate-DDdeB-Fj.js} +2 -2
  11. package/dist/cjs/{migrate-oVYAMhLH.js.map → migrate-DDdeB-Fj.js.map} +1 -1
  12. package/dist/cjs/plugin.js +1 -1
  13. package/dist/cjs/{version-manifest-fusPAO4h.js → version-manifest-DdWlzzZ6.js} +2 -2
  14. package/dist/cjs/{version-manifest-fusPAO4h.js.map → version-manifest-DdWlzzZ6.js.map} +1 -1
  15. package/dist/cjs/{version-plugin-B6tVqztE.js → version-plugin-B1Sb07cW.js} +2 -2
  16. package/dist/cjs/{version-plugin-B6tVqztE.js.map → version-plugin-B1Sb07cW.js.map} +1 -1
  17. package/dist/esm/auth.provider-BFK6x9Df.js +2 -0
  18. package/dist/esm/auth.provider-BFK6x9Df.js.map +1 -0
  19. package/dist/esm/cli.js +1 -1
  20. package/dist/esm/cli.js.map +1 -1
  21. package/dist/esm/index-PvH-M_Io.js +2 -0
  22. package/dist/esm/index-PvH-M_Io.js.map +1 -0
  23. package/dist/esm/index.js +1 -1
  24. package/dist/esm/internal.middleware-CC20He9L.js +2 -0
  25. package/dist/esm/internal.middleware-CC20He9L.js.map +1 -0
  26. package/dist/esm/{migrate-BxksV7OV.js → migrate-C1MkJPzS.js} +2 -2
  27. package/dist/esm/{migrate-BxksV7OV.js.map → migrate-C1MkJPzS.js.map} +1 -1
  28. package/dist/esm/plugin.js +1 -1
  29. package/dist/esm/version-manifest-BVgENnKn.js +2 -0
  30. package/dist/esm/{version-manifest-CGzLQLmu.js.map → version-manifest-BVgENnKn.js.map} +1 -1
  31. package/dist/esm/{version-plugin-Byv2M38F.js → version-plugin-CA9HNV-6.js} +2 -2
  32. package/dist/esm/{version-plugin-Byv2M38F.js.map → version-plugin-CA9HNV-6.js.map} +1 -1
  33. package/package.json +1 -1
  34. package/dist/cjs/auth.provider-C3O8wdGc.js +0 -2
  35. package/dist/cjs/auth.provider-C3O8wdGc.js.map +0 -1
  36. package/dist/cjs/index-DnVkH9ZF.js +0 -2
  37. package/dist/cjs/index-DnVkH9ZF.js.map +0 -1
  38. package/dist/cjs/internal.middleware-63EM6Z98.js +0 -2
  39. package/dist/cjs/internal.middleware-63EM6Z98.js.map +0 -1
  40. package/dist/esm/auth.provider-sKqGOS5N.js +0 -2
  41. package/dist/esm/auth.provider-sKqGOS5N.js.map +0 -1
  42. package/dist/esm/index-DEFt8X6C.js +0 -2
  43. package/dist/esm/index-DEFt8X6C.js.map +0 -1
  44. package/dist/esm/internal.middleware-BVjskCUz.js +0 -2
  45. package/dist/esm/internal.middleware-BVjskCUz.js.map +0 -1
  46. package/dist/esm/version-manifest-CGzLQLmu.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth.provider-C3O8wdGc.js","sources":["../../../src/constants.ts","../../../src/lib/logger.ts","../../../src/lib/helpers/color.helper.ts","../../../src/lib/output-path.ts","../../../src/lib/pp-dev-config.ts","../../../src/lib/dev-panel.ts","../../../src/lib/helpers/origin-guard.ts","../../../src/lib/auth.provider.ts"],"sourcesContent":[null,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","DEFAULT_LEVEL","current","shared","active","level","logger","createViteLogger","createLogger","undefined","info","msg","options","warn","warnOnce","error","clearScreen","type","hasErrorLogged","hasWarned","value","colors","createColors","normalizeRelativeOutputPath","relativePath","optionName","includes","path","posix","isAbsolute","win32","root","Error","normalized","normalize","replace","startsWith","createDefaultZipFileName","appName","DEV_PANEL_POSITIONS","MAX_TIMER_DELAY_MS","validatePPDevConfig","config","templateName","miMode","mi","mode","appType","app","apiVersion","miUrl","url","process","env","MI_BACKEND_URL","maxBackups","sync","Number","isInteger","stringify","buildTimeoutMs","include","console","id","devPanel","position","join","allowedHosts","server","Array","isArray","every","host","trim","normalizePPDevConfig","proxy","build","inspector","users","miHudLess","integrateMiTopBar","addSharedComponentsScripts","addRootElement","templateLess","resolvedName","defaultVersionFileTemplate","distZip","zipCfg","zip","versionPlugin","outFileName","outDir","fileName","inDir","vfCfg","versionFile","imageOptimizer","versionFileTemplate","enabled","fileNameTemplate","imgCfg","imageOptimisations","backendBaseURL","appId","enableProxyCache","cache","proxyCacheTTL","cacheTtl","disableSSLValidation","tls","allowSelfSigned","syncBackupsDir","backupsDir","syncMaxBackups","syncBuildTimeoutMs","v7Features","personalAccessToken","token","MI_ACCESS_TOKEN","inspectorEnabled","inspectorMaxMemory","maxMemory","inspectorCaptureLimit","captureLimit","devPanelPosition","devPanelHidden","hidden","devPanelAutoHide","autoHide","persistUsers","persist","map","toLowerCase","CLIENT_DIST_DIR","dirname","TEMPLATE_PATH","compiledTemplate","getDevPanelAssetPaths","base","css","js","renderDevPanelMarkup","data","templateContent","fs","encoding","ejs","compile","openDelimiter","closeDelimiter","async","rmWhitespace","compileDebug","getTemplate","template","canSync","CONTENT_TYPES","SAFE_METHODS","Set","exactAllowedHosts","filter","crossOriginReason","req","origin","headers","originUrl","hostname","endsWith","test","requestHost","scheme","normalizeHost","protocol","fetchSite","has","method","AuthProvider","state","isAuthenticated","isRedirected","listeners","getState","this","setAuthenticated","authenticated","notifyListeners","setRedirected","redirected","updateState","updates","reset","subscribe","listener","add","delete","forEach","stack","message","String","authProvider","assetPrefix","allowed","res","next","pathname","split","slice","length","filePath","readFile","err","content","statusCode","setHeader","extname","end","reason","status","json","html","panelMarkup","linkTag","bodyPrepend","result","linkInjected","headEnd","head","bodyStart","named","trimmed","indexOf","isIP","ip","readHostHeader","some","matchesAllowedHost","directory","safeRelativePath","resolvedDirectory","resolvedFile","relativeToDirectory","relative","sep","projectRoot"],"mappings":"0eAIMA,EAAkBC,EAAAA,QAEC,oBAAfC,YAA8BA,YAAeC,EAAAA,cAAc,oBAAAC,SAAAC,QAAA,OAAAC,cAAAJ,YAAAK,KAAAC,GAAA,WAAAA,EAAAC,QAAAC,eAAAF,EAAAG,KAAA,IAAAC,IAAA,4BAAAR,SAAAS,SAAAN,MACnE,YAGIO,EAAmBb,EAAAA,QAEA,oBAAfC,YAA8BA,YAAeC,EAAAA,cAAc,oBAAAC,SAAAC,QAAA,OAAAC,cAAAJ,YAAAK,KAAAC,GAAA,WAAAA,EAAAC,QAAAC,eAAAF,EAAAG,KAAA,IAAAC,IAAA,4BAAAR,SAAAS,SAAAN,MACnE,SAGWQ,EAAqBC,EAAAA,WAAWf,UAAQD,EAAiB,iBAClEA,EACAc,EAESG,EAAsBhB,EAAAA,QAAQc,EAAoB,0BAEzDG,QAAEA,EAAOC,KAAEA,GAASC,KAAKC,MAAMC,EAAAA,aAAarB,EAAAA,QAAQc,EAAoB,iBAAiBQ,YAElFC,EAAUN,EACVO,EAAeN,ECvBtBO,EAA0B,OAEhC,IAAIC,EACAC,EAEJ,SAASC,IAGP,OAFAF,IAAY,CAAEG,MAAOJ,EAAeK,OAAQC,EAAAA,aAAiBN,IAEtDC,EAAQI,MACjB,CAUM,SAAUE,EAAaH,GAoB3B,YAnBcI,IAAVJ,GAAuBA,IAAUH,GAASG,QAC5CH,EAAU,CAAEG,Q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T,uCAnBoCI,EAAqBxJ,EAAgBE,GACvE,OAAOlE,EAAKnD,QAAQ2Q,EAAatJ,GAASF,EAC5C"}
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("child_process"),t=require("./auth.provider-C3O8wdGc.js"),n=require("node:module"),i=require("vite"),r=require("fs"),o=require("path"),s=require("url");require("./helpers.js");var a="undefined"!=typeof document?document.currentScript:null;const c=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function l(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 p=l(o),u=c(o),f=i.normalizePath(p.join(t.PP_DEV_PACKAGE_DIR,"dist/client")),d=new RegExp(`^\\/?${t.PACKAGE_NAME}\\/client\\/(.*)$`);const m=(e,t)=>` * ${t}`;function v(e){return`/*!\n${"***** DO NOT EDIT THIS CODE! *****\n***** ------- *****".replace(/^(.*)$/gm,m)}\n */`}async function _(){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 P=()=>n.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index-DnVkH9ZF.js",document.baseURI).href);let g=new Set;function E(e="development",t=process.cwd()){for(const e of g)delete process.env[e];const n=new Set(Object.keys(process.env).filter(e=>e.startsWith("MI_"))),r=i.loadEnv(e,t,"MI_");for(const[e,t]of Object.entries(r))process.env[e]=t;return g=new Set(Object.keys(r).filter(e=>!n.has(e))),r}const h=Object.freeze({__proto__:null,loadPPDevEnv:E}),y=Symbol.for("@metricinsights/pp-dev:withPPDev");const T=new Map,D=new Map;function I(e=process.cwd()){const t=Date.now(),n=u.resolve(e),i=D.get(n);if(i&&t-i.timestamp<6e4)return i.data;try{const e=JSON.parse(r.readFileSync(u.resolve(n,"package.json"),{encoding:"utf-8",flag:"r"}));return D.set(n,{data:e,timestamp:t}),e}catch{const e={};return D.set(n,{data:e,timestamp:t}),e}}let j=null;const b="__pp_dev_injected_dirname",R="__pp_dev_injected_filename",w="__pp_dev_injected_import_meta_url",O={__dirname:b,__filename:R,"import.meta.url":w,"import.meta.dirname":b,"import.meta.filename":R},$={name:"pp-dev:config-module-location",setup(e){e.onLoad({filter:/\.([cm]?[jt]s|[jt]sx)$/},e=>{const t=r.readFileSync(e.path,"utf-8").replace(/^#![^\r\n]*/,"");return{contents:`const ${b} = ${JSON.stringify(u.dirname(e.path))};const ${R} = ${JSON.stringify(e.path)};const ${w} = ${JSON.stringify(s.pathToFileURL(e.path).href)};`+t,loader:e.path.endsWith(".tsx")?"tsx":e.path.endsWith(".jsx")?"jsx":/ts$/.test(e.path)?"ts":"js"}})}};async function F(e,t){const n=`bundled:${e}`,i=T.get(n);if(i&&Date.now()-i.timestamp<3e4)return i.data;let o=!1;if(/\.m[jt]s$/.test(e))o=!0;else if(/\.c[jt]s$/.test(e))o=!1;else{const e=I(t);o=!!e&&"module"===e.type}const a=await async function(){return j||(j=await(import("esbuild"))),j}(),c=await a.build({absWorkingDir:t,entryPoints:[e],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:o?"esm":"cjs",mainFields:["main"],sourcemap:"inline",metafile:!0,plugins:[$],define:O,...o?{banner:{js:"import { createRequire as __ppDevCreateRequire } from 'node:module';const require = __ppDevCreateRequire(import.meta.url);"}}:{}}),{text:l}=c.outputFiles[0],p=`${`pp-config.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.${o?"mjs":"cjs"}`,f=u.resolve(t,p),d=s.pathToFileURL(f).toString();r.writeFileSync(f,l);let m={};try{const t=(await(import(d))).default;m=t?.default||t,T.set(n,{data:m,timestamp:Date.now(),filePath:e})}finally{try{r.unlinkSync(f)}catch{}}return m}async function S(e){const t=`json:${e}`,n=T.get(t);if(n&&Date.now()-n.timestamp<3e4)return n.data;const i=JSON.parse(r.readFileSync(e,{encoding:"utf-8"}));return T.set(t,{data:i,timestamp:Date.now(),filePath:e}),i}const A=new Map;function N(e=process.cwd()){return I(e)}async function x(e=process.cwd()){const n=u.resolve(e),i=function(e){const t=Date.now(),n=A.get(e);if(n&&t-n.timestamp<1e4)return n.files;const i=/\.config\.(([cm]?ts)|([cm]?js)|(json))$/,o=r.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isFile()&&i.test(e.name)).map(e=>e.name);return A.set(e,{files:o,timestamp:t}),o}(n);let o={},s=!1;const a=await async function(e,t,n){for(const i of t)if(e.includes(i)){const e=u.resolve(n,i);if(/\.[cm]?[jt]s$/i.test(i))return await F(e,n);if(i.endsWith(".json"))return await S(e)}return null}(i,t.PP_DEV_CONFIG_NAMES,n);a&&(o=a,s=!0);const c=I(n)["pp-dev"];return s||!c||"object"!=typeof c||Array.isArray(c)||(o=c),o}const L=Object.freeze({__proto__:null,clearConfigCache:function(){T.clear(),D.clear(),A.clear()},getConfig:x,getPkg:N});function C(e){if(void 0!==e)return"1"===e||"true"===e.toLowerCase()||"0"!==e&&"false"!==e.toLowerCase()&&void 0}function V(e,n,i){if(!1===n.distZipEnabled)return!1;if(!0!==n.distZipEnabled&&void 0===n.distZipDir&&void 0===n.distZipFilename)return!1!==e&&{...e,outFileName:t.normalizeRelativeOutputPath(e.outFileName,"ZIP output file name")};const r=!1===e?{outFileName:i,outDir:"dist-zip"}:e,o=n.distZipFilename??r.outFileName;return{...r,...void 0!==n.distZipDir?{outDir:n.distZipDir}:{},outFileName:t.normalizeRelativeOutputPath(o,"ZIP output file name")}}function M(e,n){if(!1===n.versionManifestEnabled)return!1;if(!0!==n.versionManifestEnabled&&void 0===n.versionFileTemplate)return!1!==e&&void 0!==e.versionFileTemplate?{...e,versionFileTemplate:t.normalizeRelativeOutputPath(e.versionFileTemplate,"VERSION file name template")}:e;const i=!1===e?{enabled:!0}:e,r=n.versionFileTemplate??i.versionFileTemplate,o=void 0!==r?t.normalizeRelativeOutputPath(r,"VERSION file name template"):void 0;return{...i,enabled:!0,...void 0!==o?{versionFileTemplate:o}:{}}}const U=new Set(["mi","app","proxy","build","sync","inspector","devPanel","users","server"]);function H(t){if("string"==typeof t)return t;if(t&&"object"==typeof t&&"url"in t&&"string"==typeof t.url)return t.url;const n=["CI_REPOSITORY_URL","GIT_URL","BUILD_REPOSITORY_URI","CI_PROJECT_URL","BITBUCKET_GIT_HTTP_ORIGIN","BUILDKITE_REPO"];for(const e of n){const t=process.env[e];if("string"==typeof t&&t.trim())return t}const i=process.env.GITHUB_REPOSITORY;if("string"==typeof i&&i.trim()){return`${(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,"")}/${i.replace(/^\/+/,"")}`}const r=process.env.CI_PROJECT_PATH;if("string"==typeof r&&r.trim()){return`${(process.env.CI_SERVER_URL||"https://gitlab.com").replace(/\/+$/,"")}/${r.replace(/^\/+/,"")}`}const o=process.env.BITBUCKET_REPO_FULL_NAME;if("string"==typeof o&&o.trim())return`https://bitbucket.org/${o.replace(/^\/+/,"")}`;const s=process.env.TRAVIS_REPO_SLUG;if("string"==typeof s&&s.trim())return`https://github.com/${s.replace(/^\/+/,"")}`;try{const t=e.execSync("git config --get remote.origin.url",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t)return t}catch{}}function Z(e){return e?.ppDev||{}}exports.applyDistZipOverride=V,exports.applyVersionManifestOverride=M,exports.clearWithPPDevHandoff=function(){delete globalThis[y]},exports.config=L,exports.env=h,exports.getNextVersion=async function(){try{const e=P()("next/package.json");return"string"==typeof e.version?e.version:null}catch{return null}},exports.getPPDevConfigFromNextConfig=Z,exports.getViteConfig=async function(e,n={}){const r=n.root??process.cwd();E(n.mode,r);const o=N(r),s=await x(r);t.validatePPDevConfig(s,o.name);const a=t.normalizePPDevConfig(s,o.name),{templateName:c}=a;e&&(a.distZip=V(a.distZip,e,t.createDefaultZipFileName(c)),a.versionPlugin=M(a.versionPlugin,e));const{default:l}=await Promise.resolve().then(()=>require("./plugin.js")),u=[l(a),{name:"pp-dev:client",apply:"serve",config:e=>(e.optimizeDeps?.exclude?.push(`${t.PACKAGE_NAME}/client`),e),resolveId(e){const t=e.match(d);if(t){const e=i.normalizePath(p.join(f,t[1]));return e.startsWith(`${f}/`)?{id:e}:null}},transformIndexHtml:async(e,n)=>{const i=n.server?.config.base||"",r=t.getDevPanelAssetPaths(i),o={html:e,tags:[{tag:"link",injectTo:"head",attrs:{rel:"stylesheet",href:r.css}}]},{templateLess:s=!1,...a}=n.server?.config.clientInjectionPlugin||{};return o.tags.push({tag:"div",injectTo:"body-prepend",children:t.renderDevPanelMarkup({templateLess:s,...a})}),o.tags.push({tag:"script",injectTo:"body-prepend",attrs:{src:r.js,type:"module"}}),o},configureServer(e){const n=i.normalizePath(p.resolve(e.config.root,p.dirname(t.PP_DEV_CLIENT_ENTRY)));e.config.server?.fs?.allow&&e.config.server.fs.allow.push(n)}}],{outDir:m,distZip:_,versionPlugin:P,imageOptimizer:g,templateLess:h,integrateMiTopBar:y,allowedHosts:T}=a;if(y&&u.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}}}(y)),g){const{ViteImageOptimizer:e}=await(import("vite-plugin-image-optimizer"));u.push(e("object"==typeof g?g:void 0))}if(P){const{versionPlugin:e}=await Promise.resolve().then(()=>require("./version-plugin-B6tVqztE.js"));u.push(e({outDir:m,packageVersion:o.version??"0.0.0",packageRepositoryUrl:H(o.repository),..."object"==typeof P?P:{}}))}if(_){const{default:e}=await(import("vite-plugin-zip-pack"));u.push({...e("object"==typeof _?_:{outFileName:t.createDefaultZipFileName(c)}),enforce:"post"})}return{base:h?`${t.PATH_PAGE_PREFIX}/${c}`:`${t.PATH_TEMPLATE_PREFIX}/${c}`,server:{port:3e3,...!0===T||T.length>0?{allowedHosts:T}:{}},build:{minify:!1,assetsInlineLimit:4096,rollupOptions:{output:{banner:v}},outDir:m},css:{modules:{localsConvention:"dashes"}},ppDevConfig:a,plugins:u}},exports.isNextAvailable=async function(){try{return P().resolve("next"),!0}catch{return!1}},exports.loadPPDevEnv=E,exports.readWithPPDevHandoff=function(){return globalThis[y]},exports.resolveBuildCliOverrides=function(e){return{distZipEnabled:e.distZip??C(process.env.PP_DEV_DIST_ZIP),distZipDir:e.distZipDir??process.env.PP_DEV_DIST_ZIP_DIR,distZipFilename:e.distZipFilename??process.env.PP_DEV_DIST_ZIP_FILENAME,versionManifestEnabled:e.versionManifest??C(process.env.PP_DEV_VERSION_MANIFEST),versionFileTemplate:e.versionFileTemplate??process.env.PP_DEV_VERSION_FILE_TEMPLATE}},exports.safeNextImport=_,exports.withPPDev=function(e,n){return async(i,r={})=>{try{const{constants:s}=await _(),{PHASE_DEVELOPMENT_SERVER:a,PHASE_PRODUCTION_BUILD:c}=s;i!==c||process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR]||t.createLogger().warn(t.colors.yellow('⚠ Building with plain `next build`. Use `pp-dev next-build` instead to get VERSION/BUILD-MANIFEST/zip build output in the same format as `pp-dev build` (see the "Next.js Build" section in the pp-dev README).'));const l=await x(),p=N().name,u="function"==typeof e?await e(i,r):e,f=function(...e){const t={},n=t;for(const t of e)if(t)for(const[e,i]of Object.entries(t))void 0!==i&&(U.has(e)&&i&&"object"==typeof i&&!Array.isArray(i)?n[e]={...n[e]??{},...i}:n[e]=i);return t}(l,Z(u),n);t.validatePPDevConfig(f,p);const d=t.normalizePPDevConfig(f,p),{templateLess:m,v7Features:v}=d,P=i===a,g=function(e,n,i,r){return i?r?n?`${t.PATH_PAGE_PREFIX}/${e}`:`${t.PATH_TEMPLATE_LOCAL_PREFIX}/${e}`:n?`${t.PATH_PAGE_PREFIX}/${e}`:`${t.PATH_TEMPLATE_PREFIX}/${e}`:`${t.PATH_PAGE_PREFIX}/${e}`}(d.templateName,m,P,v),E={basePath:g,trailingSlash:!!P||void 0};if(!m){const e=P&&v?t.PATH_TEMPLATE_LOCAL_PREFIX:t.PATH_TEMPLATE_PREFIX;E.assetPrefix=`${e}/${d.templateName}`}const h=Object.assign({},E,u),T=t.exactAllowedHosts(d.allowedHosts);P&&T.length>0&&(h.allowedDevOrigins=[...h.allowedDevOrigins??[],...T]);const D=process.env[t.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR];return i===c&&D&&(h.distDir=D),Object.defineProperty(h,"ppDev",{value:f,enumerable:!1,configurable:!0}),Object.defineProperty(h,"ppDevWrapped",{value:!0,enumerable:!1,configurable:!0}),o={ppDev:f,wrapped:!0},globalThis[y]=o,h}catch(e){throw t.createLogger().error("Error in withPPDev:",{error:e instanceof Error?e:new Error(String(e))}),e}var o}};
2
- //# sourceMappingURL=index-DnVkH9ZF.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-DnVkH9ZF.js","sources":["../../../src/plugins/client-injection-plugin.ts","../../../src/banner/header.ts","../../../src/lib/next-import.ts","../../../src/lib/env.ts","../../../src/lib/next-config-handoff.ts","../../../src/config.ts","../../../src/lib/build-cli-overrides.ts","../../../src/index.ts","../../../src/plugins/mi-topbar-plugin.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null],"names":["CLIENT_DIST_DIR","normalizePath","path","join","PP_DEV_PACKAGE_DIR","PACKAGE_REGEXP","RegExp","PACKAGE_NAME","replacer","substring","$1","header","_chunk","replace","async","safeNextImport","next","constants","Promise","all","default","error","Error","requireFromPPDev","createRequire","previouslyLoadedKeys","Set","loadPPDevEnv","mode","envDir","process","cwd","key","env","fromEnvironment","Object","keys","filter","startsWith","loadEnv","value","entries","has","HANDOFF_KEY","Symbol","for","configCache","Map","packageJsonCache","getPackageJson","projectRoot","now","Date","root","resolve","cached","get","timestamp","data","JSON","parse","readFileSync","encoding","flag","set","empty","esbuildModule","MODULE_LOCATION","MODULE_LOCATION_DEFINE","__dirname","__filename","moduleLocationPlugin","name","setup","build","onLoad","args","contents","stringify","dirname","pathToFileURL","href","loader","endsWith","test","loadBundledConfig","filePath","cacheKey","isESM","pkg","type","esbuild","getEsbuild","result","absWorkingDir","entryPoints","outfile","write","target","platform","bundle","packages","format","mainFields","sourcemap","metafile","plugins","define","banner","js","text","code","outputFiles","fileNameTmp","Math","random","toString","slice","tempFilePath","fileUrl","writeFileSync","config","conf","unlinkSync","loadJSONConfig","dirContentCache","getPkg","getConfig","dirContent","files","endsWithRegExp","readdirSync","withFileTypes","isFile","map","getDirectoryContent","configFound","newConfig","dirFiles","configNames","configName","includes","configPath","loadConfig","PP_DEV_CONFIG_NAMES","packageConfig","Array","isArray","clear","parseBooleanFlag","undefined","toLowerCase","applyDistZipOverride","base","overrides","defaultFileName","distZipEnabled","distZipDir","distZipFilename","outFileName","normalizeRelativeOutputPath","baseConfig","outDir","applyVersionManifestOverride","versionManifestEnabled","versionFileTemplate","enabled","normalizedVersionFileTemplate","PP_DEV_CONFIG_GROUPS","resolveRepositoryUrl","repository","url","directCiRepositoryUrlEnvVars","variableName","ciRepositoryUrl","trim","githubRepository","GITHUB_REPOSITORY","GITHUB_SERVER_URL","gitlabProjectPath","CI_PROJECT_PATH","CI_SERVER_URL","bitbucketRepositoryFullName","BITBUCKET_REPO_FULL_NAME","travisRepositorySlug","TRAVIS_REPO_SLUG","gitRemoteOriginUrl","execSync","stdio","getPPDevConfigFromNextConfig","nextConfig","ppDev","globalThis","nextPkg","version","environment","ppDevConfig","validatePPDevConfig","normalizedPPDevConfig","normalizePPDevConfig","templateName","distZip","createDefaultZipFileName","versionPlugin","vitePPDev","then","require","apply","optimizeDeps","exclude","push","resolveId","source","match","resolvedId","id","transformIndexHtml","html","ctx","server","assetPaths","getDevPanelAssetPaths","tags","tag","injectTo","attrs","rel","css","templateLess","panelOptions","clientInjectionPlugin","children","renderDevPanelMarkup","src","configureServer","clientDir","PP_DEV_CLIENT_ENTRY","fs","allow","imageOptimizer","integrateMiTopBar","allowedHosts","addRootElement","addSharedComponentsScripts","defer","miTopBarPlugin","ViteImageOptimizer","versionPluginFn","packageVersion","packageRepositoryUrl","zipPack","enforce","PATH_PAGE_PREFIX","PATH_TEMPLATE_PREFIX","port","length","minify","assetsInlineLimit","rollupOptions","output","modules","localsConvention","options","PP_DEV_DIST_ZIP","PP_DEV_DIST_ZIP_DIR","PP_DEV_DIST_ZIP_FILENAME","versionManifest","PP_DEV_VERSION_MANIFEST","PP_DEV_VERSION_FILE_TEMPLATE","nextjsConfig","phase","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_BUILD","PP_DEV_NEXT_BUILD_ENV_VAR","createLogger","warn","colors","yellow","nextConfiguration","mergedConfig","configs","merged","mutableMerged","mergePPDevConfigs","normalized","v7Features","isDevelopment","basePath","PATH_TEMPLATE_LOCAL_PREFIX","createBasePath","trailingSlash","prefix","assetPrefix","assign","tunnelOrigins","exactAllowedHosts","allowedDevOrigins","buildDistDir","PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR","distDir","defineProperty","enumerable","configurable","handoff","wrapped","String"],"mappings":"2fAuBMA,EAAkBC,EAAAA,cAAcC,EAAKC,KAAKC,EAAAA,mBAAoB,gBAC9DC,EAAiB,IAAIC,OAAO,QAAQC,EAAAA,iCCtB1C,MAIMC,EAAW,CAACC,EAAmBC,IAAe,MAAYA,IAElD,SAAAC,EAAWC,GAIvB,MAAO,QAHS,0DAGUC,QAAQ,WAAYL,SAChD,CCKOM,eAAeC,IACpB,IACE,MAAOC,EAAMC,SAAmBC,QAAQC,IAAI,QAAQ,eAAgB,uBAEpE,MAAO,CACLH,KAAMA,EAAKI,QACXH,YAEJ,CAAE,MAAOI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M,QAAUF,GAGnBtQ,OAAOyQ,eAAe/M,EAAQ,QAAS,CACrCrD,MAAO+O,EACPsB,YAAY,EACZC,cAAc,IAEhB3Q,OAAOyQ,eAAe/M,EAAQ,eAAgB,CAAErD,OAAO,EAAMqQ,YAAY,EAAOC,cAAc,IHza7DC,EG2aV,CAAEhH,MAAOwF,EAAcyB,SAAS,GH1a1DhH,WAA6BrJ,GAAeoQ,EG4alClN,CACT,CAAE,MAAOxE,GAKP,MAJe6P,EAAAA,eAER7P,MAAM,sBAAuB,CAAEA,MAAOA,aAAiBC,MAAQD,EAAQ,IAAIC,MAAM2R,OAAO5R,MAEzFA,CACR,CHpbE,IAAiC0R,EGsbvC"}
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("axios"),t=require("node:http"),s=require("node:https"),r=require("./version-manifest-fusPAO4h.js"),n=require("./auth.provider-C3O8wdGc.js"),i=require("url"),a=require("http-proxy-middleware"),o=require("node:string_decoder"),c=require("zlib"),l=require("fs"),d=require("path"),u=require("node:crypto"),p=require("crypto"),h=require("process"),g=require("os"),f=require("jszip"),m=require("node:fs"),y=require("node:fs/promises"),w=require("child_process"),v=require("module"),b=require("node:os"),k=require("node:path"),$=require("express");var x="undefined"!=typeof document?document.currentScript:null;const S=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function A(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const s in e)t[s]=e[s];return t.default=e,Object.freeze(t)}const E=S(e),T=S(t),I=S(s),P=A(l),L=A(d),j=A(p),N=A(h),R=A(g),C=S(f),O=A(m),B=S(m),F=A(y),M=A(w),D=S(b),U=S(k),_=S($),H=L.dirname(n.PP_DEV_CLIENT_ENTRY),V={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function q(e,t){const s=t.clientDir??H,r=new Set([`${t.name}.js`,`${t.name}.css`,`${t.name}.js.map`,`${t.name}.css.map`]);e.get(t.path,(e,r)=>{P.readFile(L.join(s,`${t.name}.html`),"utf-8",(e,s)=>{if(e)return void r.status(500).type("text/plain").end(`${t.name} page not built (${e.message})`);const n=t.values?.()??{};r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-cache"),r.end(s.replace(/\{\{(\w+)\}\}/g,(e,t)=>n[t]??e))})}),e.get(`${t.path}/:file`,(e,t,n)=>{const i=e.params.file;r.has(i)?P.readFile(L.join(s,i),(e,s)=>{e?n():(t.setHeader("Content-Type",V[L.extname(i)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(s))}):n()})}function z(e,t,s={}){switch(t){case"gzip":return c.unzipSync(e,s);case"br":return c.brotliDecompressSync(e,s);case"deflate":return c.inflateSync(e,s);default:return e}}const W="/@pp-dev/inspector",J=new WeakMap;function K(e){const t=Array.isArray(e)?e[0]:e;return"string"==typeof t?t:void 0}function G(e,t,s=10485760,r=H){const n=J.get(e);if(n)return n.store=t,void(n.captureLimit=s);const i={store:t,captureLimit:s};J.set(e,i),e.get("/@api/requests",(e,t)=>{const{store:s}=i,r=K(e.query.limit),n=K(e.query.offset),a=K(e.query.method),o=K(e.query.search),c=void 0!==r?parseInt(r,10):void 0,l=s.list({limit:Number.isFinite(c)?c:500,offset:void 0!==n&&Number.isFinite(parseInt(n,10))?parseInt(n,10):void 0,method:a,search:o});t.json({requests:l,total:s.size,memoryUsage:s.memoryUsage,maxMemory:s.maxMemory})}),e.get("/@api/requests/stats",(e,t)=>{const{store:s}=i;t.json({total:s.size,memoryUsage:s.memoryUsage,maxMemory:s.maxMemory,memoryUsageFormatted:Z(s.memoryUsage),maxMemoryFormatted:Z(s.maxMemory)})}),e.get("/@api/requests/:id",(e,t)=>{const s=i.store.get(e.params.id);if(!s)return void t.status(404).json({error:"Not found",id:e.params.id});const r=X(s.requestHeaders["content-type"]),n=X(s.responseHeaders["content-type"]),a=s.responseBody?function(e,t,s){const r=Array.isArray(t)?t.join(", "):String(t??"");try{return z(e,r.trim().toLowerCase(),{maxOutputLength:s})}catch(t){return t instanceof RangeError?null:e}}(s.responseBody,s.responseHeaders["content-encoding"],i.captureLimit):null;t.json({id:s.id,timestamp:s.timestamp,method:s.method,url:s.url,statusCode:s.statusCode,duration:s.duration,source:s.source,user:s.user,requestHeaders:s.requestHeaders,requestBody:s.requestBody?s.requestBody.toString("base64"):null,requestBodySize:s.requestBody?.byteLength??0,requestBodyTruncated:s.requestBodyTruncated,requestContentType:r,responseHeaders:s.responseHeaders,responseBody:a?a.toString("base64"):null,responseBodySize:s.responseBody?.byteLength??0,responseBodyTruncated:s.responseBodyTruncated||null!==s.responseBody&&null===a,responseContentType:n})}),e.delete("/@api/requests",(e,t)=>{i.store.clear(),t.json({ok:!0})}),q(e,{path:W,name:"request-inspector",clientDir:r,values:()=>({captureLimit:String(i.captureLimit)})})}function X(e){return Array.isArray(e)?e[0]??"":String(e??"")}function Z(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/1073741824).toFixed(2)} GB`}class Y{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 Q extends Y{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.download(this.getDownloadUrl(e),t)}async uploadPageAssets(e,t,s){return this.upload(this.getUploadUrl(e),t,s)}async downloadTemplateAssets(e,t){return this.download(this.getDownloadTemplateUrl(e),t)}async uploadTemplateAssets(e,t,s){return this.upload(this.getUploadTemplateUrl(e),t,s)}async download(e,t){return this.axios.get(e,{withCredentials:!0,headers:Object.assign({},t,{accept:"*/*"}),responseType:"arraybuffer"}).then(e=>e.data)}async upload(e,t,s){const r=new FormData;return r.append("file",new File([new Uint8Array(t)],"file.zip",{type:"application/zip"}),"file.zip"),this.axios.post(e,r,{withCredentials:!0,headers:Object.assign({},s,{accept:"application/json","Content-Type":"multipart/form-data",Referer:this.axios.getUri({url:e})})}).then(e=>e.data)}}class ee extends Q{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`}}const te="Something went wrong when fetching page data",se="Something went wrong when fetching page template data",re="Something went wrong when fetching page variables",ne="Something went wrong when checking who the credentials belong to",ie=" The instance may be down or in maintenance mode. Please try again later.",ae=[te,se,re,ne];function oe(){return new Error(`${te}.${ie}`)}function ce(){return new Error(`${se}.${ie}`)}function le(e){return e instanceof Error&&ae.some(t=>e.message.includes(t))}class de extends Y{async getAll(e){const t=(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;if("object"!=typeof t||null===t||!Array.isArray(t.pages))throw oe();return t.pages}async get(e,t){const s=(await this.axios.get(`/api/page/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page||null===s.page)throw oe();return s.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){const s=(await this.axios.post("/api/page",e,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page||null===s.page)throw oe();return s.page}}class ue extends Y{async getAll(e,t){const s=(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;if("object"!=typeof s||null===s||!Array.isArray(s.page_templates))throw ce();return s.page_templates}async get(e,t){const s=(await this.axios.get(`/api/page_template/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page_template||null===s.page_template)throw ce();return s.page_template}}class pe extends Y{async getById(e,t){const s=(await this.axios.get("/api/page_variable",{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"}),params:{page_id:e}})).data;if("object"!=typeof s||null===s)throw new Error(`${re}.${ie}`);return function(e){let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch{throw new TypeError('Page variable response contains invalid JSON in "tags".')}if(!Array.isArray(t))throw new TypeError('Page variable response must contain a "tags" array.');const s=t.findIndex(e=>{return!("object"==typeof(t=e)&&null!==t&&"string"==typeof t.name&&"string"==typeof t.value);var t});if(-1!==s)throw new TypeError(`Page variable response contains a malformed entry at index ${s}.`);return t}(s.tags)}async updateById(e,t,s){await this.axios.put("/api/page_variable",{tags:JSON.stringify(t)},{withCredentials:!0,headers:Object.assign({},s,{accept:"application/json","content-type":"application/json"}),params:{page_id:e}})}}function he(e){if(e.socket?.encrypted)return!0;const t=e.headers?.["x-forwarded-proto"],s=Array.isArray(t)?t[0]:t;return"string"==typeof s&&"https"===s.split(",",1)[0].trim().toLowerCase()}function ge(e,t){const[s,...r]=e.split(";"),n=r.map(e=>e.trim()).filter(e=>{if(!e)return!1;const s=e.split("=",1)[0].trim().toLowerCase();return"domain"!==s&&(t||"secure"!==s)}).map(e=>!t&&/^samesite\s*=\s*none$/i.test(e)?"SameSite=Lax":e);return[s.trim(),...n].join("; ")}const fe="metric_insights_session";function me(e,t){for(const s of e){const e=s.indexOf("=");if(-1!==e&&s.slice(0,e).trim()===t)return s.slice(e+1).trim()}}function ye(e,t){return e?me(e.split(";"),t):void 0}function we(e,t){if(void 0===e||"number"==typeof e)return;return me((Array.isArray(e)?e:[e]).map(e=>e.split(";",1)[0]),t)}function ve(e,t){return void 0===e?e:Array.isArray(e)?e.map(e=>ge(e,t)):ge(e,t)}const be=function(e){const t={personal:{placeholder:"API Token",label:"API Token",path:"/api-token"},regular:{placeholder:"Legacy Token",label:"Legacy Token",path:"/api/get_token"}};function s(s,r,n){const i=t[s],a=document.createElement("a");a.href=`https://${e}${i.path}`,a.target="_blank",a.style.color="#007bff",a.style.textDecoration="none",a.textContent="here",r.placeholder=i.placeholder,n.replaceChildren(`You can get the ${i.label} `,a)}function r(e,t){t.textContent=e,t.classList.add("show")}function n(e){e.classList.remove("show")}function i(e,t,s,i){s.addEventListener("click",async s=>{if(s.preventDefault(),n(i),!t.value.trim())return r(`${t.placeholder} is required`,i),void t.focus();const a=document.getElementById("token-type-switcher"),o=a?.querySelector(".token-type-option.active"),c=o?.dataset.value||"personal";await async function(e,t,s,n){try{s.classList.add("loading");const i=await fetch("/@api/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,tokenType:t}),redirect:"follow"}),a=i.url&&new URL(i.url,window.location.origin);if(!a||a.pathname.startsWith("/login")||a.pathname.startsWith("/@api/"))try{const e=await i.json();r(`Login failed: ${e?.error||"Unknown error occurred"}`,n)}catch(e){r("Login failed: Unable to parse response",n)}else window.location.href=i.url}catch(e){r("Login failed: Network error. Please check your connection.",n)}finally{s.classList.remove("loading")}}(t.value.trim(),c,e,i)}),t.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),s.click())}),t.addEventListener("input",()=>{n(i)})}function a(e){const t=e.firstChild;if(!t)return;const r=t.lastChild?.cloneNode(!0);if(!r)return;r.innerHTML="";const n=r.cloneNode(!0);n.innerText="OR",n.setAttribute("role","separator"),n.setAttribute("aria-label","Alternative login method");const a=r.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"></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>',a.appendChild(o),t.appendChild(n),t.appendChild(a);const l=document.getElementById("token-type-switcher"),d=document.getElementById("helper-token"),u=document.getElementById("token-caption"),p=document.getElementById("helper-token-submit"),h=document.getElementById("error-message"),g=o.querySelector(".helper-login-wrapper");l&&d&&u&&p&&h&&g?(!function(e,t,r){const n=e.querySelectorAll(".token-type-option"),i=e=>{const i=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"),s(i,t,r)};n.forEach(e=>{e.addEventListener("click",e=>{const t=e.currentTarget;i(t)}),e.addEventListener("keydown",t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),i(e))})})}(l,d,u),i(g,d,p,h),s("personal",d,u)):console.error("Failed to find required form elements")}const o='#mi-react-root form:not([id]):has(input[name="login"]):has(input[name="password"])',c=new MutationObserver(e=>{for(const t of e)if("childList"===t.type){const e=document.querySelector(o);if(e){c.disconnect(),a(e);break}}});c.observe(document.body,{childList:!0,subtree:!0});const l=document.querySelector(o);l&&(c.disconnect(),a(l))};function ke(e){const{message:t,response:s}="object"==typeof e&&null!==e?e:{},r="number"==typeof s?.status?s.status:0,n=s?.data?.message;return"string"==typeof n&&n?{status:r,message:n}:"string"==typeof t&&t?{status:r,message:t}:{status:r,message:"string"==typeof e&&e?e:"Unknown error"}}function $e(e){const{status:t,message:s}=ke(e);switch(t){case 412:{const e=s.toLowerCase();return e.includes("session expired")||e.includes("session has expired")?{status:t,message:s,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:s,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:s,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:s,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:s,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"]}}}function xe(e){const{status:t}=ke(e);return 401===t||403===t||412===t}const Se=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ae=new Map,Ee=new Map;const Te=(e,t,s)=>{let r=Ae.get(e);if(!r){const t=/:\d+$/.test(e)?"":"(?::(?<port>\\d+))?";r=new RegExp(`(?<keep>!!)?(?<url>http(?<secure>s)?(?<slashes>:(?:\\\\)?/(?:\\\\)?/)${Se(e)}${t})`,"gi"),Ae.set(e,r)}return s.replace(r,(...e)=>{const{keep:s,url:r,secure:n,slashes:i,port:a}=e.at(-1);return s||a&&a!==(n?"443":"80")?r:`http${i}${t}`})},Ie=(e,t,s)=>{const r=new RegExp(`${e.replace(/\\*\//gi,"\\\\/")}`,"gi"),n=new RegExp(`${e}`,"gi"),i=s.replace(r,t);return i===s?i.replace(n,t):i},Pe=(e,t,s)=>{e.setHeader("location",t),e.statusCode=s,e.end()};function Le(e){return e.split("?")[0]}const je="[DEV PAGE. DO NOT DELETE]",Ne=new Map;class Re{#e;#t;#s=null;#r;#n;#i=!1;#a=null;#o=null;#c;#l;#d;#u;#p;internalPageName;appId;templateLess;assetsApi;pageApi;pageTemplateApi;pageVariableApi;logger;constructor(e,t){const{headers:s={},appId:r,templateLess:i=!0,disableSSLValidation:a=!1,v7Features:o=!1,personalAccessToken:c}=t||{};this.#e=s,this.#n=[],this.#r="",this.#c=o,this.#l=c,this.#d=!1,this.#u=Promise.resolve(!1);const l=`${e}:${a}`;if(Ne.has(l))this.#t=Ne.get(l);else{const t=new I.Agent({keepAlive:!1,...a?{rejectUnauthorized:!1}:{}});this.#t=E.create({baseURL:e,headers:s,timeout:3e4,maxRedirects:5,httpAgent:new T.Agent({keepAlive:!1}),httpsAgent:t}),Ne.set(l,this.#t)}this.appId=r,this.templateLess=i,this.assetsApi=new(o?ee:Q)(this.#t),this.pageApi=new de(this.#t),this.pageTemplateApi=new ue(this.#t),this.pageVariableApi=new pe(this.#t),this.logger=n.createLogger()}async isTemplateLoaded(){return this.#u}get isV710OrHigher(){return this.#d}get v7Features(){return this.#c}get pageId(){return this.appId}#h(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.#l&&(t.authorization=`Bearer ${this.#l}`),t}#g(e){return e.replace(/[.*+?^${}()|[\]\\\/]/g,"\\$&")}get personalAccessToken(){return this.#l}set personalAccessToken(e){this.#l=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.#u||this.#s||(this.#u=new Promise(e=>{this.#p=e})),this.#s)return Promise.resolve(this.#s);if(void 0===this.templateLess&&(this.templateLess=!1),this.#c){const t=await this.pageApi.get(this.appId,this.#h(e)).then(e=>(this.logger.info(n.colors.green("Page fetched")),e)).catch(async t=>{if(this.#p(!1),le(t))throw t;throw await this.pageApi.checkAuth(this.#h(e))?(this.logger.error(n.colors.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 app.id is correct.")):t});return void 0!==t.template_id&&(this.#d=!0),this.internalPageName=t.internal_name,this.#s=this.localTemplateHTML,this.#s=this.#s.replace(/%%PAGE TITLE%%/g,t.name||"Local template"),this.logger.info(n.colors.green("Local page template fetched")),this.#p(!0),this.#s}let t=(await this.pageApi.getAll(this.#h(e)).then(e=>(this.logger.info(n.colors.green("Page list fetched")),e)).catch(async t=>{throw this.#p(!1),await this.pageApi.checkAuth(this.#h(e))?(this.logger.error(n.colors.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===je);return t||(this.logger.warn(n.colors.yellow("Creating dev page template...")),t=await this.pageApi.create({enabled:"Y",name:je,internal_name:"dev-page-template",visible_in_homepage:"Y"},this.#h(e)).then(e=>(this.logger.info(n.colors.green("Dev page created")),e)).catch(e=>{throw this.logger.error(n.colors.red(`Error creating dev page: ${e.message}`)),this.#p(!1),new Error(`Error when creating dev page.\n That can be caused by missing permissions or page with name "${je}" already exists`)})),await this.pageApi.getPageContent(t.internal_name,this.#h(e)).then(e=>(this.#s=e,e)).then(e=>(this.#p(!0),this.logger.info(n.colors.green("Page template fetched")),e)).catch(e=>{throw this.#p(!1),this.logger.error(n.colors.red(`Error fetching page template: ${e.message}`)),new Error("Error fetching page template")})}async getPageVariables(e,t){return void 0===this.appId&&(this.appId=e,this.templateLess=!1),this.#s=await this.getPageTemplate(t),await this.pageApi.get(e,this.#h(t)).then(e=>{const{tags:t="[]",name:s,template:r}=e;if(r&&t){const e=JSON.parse(t);return this.#n=e,this.#i=!0,this.#r=s,e}return this.#n=[],this.#i=!0,this.#r=s,[]}).catch(t=>{if(this.logger.error(n.colors.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 this.logger.warn(`Unauthorized error: ${t}`),new Error(`Current user does not have access to page with id "${e}" on instance ${this.#t.getUri()}`);throw t})}async getLivePageVariables(e=this.#e){if(void 0===this.appId)throw new Error("Cannot fetch live page variables before the page ID is known");const t=this.appId,s=Date.now();this.logger.info(n.colors.cyan(`[page-variables] Fetching live variables for page ID ${t} (page_id lookup)`));const r=await this.pageVariableApi.getById(t,this.#h(e));return this.logger.info(n.colors.green(`[page-variables] Fetched ${r.length} live variable(s) for page ID ${t} in ${Date.now()-s}ms`)),r}async applyPageVariables(e,t=this.#e){if(void 0===this.appId)throw new Error("Cannot apply page variables before the page ID is known");const s=this.appId,r=Date.now();this.logger.info(n.colors.cyan(`[page-variables] Applying ${e.length} variable(s) to page ID ${s} (page_id lookup)`)),await this.pageVariableApi.updateById(s,e,this.#h(t)),this.logger.info(n.colors.green(`[page-variables] Applied variables to page ID ${s} in ${Date.now()-r}ms`))}async listPages(e=this.#e){return this.pageApi.getAll(this.#h(e))}async getPageVariablesFor(e,t=this.#e){return this.pageVariableApi.getById(e,this.#h(t))}get localPageVariables(){return this.templateLess||!this.#i?null:this.#n.map(({name:e,value:t})=>({name:e,value:t}))}get isTemplateLess(){return!!this.templateLess}async reloadPageVariables(e=this.#e){return this.templateLess||void 0===this.appId?null:this.getPageVariables(this.appId,e)}async getPageInfo(e,t){void 0===this.appId&&(this.appId=e);const s=this.#h(t),r=this.appId;try{return this.#c?await this.#f(r,s):await this.#m(r,s)}catch(e){this.#y(e,r)}}async#f(e,t){const s=await this.pageApi.get(e,t);return this.logger.info(n.colors.green("Page fetched")),void 0!==s.template_id&&(this.#d=!0),this.internalPageName=s.internal_name,s}async#m(e,t){return await this.pageApi.get(e,t)}#y(e,t){if(le(e))throw e;if(this.#c&&e.message?.includes("access"))throw new Error("The current user does not have access to this page. Check your configuration to ensure app.id 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(n.colors.red(`Current user does not have access to page with id "${t}" on instance ${this.#t.getUri()}`)),e}buildPage(e,t=!1){let s="string"==typeof e?e:e.toString("utf-8");for(const{regExp:e,value:t}of this.#w())s=s.replace(e,()=>t);if(t){return new(r.getJSDOM())(s).serialize()}const{before:n,after:i}=this.#v();return n+s+i}#w(){return this.#a?.vars!==this.#n&&(this.#a={vars:this.#n,replacements:this.#n.map(({name:e,value:t})=>({regExp:new RegExp(`\\[${this.#g(e)}\\]`,"g"),value:t}))}),this.#a.replacements}#v(){const e=this.#s,t=this.#r;if(this.#o?.template===e&&this.#o.title===t)return this.#o;const s=new(r.getJSDOM())(e),{document:n}=s.window,i="%%PLACEHOLDER%%",a=n.createElement("div");a.innerHTML=i;const o=n.querySelector(".main-side");if(o){const e=o.querySelectorAll("script");e.length?o.insertBefore(a,e.item(e.length-1)):o.append(a)}else{const e=n.createElement("div");e.append(a),n.body.append(e)}const c=n.querySelector("head"),l=c.querySelector("title");if(l)l.text=t;else{const e=n.createElement("title");e.textContent=t,c.appendChild(e)}const d=s.serialize(),u=new RegExp(`<div>\\s*${i}\\s*<\\/div>`,"i").exec(d);return this.#o={template:e,title:t,before:d.slice(0,u.index),after:d.slice(u.index+u[0].length)},this.#o}async getAssets(){if(this.appId){if(this.templateLess)return await this.assetsApi.downloadPageAssets(this.appId,this.#e);{const e=await this.pageApi.get(this.appId,this.#e);if(this.#d){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.appId){if(this.templateLess)return await this.assetsApi.uploadPageAssets(this.appId,e,this.#e);{const t=await this.pageApi.get(this.appId,this.#e);if(this.#d){const s=await this.pageTemplateApi.get(t.template_id,this.#e);return await this.assetsApi.uploadTemplateAssets(s.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=$e(e);return{isValid:!1,error:t.userFriendlyMessage,code:t.code}}}async get(e,t,s=!1,r={}){const i=s?t:Object.assign({},this.#h(this.#e),t);try{return await this.#t.get(e,{headers:i})}catch(e){if("UNKNOWN_ERROR"!==$e(e).code){const t=$e(e);throw r.quiet||(this.logger.error(n.colors.red(`API request failed: ${t.userFriendlyMessage}`)),function(e,t,s){const r=$e(t),i=`[${s}] `;e.error(n.colors.red(`${i}${r.userFriendlyMessage}`)),e.error(n.colors.red(`Status: ${r.status} (${r.code})`)),e.error(n.colors.red(`Details: ${r.message}`)),r.suggestions.length>0&&(e.info(n.colors.yellow("Suggestions:")),r.suggestions.forEach((t,s)=>{e.info(n.colors.yellow(` ${s+1}. ${t}`))}))}(this.logger,e,"API Request")),e.tokenErrorInfo=t,e}throw e}}}function Ce(e,t){const s=(e=(e=e.startsWith("/")?e:`/${e}`).endsWith("/")?e:`${e}/`).endsWith("/")?e.slice(0,-1):e,r=n.createLogger();return(a,o,c)=>{const l=new i.URL(a.url??"","http://localhost"),{pathname:d,search:u}=l,p=["/",s];if(t&&(p.push(`${n.PATH_TEMPLATE_PREFIX}/${t}`),p.push(`${n.PATH_TEMPLATE_LOCAL_PREFIX}/${t}`)),p.includes(d)){const t=`${e}${u}`;return r.info(n.colors.yellow(`Redirecting to: ${t}`)),Pe(o,t,302)}c()}}const Oe=String.raw`[a-z](?:[a-z0-9\-]*[a-z0-9])?`,Be=new RegExp(`^(?:${Oe})$`),Fe=".localhost";function Me(e){return e?e.length>32?"The name must be at most 32 characters long":Be.test(e)?void 0:'The name may contain only lowercase latin letters, digits and "-", must start with a letter and must not end with "-"':"The name is required"}function De(e){if(!e)return;const t=e.toLowerCase().replace(/:\d+$/,"");if(!t.endsWith(Fe))return;const s=t.slice(0,-10);return s&&!s.includes(".")?s:void 0}function Ue(e,t){const s=/:(\d+)$/.exec(e.headers.host??"")?.[1];return`${he(e)?"https":"http"}://${t?`${t}.`:""}localhost${s?`:${s}`:""}`}const _e=new class{#b=new Map;#k=new Set;#$=new Set;#x=!1;#S=new Set;#A;#E=new Map;#T=new WeakMap;#I;useContext(e){void 0!==this.#I&&this.#I!==e&&this.clear(),this.#I=e}get context(){return this.#I}list(){return[...this.#b.values()]}get(e){return this.#b.get(e)}add(e){const t=Me(e.name);if(t)throw new Error(t);if(this.#b.has(e.name))throw new Error(`A user named "${e.name}" already exists`);if("token"===e.kind&&!e.token)throw new Error("A token user needs an API token");const s="session"===e.kind?{state:"pending",...e}:{...e};return this.#E.delete(s.name),this.#b.set(s.name,s),this.#P(),s}replace(e,t){if(!this.#b.has(e))throw new Error(`There is no user named "${e}"`);const s=Me(t.name);if(s)throw new Error(s);if(t.name!==e&&this.#b.has(t.name))throw new Error(`A user named "${t.name}" already exists`);const r=this.#A===e,n=[...this.#E].filter(([,t])=>t===e).map(([e])=>e);let i;this.#x=!0;try{this.remove(e),i=this.add(t)}catch(s){throw this.#x=!1,this.#P(),s}finally{this.#x=!1}for(const s of t.name===e?n:[...n,e])this.#E.set(s,i.name);return r&&(this.#A=i.name),this.#P(),i}#P(){this.#x||this.#$.forEach(e=>e())}renamedTo(e){return this.#E.get(e)}remove(e){const t=this.#b.get(e);if(!t)return!1;this.#A===e&&(this.#A=void 0);for(const[t,s]of this.#E)s===e&&this.#E.delete(t);return this.#b.delete(e),this.#k.forEach(e=>e(t)),this.#P(),!0}clear(){for(const e of[...this.#b.keys()])this.remove(e)}onRemove(e){return this.#k.add(e),()=>{this.#k.delete(e)}}onSessionChange(e){return this.#S.add(e),()=>{this.#S.delete(e)}}sessionChanged(e){this.#b.get(e.name)===e&&this.#S.forEach(t=>t(e))}onChange(e){return this.#$.add(e),()=>{this.#$.delete(e)}}get defaultUser(){return void 0===this.#A?void 0:this.#b.get(this.#A)}setDefaultUser(e){if(void 0===e)return void(this.#A=void 0);const t=this.#b.get(e);if(!t)throw new Error(`There is no user named "${e}"`);if("session"===t.kind&&("active"!==t.state||!t.session))throw new Error(`"${e}" has to log in on its own host before it can be the default user`);if("token"===t.kind&&"expired"===t.state)throw new Error(`MI turned down the API token of "${e}"`);this.#A=e}resolve(e){if(this.#T.has(e))return this.#T.get(e);const t=De(e.headers.host);let s;if(void 0===t){const t="localhost"===(e.headers.host??"").toLowerCase().replace(/:\d+$/,"")?this.defaultUser:void 0;s={key:t?.name??"",user:t}}else{const e=this.#b.get(t)??this.#b.get(this.#E.get(t)??"");s=e?{key:e.name,user:e}:void 0}return this.#T.set(e,s),s}};function He(e=_e){return(t,s,r)=>{const n=e.resolve(t),i=De(t.headers.host)??"";if(n?.user&&i&&n.key!==i&&function(e){if("GET"!==e.method&&"HEAD"!==e.method)return!1;const t=e.headers["sec-fetch-mode"];return"string"==typeof t?"navigate"===t:String(e.headers.accept??"").includes("text/html")}(t)){const e=t.originalUrl??t.url??"/";return s.statusCode=302,s.setHeader("Location",`${Ue(t,n.key)}${e}`),s.setHeader("Cache-Control","no-store"),void s.end()}n?r():(s.statusCode=404,s.setHeader("Content-Type","text/plain; charset=utf-8"),s.setHeader("Cache-Control","no-store"),s.end(`pp-dev has no user named "${i}". Open users from the pp-dev dev panel on the main host.`))}}const Ve=/(?:^|\/\/[^/]+)\/(?:login|auth\/saml\/login)(?:[/?#]|$)/i;function qe(e){return(e??"").split(";").map(e=>e.trim()).filter(e=>e&&e.split("=",1)[0].trim()!==fe)}function ze({statusCode:e=200,headers:t}){return 401===e||412===e||e>=300&&e<400&&Ve.test(String(t.location??""))}class We{#b;#L;#j=n.createLogger();#N=new WeakMap;#R=new WeakMap;#C=new WeakMap;#O=new WeakMap;constructor(e,t){this.#b=e,this.#L=t}isLeftBehindRequest(e,t,s){const r=De(t.headers.host)===e.name?ye(t.headers.cookie,fe):s;return void 0!==r&&this.#B(e,r)}observe(e,t,s,r){if("session"!==e.kind||this.#b.get(e.name)!==e)return;const n=De(t.headers.host)===e.name,i=n?ye(t.headers.cookie,fe):r,a=we(s.headers["set-cookie"],fe),o=this.#C.get(e);let c,l,d=n;return a&&a!==i?(c=a,l=i):n&&i!==e.session&&!ze(s)?c=i:o&&Date.now()>=o.retryAt&&(c=o.session,d=o.ownHost),c&&c===o?.session&&void 0===l&&(l=o.replaced),"active"===e.state&&ze(s)&&i===e.session&&this.#F(e,`MI turned away ${t.method} ${t.url}`),c&&c!==e.session&&c!==this.#N.get(e)&&c!==this.#R.get(e)&&!this.#B(e,c)?this.#M(e,c,l,d):void 0}async#M(e,t,s,r){let i;this.#N.set(e,t);try{i=await this.#L(t)}catch(i){return this.#N.get(e)===t&&(this.#N.delete(e),this.#C.set(e,{session:t,replaced:s,ownHost:r,retryAt:Date.now()+5e3})),void this.#j.warn(n.colors.yellow(`Could not check the MI session of user ${e.name}: ${String(i)}`))}if(this.#N.get(e)===t&&this.#b.get(e.name)===e)if(this.#N.delete(e),this.#C.get(e)?.session===t&&this.#C.delete(e),i){if(this.#B(e,t)||void 0!==s&&this.#B(e,s))return;const a="active"===e.state;r&&(this.#D(e),void 0!==s&&s!==t&&this.#D(e,s)),this.#C.delete(e),Object.assign(e,{state:"active",session:t,miUser:i}),this.#R.delete(e),this.#b.sessionChanged(e),a||this.#j.info(`${n.colors.blue("User")} ${n.colors.yellow(e.name)} ${n.colors.blue("logged in")} (MI user ${i.id}${i.username?`, ${i.username}`:""})`)}else this.#R.set(e,t),"active"===e.state&&s===e.session&&this.#F(e,"MI started a guest session")}#B(e,t){return"active"===e.state&&Boolean(this.#O.get(e)?.has(t))}#D(e,t=e.session){if(!t)return;const s=this.#O.get(e)??new Set;s.add(t),s.size>20&&s.delete(s.values().next().value),this.#O.set(e,s)}#F(e,t){this.#D(e),e.state="expired",e.session=void 0,this.#N.delete(e),this.#C.delete(e),this.#b.sessionChanged(e),this.#b.defaultUser===e&&this.#b.setDefaultUser(void 0),this.#j.warn(`${n.colors.yellow(`The MI session of user ${e.name} ended`)} (${t}). Log in again on its host.`)}}async function Je(e,t){try{const s=(await e.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",...t},!0,{quiet:!0})).data;if("object"!=typeof s||null===s)throw new Error(`${ne}.${ie}`);const r=s.user;return"number"==typeof r?.user_id?{miUser:{id:r.user_id,username:"string"==typeof r.username?r.username:""}}:{miUser:void 0}}catch(e){if(xe(e))return{miUser:void 0,refused:$e(e).userFriendlyMessage};throw e}}async function Ke(e,t){try{const s=await Je(e,{Authorization:`Bearer ${t}`});return s.miUser?{ok:!0,miUser:s.miUser}:{ok:!1,rejected:!0,message:s.refused?`The API token was rejected: ${s.refused}`:"The API token is expired or invalid"}}catch(e){return{ok:!1,rejected:!1,message:`Could not check the API token with MI: ${$e(e).userFriendlyMessage}`}}}const Ge=/^(https?:\/\/)([^/]+)(\/.*)?$/i,Xe="X-PP-Proxy";const Ze=/^\/login(?:\/|$)/i,Ye="/auth/saml/login";const Qe=/^\/auth\/(?:index\/)?logout(?:[/?#]|$)/i;const et=new WeakMap,tt=new WeakMap;const st=[/^text\//,/^application\/(?:[\w.-]+\+)?(?:json|xml)$/,/^application\/(?:x-)?(?:java|ecma)script$/,/^[\w.-]+\/[\w.-]+\+(?:json|xml)$/];function rt(e){const t=e.split(";",1)[0].trim().toLowerCase();return st.some(e=>e.test(t))}const nt=/[\w.:/\\!-]/;function it(e){const t=e["content-encoding"];if("string"==typeof t&&t.trim()&&"identity"!==t.trim())return!1;const s=e["content-type"];return"string"==typeof s&&rt(s)}function at(e){return async(t,s,r)=>{const n=e&&it(t.headers);r.statusCode=t.statusCode??r.statusCode,t.statusMessage&&(r.statusMessage=t.statusMessage),r.setHeader(Xe,1);for(const[e,s]of Object.entries(t.headers))void 0!==s&&(n&&"content-length"===e.toLowerCase()||r.setHeader(e,s));if(!n)return void t.pipe(r);const i=new o.StringDecoder("utf8");let a="",c=!1;const l=s=>{if(!s)return;r.write(e(Buffer.from(s,"utf8"),"utf8"))||c||(c=!0,t.pause(),r.once("drain",()=>{c=!1,t.resume()}))};t.on("data",e=>{a+=i.write(e);const t=a.lastIndexOf("\n");if(-1!==t&&(l(a.slice(0,t+1)),a=a.slice(t+1)),a.length>=65536){const e=function(e){for(let t=e.length-1;t>=0;t-=1)if(!nt.test(e[t]))return t;return-1}(a)+1||a.length;l(a.slice(0,e)),a=a.slice(e)}}),t.on("end",()=>{l(a+i.end()),a="",r.end()}),t.on("error",()=>{r.end()})}}function ot(e){const{rewritePath:t=/^\/(?!p[tl]).*/i,baseURL:s="",disableSSLValidation:r=!1,miAPI:o,templateName:c,users:l=_e}=e;if(!s)throw new Error("Base url is required");const d=function(e){try{return new URL(e).host}catch{return e.replace(Ge,"$2")}}(s),u=s.replace(Ge,"$1$2"),p=import("file-type"),h=n.createLogger(),g=e.sessionUsers??new We(l,function(e){return async t=>(await Je(e,{Cookie:`${fe}=${t}`})).miUser}(o));return a.createProxyMiddleware({selfHandleResponse:!0,pathFilter:(s,r)=>!(e.proxyIgnore||[]).some(e=>"string"==typeof e?s.startsWith(e):"function"!=typeof e.test||e.test(s))&&("string"==typeof t?s.startsWith(t):Array.isArray(t)?t.some(e=>s.startsWith(e)):"function"==typeof t.test&&t.test(s)),target:s,changeOrigin:!0,logger:{info:()=>{},warn:()=>{},error:()=>{}},secure:!r,headers:{host:d,origin:u},on:{proxyReq(e,t,r){const a=t.headers.host,d=e.getHeader("referer");a&&d&&"string"==typeof d&&e.setHeader("referer",d.replace(function(e){let t=Ee.get(e);return t||(t=new RegExp(`^https?://${Se(e)}(?=[/?#]|$)`,"i"),Ee.set(e,t)),t}(a),s));const u=l.resolve(t);let p;u?.user?p=u.user.token:u&&(p=o.personalAccessToken),p?(e.setHeader("Authorization",`Bearer ${p}`),et.set(t,p)):"session"===u?.user?.kind&&e.removeHeader("Authorization"),u?.user&&e.removeHeader("Token");const g="session"===u?.user?.kind?u.user:void 0;let f;if(g&&De(t.headers.host)!==g.name){f=g.session;const s=f?(m=t.headers.cookie,y=f,[...qe(m),`${fe}=${y}`].join("; ")):function(e){const t=qe(e);return t.length?t.join("; "):void 0}(t.headers.cookie);s?e.setHeader("cookie",s):e.removeHeader("cookie")}var m,y;tt.set(t,{user:u?.user,sentSession:f}),e.removeHeader("if-none-match"),e.removeHeader("if-modified-since");const w=t.url??"/",v=function(e,t,s,r){if(!t||!s||!r||s===r)return e;try{const t=new i.URL(e,"http://localhost"),n=t.pathname.match(/^\/data\/page\/([^/]+)(\/.*)?$/);if(!n)return e;let a;try{a=decodeURIComponent(n[1])}catch{a=n[1]}if(a!==s)return e;return`/data/page/${r}${n[2]??""}`+t.search+t.hash}catch{return e}}(w,o.v7Features,c,o.internalPageName);v!==w&&(t.url=v,e.path=v,console.info(`${n.colors.cyan("Rewrites data page to correct internal page name")}: ${n.colors.yellow(w)} ${n.colors.blue("→")} ${n.colors.green(v)}`)),h.info(`${n.colors.blue("Proxies request:")} ${n.colors.green(t.method)} ${t.url} -> ${n.colors.green(e.method)} ${e.protocol}//${e.host}${e.path}${u?.user?` ${n.colors.blue("as")} ${n.colors.yellow(u.user.name)}`:""}`);const{socket:b}=t,k=()=>{setTimeout(()=>{e.destroyed||e.destroy()},200)};return b.once("close",k),e.once("close",()=>b.off("close",k)),e},proxyRes:(e,t,s)=>{s.setHeader(Xe,1),e.headers["set-cookie"]&&(e.headers["set-cookie"]=ve(e.headers["set-cookie"],he(t))),e.headers.location&&(e.headers.location=function(e,t,s){const r=s.headers.host;let n;try{n=new URL(e)}catch{return e}return r&&/^https?:$/.test(n.protocol)&&n.host===t.toLowerCase()?e.replace(/^https?:\/\/[^/?#]*/i,`${he(s)?"https":"http"}://${r}`):e}(e.headers.location,d,t));const r=function(e,t){if(!Qe.test(e.url??""))return;const s=De(e.headers.host);return void 0===s?void 0:t.get(s)}(t,l),i=tt.get(t);if(r){e.resume();const a={"cache-control":"no-store"};i?.user===r&&(l.remove(r.name),h.info(`${n.colors.blue("Logged out user")} ${n.colors.yellow(r.name)}, back to the main host`),e.headers["set-cookie"]&&(a["set-cookie"]=e.headers["set-cookie"]));const o=t.headers["sec-fetch-mode"];return o&&"navigate"!==o?s.writeHead(204,a):s.writeHead(302,{...a,location:`${Ue(t)}/`}),void s.end()}const o=i?.user;let c=!0;if(o&&l.get(o.name)!==o)c=!1;else if(o){let s=!1;"session"===o.kind&&(s=g.isLeftBehindRequest(o,t,i?.sentSession),g.observe(o,t,e,i?.sentSession)),c=De(t.headers.host)===o.name&&!s}if(!c){const t=function(e){const t=(e??[]).filter(e=>void 0===we(e,fe));return t.length?t:void 0}(e.headers["set-cookie"]);t?e.headers["set-cookie"]=t:delete e.headers["set-cookie"]}e.headers["cache-control"]="no-store",delete e.headers.expires,delete e.headers.pragma;const u=(e,s)=>Buffer.from(Ie(Ye,"/login",Te(d,t.headers.host??"",e.toString(s))),s);if(e.headers["content-type"]?.includes("text/event-stream")||e.headers["transfer-encoding"]?.includes("chunked")&&"no"===e.headers["x-accel-buffering"])return h.info(`${n.colors.blue("Start streaming for request:")} ${n.colors.green(t.method)} ${t.url}`),at(u)(e,t,s);const f=function(e){const t=e["content-type"];if("string"==typeof t&&t.trim()&&!rt(t))return"pipe";const s=Number(e["content-length"]);return Number.isFinite(s)&&s>=10485760&&it(e)&&!function(e){const t="string"==typeof e?e.split(";",1)[0].trim().toLowerCase():"";return"text/html"===t||"application/xhtml+xml"===t}(t)?"stream":"buffer"}(e.headers);if("stream"===f&&(e.headers["x-accel-buffering"]="no"),"buffer"!==f)return at("stream"===f?u:void 0)(e,t,s);const m=a.responseInterceptor(async(e,t,s,r)=>{r.setHeader(Xe,1);if(await(await p).fileTypeFromBuffer(e))return e;{let t=e.toString("utf8");try{const e=new URL(s.url??"",`http://${d}`);if(e.searchParams&&e.searchParams.has("proxyRedirect")){const e=function(){const e="pp-dev::redirectCount",t="pp-dev::lastRedirect";let s=+(localStorage.getItem(e)??0);localStorage.getItem(t);Number.isNaN(s)&&(s=0);let r=window.location.href;const n=function(){const i=new URLSearchParams(window.location.search);if(!i.has("proxyRedirect"))return console.debug("No proxyRedirect param. Cleaning up."),void localStorage.removeItem(e);r!==window.location.href?(r=window.location.href,setTimeout(n,s<3?3e3:5e3)):window.location.href=i.get("proxyRedirect"),localStorage.setItem(e,""+ ++s),localStorage.setItem(t,(new Date).toISOString())};setTimeout(n,3e3)};t+=`<script>(${e.toString()})()<\/script>`}const r=t.slice(0,100);Ze.test(e.pathname)&&(r.includes("<html")||r.includes("<body")||r.includes("<head")||r.includes("html>"))&&!De(s.headers.host)&&(t+=`<script>(${be.toString()})(${n=d,JSON.stringify(n).replace(/</g,"\\u003c")})<\/script>`)}catch{}const r=s.headers.host??"";return Ie(Ye,"/login",Te(d,r,t))}var n});return m(e,t,s)},error(e,t,s){!function(e,t,s,r){const n=`Proxy error: "${e.message}" when trying to "${t.method} ${t.url}"`;if(r(`${n}\n\n${e.stack??""}`),"function"!=typeof s.writeHead)return void s.destroy();const i=s;i.writableEnded||i.destroyed||(i.headersSent?i.destroy():(i.writeHead(502,{"Content-Type":"text/plain; charset=utf-8"}),i.end(n)))}(e,t,s,e=>h.error(e))}}})}const ct=/\.(?:[a-z0-9]+)$/i,lt=6e5,dt=104857600,ut=1e3,pt=10485760;const ht=new class{items=new Map;totalSize=0;maxSize;maxItems;constructor(e,t){this.maxSize=e,this.maxItems=t}get(e){const t=this.items.get(e);return t?t.expiresAt<=Date.now()?(this.del(e),null):t.value:null}put(e,t,s=lt){return this.del(e),this.items.set(e,{value:t,expiresAt:Date.now()+s}),this.totalSize+=t.size,this.cleanup(),t}del(e){const t=this.items.get(e);return!!t&&(this.totalSize-=t.value.size,this.items.delete(e))}clear(){this.items.clear(),this.totalSize=0}keys(){return this.purgeExpired(),[...this.items.keys()]}getTotalSize(){return this.totalSize}getItemCount(){return this.keys().length}purgeExpired(){const e=Date.now();for(const[t,s]of this.items)s.expiresAt<=e&&this.del(t)}cleanup(){for(this.purgeExpired();this.items.size>0&&(this.items.size>this.maxItems||this.totalSize>this.maxSize);)this.del(this.items.keys().next().value)}}(dt,ut),gt=new Set,ft=new Map;function mt(e){ht.clear(),ft.clear(),gt.forEach(e=>e()),n.createLogger().info(n.colors.blue(`Proxy cache cleared: ${e}`))}const yt=new WeakSet;function wt(e,t){return t?e.startsWith(`@${t}@`):!e.startsWith("@")}function vt(e,t){if(e){for(const t of ht.keys())wt(t,e)&&ht.del(t);ft.delete(e),n.createLogger().info(n.colors.blue(`Proxy cache cleared for ${e}: ${t}`))}else mt(t)}function bt(e,t,s){const r=function(e){return et.get(e)}(e);if(void 0!==r){const e=ft.get(s),t=void 0!==e&&r!==e;return ft.set(s,r),t?"personal access token changed":void 0}const n=we(t.getHeader("set-cookie"),fe);return void 0!==n&&n!==ye(e.headers.cookie,fe)?"MI session changed":void 0}function kt(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 $t(e){const{devServer:t,ttl:s=lt,maxSize:r=dt,maxItems:i=ut,users:a=_e}=e,o=n.createLogger();return r===dt&&i===ut||(ht.maxSize=r,ht.maxItems=i),t&&(t.cache=ht),yt.has(a)||(yt.add(a),a.onRemove(e=>vt(e.name,"user removed")),a.onSessionChange(e=>vt(e.name,"MI session changed or ended"))),(e,t,r)=>{const i=a.resolve(e);if(!i)return r();t.once("finish",()=>{const s=t.hasHeader(Xe)?bt(e,t,i.key):void 0;s&&vt(i.key,`${s} (${e.method} ${Le(e.url??"")})`)});const c=i.user?.session,l=e.originalUrl||e.url||"",d="GET"===e.method?function(e,t,s){const r=e.split("?")[0];return ct.test(r)?r.includes("/auth/info.js")?"":t?`@${t}@${s}:${e}`:`${s}:${e}`:""}(l,i.key,e.headers.host??""):"";if(!d||!function(e,t){const{user:s}=t;return"session"!==s?.kind||!!s.session&&(De(e.headers.host)!==s.name||ye(e.headers.cookie,fe)===s.session)}(e,i))return r();const u=ht.get(d);if(u)return o.info(`${n.colors.blue("Proxies request:")} ${n.colors.green(e.method)} ${l} -> ${n.colors.blue("Cache")} ${d}`),function(e,t){try{for(const[s,r]of Object.entries(t))null!=r&&e.setHeader(s,r)}catch(e){n.createLogger().warn(`Failed to set some response headers: ${e instanceof Error?e.message:String(e)}`)}}(t,u.headers),t.setHeader("X-PP-Cache","hit"),t.write(u.content),void t.end();const p=t.end,h=t.write,g=[];let f=0,m="undecided";const y=(e,t)=>null==e?null:"string"==typeof e?Buffer.from(e,t||"utf8"):e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf8"),w=()=>{m="pass";for(const e of g.splice(0))h.call(t,e)},v=()=>{"undecided"===m&&(t.hasHeader(Xe)?!function(e){if(200!==e.statusCode)return!1;if(/^text\/event-stream/i.test(String(e.getHeader("content-type")??"")))return!1;if("no"===String(e.getHeader("x-accel-buffering")??"").toLowerCase())return!1;const t=Number(e.getHeader("content-length"));return!(Number.isFinite(t)&&t>=pt)}(t)?w():m="buffer":m="pass")};t.write=function(e,t,s){if(v(),"pass"===m)return h.call(this,e,t,s);const r="function"==typeof t?t:s,n=y(e,"string"==typeof t?t:void 0);return n&&(g.push(n),f+=n.length),f>pt&&w(),r&&process.nextTick(r),!0},t.end=function(e,r,l){if(v(),"pass"===m)return p.call(this,e,r,l);"function"==typeof e?(l=e,e=void 0):"function"==typeof r&&(l=r,r=void 0);const u=y(e,"string"==typeof r?r:void 0);let h;u&&g.push(u);try{h=kt(g);const e=Buffer.byteLength(h);if(200===t.statusCode&&e>0&&e<pt&&function(e,t,s){return!e.user||s.get(e.key)===e.user&&e.user.session===t}(i,c,a)){const{"set-cookie":r,...i}=t.getHeaders(),a={headers:i,content:h,timestamp:Date.now(),size:e};ht.put(d,a,s),o.info(`${n.colors.blue("[Cached]")} ${d} (${(e/1024).toFixed(1)}KB)`)}}catch(e){o.error(`Failed to cache response for ${d}: ${e}`),h=kt(g)}return p.call(this,h,l)},r()}}const xt=new Map;function St(e){const t=xt.get(e);return t?Date.now()-t.timestamp>18e4?(xt.delete(e),null):t.data:null}function At(e,t){xt.set(e,{timestamp:Date.now(),data:t})}var Et;Et=()=>xt.clear(),gt.add(Et);let Tt=!1;function It(e){Tt||(Tt=!0,e.info(n.colors.blue("Clearing proxy cache after successful login")),ht.clear())}function Pt(){Tt=!1,n.authProvider.reset()}const Lt="/home?proxyRedirect=";function jt(e){const t=e.headers??{},s=Boolean(De(e.headers?.host));if(!s&&!_e.resolve(e)?.user)return t;const{cookie:r,authorization:n,token:i,...a}=t;return s||void 0===r?a:{...a,cookie:r}}function Nt(e,t,s){const{templateLess:r=!1,miHudLess:i=!1,appId:a,base:o,appBase:c,v7Features:l}=s,d=n.createLogger();if(r&&i&&void 0===a)throw new Error("Custom App ID is required when both templateLess and miHudLess are true");return async(s,u,p)=>{try{const h=!(r&&i),g=Le(s.url??""),f=e.test(g),m=!f&&!g.startsWith("/home")&&function(e,t){if(!t)return!1;if("/"===t)return!0;const s=t.endsWith("/")?t:`${t}/`;return e===s||e===s.slice(0,-1)||e.startsWith(s)}(g,c)&&function(e){const t=e.headers["sec-fetch-dest"];if("string"==typeof t)return"document"===t;const s=e.headers.accept;return"string"==typeof s&&s.includes("text/html")}(s),y=n.authProvider.getState();if(!y.isAuthenticated&&!y.isRedirected&&s.url?.startsWith("/home")&&!s.url?.startsWith(Lt)){let e;d.info(n.colors.blue("Trying to authenticate and redirect to base"));const c=t=>{e=t};try{if(h?await Ct(t,{templateLess:r,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${Lt}${encodeURIComponent("/")}`},s,u,c,d):await Rt(t,{templateLess:r,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${Lt}${encodeURIComponent("/")}`},s,u,c,d),u.headersSent||u.writableEnded)return;return e?p(e):(n.authProvider.setRedirected(!0),d.info(n.colors.blue("Successfully authenticated. Redirecting to base")),Pe(u,o??"/",302))}catch(e){if(u.headersSent||u.writableEnded)return;return p()}}if(!f&&!m)return p();if(!h){return await Rt(t,{templateLess:r,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${Lt}${encodeURIComponent("/")}`},s,u,p,d)}return await Ct(t,{templateLess:r,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${Lt}${encodeURIComponent("/")}`},s,u,p,d)}catch(e){return d.error(n.colors.red(`Unexpected error in load-pp-data middleware: ${e instanceof Error?e.message:String(e)}`)),Pt(),p(e)}}}async function Rt(e,t,s,r,i,a){const{appId:o,redirectOnAuthFailure:c,redirectUrl:l}=t;if(void 0===o){const e=new Error("Custom App ID is required for page info only mode");return a.error(n.colors.red(e.message)),i(e)}const d=jt(s);a.info(n.colors.green("Start loading page info"));try{const t=`pageInfo:${o}`;return St(t)?(a.info(n.colors.green("Page info loaded from cache")),i()):(await e.getPageInfo(o,d),It(a),At(t,{success:!0}),n.authProvider.updateState({isAuthenticated:!0}),a.info(n.colors.green("Page info loaded successfully")),i())}catch(e){return Pt(),Ot(e,c??!0,l||`${Lt}${encodeURIComponent("/")}`,r,i,a,"Page info")}}async function Ct(e,t,s,r,i,a){const{templateLess:o,appId:c,redirectOnAuthFailure:l,redirectUrl:d}=t,u=jt(s);a.info(n.colors.green("Start loading page data"));try{const t=`pageData:${o}:${c}`;if(St(t))return a.info(n.colors.green("Page data loaded from cache")),i();const s=o||void 0===c?e.getPageTemplate(u):e.getPageVariables(c,u);return await s,It(a),At(t,{success:!0}),a.info(n.colors.green("Page data loaded successfully")),i()}catch(e){return Pt(),Ot(e,l??!0,d||`${Lt}${encodeURIComponent("/")}`,r,i,a,"Page data")}}function Ot(e,t,s,r,i,a,o){if(function(e){return null!==e&&"object"==typeof e&&xe(e)}(e)&&(a.info(n.colors.red(`${o} loading failed. Not authorized`)),t)){const e=`${s}`;return a.info(n.colors.yellow(`Redirecting to: ${e}`)),Pe(r,e,302)}const c=e instanceof Error?e.message:String(e);return a.info(n.colors.red(`${o} loading failed. Error: ${c}`)),i(e)}function Bt(e){return"string"==typeof e?e:void 0}function Ft(e,t){return"string"==typeof e?Buffer.from(e,t):e instanceof Uint8Array?Buffer.from(e):null}function Mt(e,t,s={}){return async(r,i,a)=>{if(await e(r.url??"",r,i)){const e=n.createLogger();"GET"!==r.method&&"HEAD"!==r.method||!(r.headers.accept??"").includes("text/html")||delete r.headers["if-none-match"];const o=i.end;if("HEAD"===r.method)return i.end=function(e,t,s){const r=[e,t,s].find(e=>"function"==typeof e);return i.headersSent||i.removeHeader("content-length"),o.call(this,r),this},void a();e.info(`Rewrite response for ${r.url}`);const l=[],d=i.write,u=i.writeHead,p=i.flushHeaders;let h=null,g=!1;const f=()=>{g=!0,h&&!i.headersSent&&u.apply(i,h),h=null;for(const e of l.splice(0))d.call(i,e)},m=(e=!1)=>{if(g)return!0;if(!s.contentType)return!1;const t=i.getHeader("content-type");return!(void 0===t&&!e)&&(!s.contentType(void 0===t?"":String(t))&&(f(),!0))};i.flushHeaders=function(){m()&&p.call(this)},i.writeHead=function(e,...t){if(g)return u.call(this,e,...t);const s="string"==typeof t[0]?t[0]:void 0;return function(e,t){if(Array.isArray(t)){const s=new Map;for(let e=0;e+1<t.length;e+=2){const r=String(t[e]),n=s.get(r.toLowerCase())??{name:r,values:[]};n.values.push(String(t[e+1])),s.set(r.toLowerCase(),n)}for(const{name:t,values:r}of s.values())e.setHeader(t,1===r.length?r[0]:r);return}if(t&&"object"==typeof t)for(const[s,r]of Object.entries(t))void 0!==r&&e.setHeader(s,r)}(this,void 0===s?t[0]:t[1]),this.statusCode=e,h=void 0===s?[e]:[e,s],m(),this},i.write=function(e,t,s){if(m())return d.call(this,e,t,s);const r=Ft(e,Bt(t));r&&l.push(r);const n="function"==typeof t?t:s;return"function"==typeof n&&process.nextTick(n),!0},i.end=function(s,n,a){if(m(!0))return o.call(this,s,n,a);"function"==typeof s&&(a=s,s=void 0);const d=Ft(s,Bt(n));d&&l.push(d);const p="function"==typeof n?n:a,g=i.getHeader("content-encoding"),f=z(Buffer.concat(l),g),y=function(e,t){switch(t){case"gzip":return c.gzipSync(e);case"br":return c.brotliCompressSync(e);case"deflate":return c.deflateSync(e);default:return e}}(t(f,r,i),g);return void 0!==i.getHeader("content-length")&&(i.headersSent?e.warn(`Rewrite response for ${r.url}: headers already sent, Content-Length left as is`):i.setHeader("content-length",y.length)),i.headersSent||i.removeHeader("etag"),i.writeHead=u,h&&!i.headersSent&&u.apply(this,h),o.call(this,y,p),this}}a()}}const Dt="<redacted>",Ut=new RegExp(`(^|;\\s*)(${fe}=)[^;]*`,"gi"),_t=new RegExp(`^(\\s*${fe}=)[^;]*`,"i");function Ht(e){const t={...e};if("string"==typeof t.authorization){const[e,s]=t.authorization.split(/\s+/,2);t.authorization=void 0===s?Dt:`${e} ${Dt}`}return void 0!==t.token&&(t.token=Dt),"string"==typeof t.cookie&&(t.cookie=t.cookie.replace(Ut,`$1$2${Dt}`)),t}function Vt(e){const t={...e},s=t["set-cookie"],r=e=>e.replace(_t,`$1${Dt}`);return Array.isArray(s)?t["set-cookie"]=s.map(r):"string"==typeof s&&(t["set-cookie"]=r(s)),t}const qt=/^\/(?:login|auth)(?:[/?#]|$)/i,zt=/pass(?:word|wd|code)?|pwd|secret|token|otp|mfa|2fa/i;function Wt(e,t){return Array.isArray(e)?e.map(e=>Wt(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,s])=>zt.test(e)?(t.any=!0,[e,Dt]):[e,Wt(s,t)])):e}function Jt(e,t,s){if(!s)return s;if(qt.test(e))return Buffer.from(Dt);const r=(t??"").split(";",1)[0].trim().toLowerCase();try{if("application/x-www-form-urlencoded"===r){const e=new URLSearchParams(s.toString("utf8")),t=[...new Set(e.keys())].filter(e=>zt.test(e));return t.forEach(t=>e.set(t,Dt)),t.length?Buffer.from(e.toString()):s}if("application/json"===r||r.endsWith("+json")){const e={any:!1},t=Wt(JSON.parse(s.toString("utf8")),e);return e.any?Buffer.from(JSON.stringify(t)):s}}catch{}return s}const Kt=["/@","/_next/","/__nextjs_"],Gt=new Set(["/favicon.ico","/installHook.js.map"]);function Xt(e,t=10485760,s=_e){return(r,n,i)=>{const a=r.url||"/",o=a.split("?")[0];if(Kt.some(e=>a.startsWith(e))||Gt.has(o))return void i();const c=e.allocateId(),l=s.resolve(r)?.user?.name,d=Date.now(),u=[];let p=0,h=!1;const g=r.emit.bind(r);r.emit=(e,...s)=>{if("data"===e&&!h){const e=s[0],r=Buffer.isBuffer(e)?e:Buffer.from(String(e));p+=r.byteLength,p<=t?u.push(r):(h=!0,u.length=0)}return g(e,...s)};const f=[];let m=0,y=!1;const w=n.write.bind(n),v=n.end.bind(n);function b(e,s){if(!y&&null!=e)try{const r=Buffer.isBuffer(e)?e:"string"==typeof e?Buffer.from(e,s):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?Buffer.from(e):Buffer.from(String(e));m+=r.byteLength,m<=t?f.push(r):(y=!0,f.length=0)}catch{}}function k(e){return"string"==typeof e[0]?e[0]:void 0}function $(){const e=n.getHeaders();return e["x-pp-proxy"]?"hit"===e["x-pp-cache"]?"proxy-cache":"proxy":"local"}let x=!1;n.write=(e,...t)=>(b(e,k(t)),w(e,...t)),n.end=(t,...s)=>("function"!=typeof t&&b(t,k(s)),function(){if(x)return;x=!0;const t=Jt(a,"string"==typeof r.headers["content-type"]?r.headers["content-type"]:void 0,!h&&u.length>0?Buffer.concat(u):null),s=!y&&f.length>0?Buffer.concat(f):null;e.add({id:c,timestamp:d,method:r.method||"GET",url:a,statusCode:n.statusCode??null,duration:Date.now()-d,source:$(),user:l,requestHeaders:Ht(r.headers),requestBody:t,requestBodyTruncated:h,responseHeaders:Vt(n.getHeaders()),responseBody:s,responseBodyTruncated:y})}(),v(t,...s)),i()}}function Zt(e){return(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0)+512}function Yt(e){return{id:e.id,timestamp:e.timestamp,method:e.method,url:e.url,statusCode:e.statusCode,duration:e.duration,source:e.source,user:e.user,requestSize:e.requestBody?.byteLength??0,responseSize:e.responseBody?.byteLength??0,requestBodyTruncated:e.requestBodyTruncated,responseBodyTruncated:e.responseBodyTruncated}}class Qt{entries=new Map;insertOrder=[];head=0;totalSize=0;maxMemory;maxEntries;constructor(e=1073741824,t=1e4){this.maxMemory=e,this.maxEntries=t}evictOldest(){const e=this.insertOrder[this.head++],t=this.entries.get(e);t&&(this.totalSize-=Zt(t),this.entries.delete(e)),this.head>=1024&&2*this.head>=this.insertOrder.length&&(this.insertOrder=this.insertOrder.slice(this.head),this.head=0)}allocateId(){return u.randomUUID()}add(e){let t=e,s=(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0);s>this.maxMemory&&(t={...e,requestBody:null,responseBody:null,requestBodyTruncated:e.requestBodyTruncated||null!==e.requestBody,responseBodyTruncated:e.responseBodyTruncated||null!==e.responseBody},s=0);const r=Zt(t);for(;(this.totalSize+r>this.maxMemory||this.entries.size>=this.maxEntries)&&this.head<this.insertOrder.length;)this.evictOldest();this.entries.set(t.id,t),this.insertOrder.push(t.id),this.totalSize+=r}get(e){return this.entries.get(e)}list(e){const t=e?.method?.toUpperCase(),s=e?.search?.toLowerCase(),r=e=>(!t||e.method===t)&&(!s||e.url.toLowerCase().includes(s)),n=Number.isFinite(e?.limit)?e.limit:1/0,i=[];if(n<=0)return i;if(void 0===e?.offset){for(let e=this.insertOrder.length-1;e>=this.head&&i.length<n;e-=1){const t=this.entries.get(this.insertOrder[e]);t&&r(t)&&i.push(Yt(t))}return i.reverse()}let a=Number.isFinite(e.offset)?Math.max(0,e.offset):0;for(let e=this.head;e<this.insertOrder.length&&i.length<n;e+=1){const t=this.entries.get(this.insertOrder[e]);t&&r(t)&&(a>0?a-=1:i.push(Yt(t)))}return i}clear(){this.entries.clear(),this.insertOrder=[],this.head=0,this.totalSize=0}get size(){return this.entries.size}get memoryUsage(){return this.totalSize}}async function es(e){const t=new C,s=async r=>{const n=await l.promises.readdir(r,{withFileTypes:!0});for(const i of n){const n=L.join(r,i.name);if(i.isDirectory())await s(n);else if(i.isFile()){const s=L.relative(e,n).replace(/\\/g,"/");t.file(s,await l.promises.readFile(n))}}};return await s(e),await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"})}async function ts(e,t){const s=await C.loadAsync(await l.promises.readFile(e),{createFolders:!1}),r=L.resolve(t),n=Object.values(s.files).filter(e=>!e.name.startsWith("__MACOSX/"));for(const e of n){const t=e.unsafeOriginalName??e.name,s=L.resolve(r,t);if(s!==r&&!s.startsWith(r+L.sep))throw new Error(`Zip entry "${t}" resolves outside the extraction directory`);if("number"==typeof e.unixPermissions&&40960==(61440&e.unixPermissions))throw new Error(`Zip archive contains a symlink ("${t}"), which is not allowed`)}await l.promises.mkdir(r,{recursive:!0});for(const e of n){const t=L.resolve(r,e.unsafeOriginalName??e.name);e.dir?await l.promises.mkdir(t,{recursive:!0}):(await l.promises.mkdir(L.dirname(t),{recursive:!0}),await l.promises.writeFile(t,await e.async("nodebuffer")))}}function ss(e){return`${e}.${process.pid}.${u.randomBytes(4).toString("hex")}.tmp`}const rs=new Map;async function ns(e,t,s){const r=ss(e);try{await F.writeFile(r,t,s),await F.rename(r,e)}catch(e){throw await F.rm(r,{force:!0}),e}}function is(e,t){const s=t?.distDir;if("export"!==t?.output||!s||".next"===s)return null;const r=L.resolve(e,s,"dev","types");return P.existsSync(r)?(P.rmSync(r,{recursive:!0,force:!0}),r):null}const as=6e5;function os(e,t,s){if(e.pid)if("win32"!==process.platform)try{s?process.kill(-e.pid,t):e.kill(t)}catch{}else null===e.exitCode&&null===e.signalCode&&M.spawn("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore"}).on("error",()=>{})}function cs(e,t,s,{cwd:r,env:n,timeoutMs:i,signal:a,killGraceMs:o=5e3}){return new Promise((c,l)=>{if(a?.aborted)return void l(new Error(`${e} was stopped`));const d="win32"!==process.platform&&(void 0!==a||void 0!==i),u=M.spawn(t,s,{cwd:r,env:n,stdio:"inherit",detached:d});let p,h;const g=(e,t)=>{p?t||void 0===h||(clearTimeout(h),h=void 0,os(u,"SIGKILL",d)):(p=e,t?(os(u,"SIGTERM",d),h=setTimeout(()=>{h=void 0,os(u,"SIGKILL",d)},o)):os(u,"SIGKILL",d))},f=()=>g(`${e} was stopped`,!1),m=void 0===i?void 0:setTimeout(()=>g(`${e} timed out after ${Math.round(i/1e3)} s`,!0),i);a?.addEventListener("abort",f,{once:!0});const y=e=>{clearTimeout(m),clearTimeout(h),a?.removeEventListener("abort",f),d&&os(u,"SIGKILL",d),e?l(e):c()};u.on("close",t=>{p?y(new Error(p)):0!==t?y(new Error(`${e} exited with code ${t}`)):y()}),u.on("error",e=>y(e))})}const ls=".next";async function ds(e,t={}){let s;try{const t=v.createRequire(L.join(e,"package.json")).resolve("next/package.json");s=L.resolve(L.dirname(t),"dist/bin/next")}catch{throw new Error(`Unable to resolve the "next" binary from ${e}. Is Next.js installed?`)}const{distDir:r,...i}=t,a=Object.assign({},process.env,{NODE_ENV:"production",[n.PP_DEV_NEXT_BUILD_ENV_VAR]:"1"});r?a[n.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR]=r:delete a[n.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR],await cs("next build",process.execPath,[s,"build"],{...i,cwd:e,env:a})}const us="pageName",ps="date",hs=L.dirname("undefined"!=typeof __filename&&__filename||i.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:x&&"SCRIPT"===x.tagName.toUpperCase()&&x.src||new URL("internal.middleware-63EM6Z98.js",document.baseURI).href)),gs=L.resolve(hs,"..",".."),fs=Buffer.from([80,75,3,4]),ms=20,ys=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const ws="sync-service.meta.json",vs="BUILD-MANIFEST.json",bs="__template_variables.json";const ks=["text","select","multiselect","file","list","color","boolean"];function $s(e){return ks.includes(e)}const xs=["true","false","Y","N","1","0"],Ss=/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function As(e,t){return e.id===t||e.text===t}function Es(e){if("string"==typeof e||"number"==typeof e)return{id:String(e),text:String(e)};if("object"!=typeof e||null===e)return{text:""};const{id:t,text:s}=e,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{id:r,text:"string"==typeof s?s:r??""}}function Ts(e,t,s,r){const n="select"===s.type||"multi-select"===s.type;if("string"!=typeof r&&(!n||"number"!=typeof r))return[{name:e,severity:"warning",message:`${t}: field "${s.name}" should be a string, got ${typeof r}.`}];const i=String(r);if(!i)return[];switch(s.type){case"color":return Ss.test(i)?[]:[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${i}" is not a recognized color (expected e.g. "#075b7e").`}];case"select":{if(!Array.isArray(s.options)||!s.options.length)return[];const r=s.options.map(Es);return r.some(e=>As(e,i))?[]:[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${i}" is not one of the declared options (${r.map(e=>e.text).join(", ")}).`}]}case"multi-select":{if(!Array.isArray(s.options)||!s.options.length)return[];const r=s.options.map(Es),n=i.split(",").map(e=>e.trim()).filter(e=>!r.some(t=>As(t,e)));return n.length?[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${n.join(", ")}" is not among the declared options (${r.map(e=>e.text).join(", ")}).`}]:[]}default:return[]}}function Is(e,t){const s=function(e){if(!Array.isArray(e)||0===e.length)return null;const t=e.map(e=>"string"==typeof e?{name:e,type:"textarea"}:e&&"object"==typeof e&&"string"==typeof e.name?e:null).filter(e=>null!==e);return t.length?t:null}(e.additional_options);if(!s)return[];const r=new Set(s.map(e=>e.name)),n=[];return t.forEach((t,i)=>{const a=`"${e.name}" item #${i+1}`;if("object"!=typeof t||null===t||Array.isArray(t))return void n.push({name:e.name,severity:"warning",message:`${a} should be an object with field(s): ${s.map(e=>e.name).join(", ")}.`});const o=t;for(const t of s)t.name in o?n.push(...Ts(e.name,a,t,o[t.name])):n.push({name:e.name,severity:"warning",message:`${a} is missing field "${t.name}".`});const c=Object.keys(o).filter(e=>!r.has(e));c.length&&n.push({name:e.name,severity:"warning",message:`${a} has unexpected field(s) not declared in additional_options: ${c.join(", ")}.`})}),n}function Ps(e,t){const s=[];switch(e.tag_type){case"boolean":xs.includes(t)||s.push({name:e.name,severity:"warning",message:`Value "${t}" is not a recognized boolean encoding (expected one of ${xs.join(", ")}).`});break;case"list":try{const r=JSON.parse(t);Array.isArray(r)?s.push(...Is(e,r)):s.push({name:e.name,severity:"warning",message:`Value for list variable "${e.name}" is valid JSON but not an array.`})}catch{s.push({name:e.name,severity:"warning",message:`Value for list variable "${e.name}" is not valid JSON.`})}break;case"select":case"multiselect":if(Array.isArray(e.additional_options)){const r=e.additional_options.map(Es),n=("multiselect"===e.tag_type?t.split(",").map(e=>e.trim()):[t]).filter(e=>!r.some(t=>As(t,e)));n.length&&s.push({name:e.name,severity:"warning",message:`Value "${n.join(", ")}" does not match any declared option for "${e.name}".`})}}return s}function Ls(e,t){switch(e.tag_type){case"boolean":return xs.includes(t)?null:`Not a recognized boolean value ("${t}").`;case"color":return""===t||Ss.test(t)?null:`Not a recognized color value ("${t}").`;case"list":if(""===t)return null;try{const e=JSON.parse(t);return null===e||Array.isArray(e)?null:"Value is valid JSON but not an array."}catch{return"Value is not valid JSON."}default:return null}}const js="/@pp-dev/variables-editor",Ns=/^[A-Za-z0-9_\s-]+$/,Rs="Dist service or MiAPI is not defined",Cs=new WeakMap;async function Os(e){const t=await e.readPublicTemplateVariablesFile();if(!t)return null;const s=t.toString("utf-8");let r;try{r=JSON.parse(s)}catch(e){return{raw:s,schema:null,parseError:e instanceof Error?e.message:"Invalid JSON"}}return"object"!=typeof r||null===r||Array.isArray(r)||!Array.isArray(r.tags)?{raw:s,schema:null,parseError:'The root value must be a JSON object with a "tags" array.'}:{raw:s,schema:r}}async function Bs(e){const t=e?(await Os(e))?.schema??null:null;return t&&{...t,tags:t.tags.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.name&&""!==e.name)}}function Fs(e,t,s){const r=Cs.get(e);if(r)return void(r.deps=t);const n={deps:t};Cs.set(e,n),e.get("/@api/variables/schema",async(e,t)=>{const{distService:s}=n.deps;if(!s)return void t.status(503).json({error:Rs});const r=await Os(s);t.json(r?{exists:!0,...r}:{exists:!1,schema:null,raw:null})}),e.put("/@api/variables/schema",async(e,t)=>{const{distService:s}=n.deps;if(!s)return void t.status(503).json({error:Rs});const r=e.body?.raw;if("string"!=typeof r)return void t.status(400).json({error:"Request body must be { raw: string }."});let i;try{i=JSON.parse(r)}catch{return void t.status(400).json({error:"Not valid JSON."})}if("object"!=typeof i||null===i||Array.isArray(i))return void t.status(400).json({error:"The root value must be a JSON object."});const a=i.tags;if(!Array.isArray(a))return void t.status(400).json({error:'"tags" must be an array.'});const o=a.findIndex(e=>"object"!=typeof e||null===e||"string"!=typeof e.name||!e.name);if(-1!==o)return void t.status(400).json({error:`tags[${o}] is missing a non-empty "name".`});const c=[],l=new Set;for(const e of a)l.has(e.name)&&c.push(`Duplicate variable name "${e.name}".`),l.add(e.name),e.tag_type&&!$s(e.tag_type)&&c.push(`"${e.name}" has an unrecognized tag_type "${e.tag_type}".`),Ns.test(e.name)||c.push(`"${e.name}" contains a character MI's own editor doesn't allow (only letters, digits, underscore, hyphen, and whitespace).`);try{await s.saveTemplateVariablesFile(Buffer.from(r,"utf-8"))}catch(e){return void t.status(500).json({error:`Failed to write ${bs}.`,details:e instanceof Error?e.message:String(e)})}t.json({ok:!0,warnings:c})}),e.get("/@api/variables/values",async(e,t)=>{const{distService:s,miAPI:r}=n.deps;try{const e=await Bs(s),n=await r.getLivePageVariables(),i=function(e,t){const s=(e?.tags??[]).filter(e=>"string"==typeof e?.name&&""!==e.name),r=new Map(s.map(e=>[e.name,e])),n=new Map(t.map(e=>[e.name,e.value])),i=new Set([...r.keys(),...n.keys()]);return Array.from(i).map(e=>({name:e,value:n.get(e)??r.get(e)?.default_value??""}))}(e,n);t.json({schema:e,live:n,combined:i,local:r.localPageVariables??null})}catch(e){t.status(502).json({error:"Failed to fetch live page variables.",details:e instanceof Error?e.message:String(e)})}}),e.put("/@api/variables/values",async(e,t)=>{const{distService:s,miAPI:r}=n.deps,i=function(e){const t="object"==typeof e&&null!==e?e.tags:void 0;if(!Array.isArray(t))return null;const s=[];for(const e of t){if("object"!=typeof e||null===e)return null;const{name:t,value:r}=e;if("string"!=typeof t||!t||"string"!=typeof r)return null;s.push({name:t,value:r})}return s}(e.body);if(!i)return void t.status(400).json({error:"Request body must be { tags: {name, value}[] }."});const a=i.map(e=>e.name).find((e,t,s)=>s.indexOf(e)!==t);if(void 0===a)try{const e=await Bs(s),n=new Map((e?.tags??[]).map(e=>[e.name,e])),a=[];for(const e of i){const t=n.get(e.name);t&&a.push(...Ps(t,e.value))}let o;await r.applyPageVariables(i);try{await r.reloadPageVariables()}catch(e){o=e instanceof Error?e.message:String(e)}t.json({ok:!0,warnings:a,local:r.localPageVariables??null,...o?{localError:o}:{}})}catch(e){t.status(502).json({error:"Failed to save live page variables.",details:e instanceof Error?e.message:String(e)})}else t.status(400).json({error:`Variable "${a}" is listed more than once.`})}),e.post("/@api/variables/values/local",async(e,t)=>{const{miAPI:s}=n.deps;try{await s.reloadPageVariables(),t.json({local:s.localPageVariables??null})}catch(e){t.status(502).json({error:"Failed to update the local values.",details:e instanceof Error?e.message:String(e)})}}),e.get("/@api/variables/pages",async(e,t)=>{const{miAPI:s}=n.deps;try{const e=await s.listPages(),r=e=>void 0!==s.pageId?e.id===s.pageId:e.internal_name===s.internalPageName,n=e.find(r)??null,i=e.filter(e=>!r(e)).map(e=>({id:e.id,name:e.name,internal_name:e.internal_name,sameTemplate:!!n&&(null!=n.template_id?e.template_id===n.template_id:!!n.template&&e.template===n.template)}));t.json({pages:i,currentPageName:n?.name??null})}catch(e){t.status(502).json({error:"Failed to fetch the page list.",details:e instanceof Error?e.message:String(e)})}}),e.get("/@api/variables/import-plan/:pageId",async(e,t)=>{const{distService:s,miAPI:r}=n.deps,i=Number(e.params.pageId);if(!Number.isInteger(i)||i<=0)t.status(400).json({error:"pageId must be a positive integer."});else try{const e=await Bs(s),n=await r.getPageVariablesFor(i);t.json(function(e,t){const s=new Map((e?.tags??[]).map(e=>[e.name,e])),r=[],n=[];for(const e of t){const t=s.get(e.name);if(!t){n.push({name:e.name,sourceValue:e.value,reason:"Not in the current page's schema."});continue}const i=Ls(t,e.value);i?n.push({name:e.name,sourceValue:e.value,reason:i}):r.push({name:e.name,sourceValue:e.value,tagType:t.tag_type||"text"})}return{importable:r,skipped:n}}(e,n))}catch(e){t.status(502).json({error:"Failed to fetch values from the selected page.",details:e instanceof Error?e.message:String(e)})}}),q(e,{path:js,name:"variables-editor",clientDir:s,values:()=>({templateLess:String(Boolean(n.deps.miAPI.isTemplateLess))})})}const Ms=12e4;class Ds{server;opts;eventMap;logger;syncInFlight=null;syncActionResolvers=new Map;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.eventMap.set("template:sync:action-response",this.onTemplateSyncActionResponse.bind(this)),this.eventMap.set("page-variables:reload",this.onPageVariablesReload.bind(this)),this.logger=n.createLogger(),this.init()}init(){const{ws:e}=this.server;for(const[t,s]of this.eventMap)e.on(t,s);e.on("error",()=>{this.clearAllPendingSyncActions("disconnected")})}dispose(){this.clearAllPendingSyncActions("shutdown"),this.opts.distService?.stopBuilds()}resolveSyncAction(e,t){const s=this.syncActionResolvers.get(e);s&&(clearTimeout(s.timeoutId),s.cleanup(),this.syncActionResolvers.delete(e),s.resolve(t))}clearAllPendingSyncActions(e){for(const t of[...this.syncActionResolvers.keys()])this.resolveSyncAction(t,{approved:!1,reason:e})}describeSyncCancel(e){switch(e){case"cancelled":return"Sync cancelled by user.";case"timeout":return`Sync cancelled: its dialog was not answered within ${Math.round((this.opts.syncActionTimeoutMs??Ms)/1e3)} s.`;case"disconnected":return"Sync cancelled: the tab that started it lost its connection to the dev server.";case"shutdown":return"Sync cancelled: the dev server is shutting down."}}cancelSync(e,t){const s=this.describeSyncCancel(t);this.sendSyncResponse(e,{cancelled:!0,message:`${s} Backup was saved.`}),this.logger.info(n.colors.yellow(s))}sendSyncResponse(e,t){e.send("template:sync:response",t)}onInfoDataRequest(e,t){t.send("info-data:response",{})}onTemplateSyncActionResponse(e){e&&"string"==typeof e.requestId&&"boolean"==typeof e.approved&&this.resolveSyncAction(e.requestId,e.approved?{approved:!0}:{approved:!1,reason:"cancelled"})}async requestSyncAction(e,t){const s=p.randomUUID(),r=this.opts.syncActionTimeoutMs??Ms;return await new Promise(n=>{const i=e=>this.resolveSyncAction(s,{approved:!1,reason:e}),a=setTimeout(()=>i("timeout"),r),{socket:o}=t,c=()=>i("disconnected");o?.once("close",c),this.syncActionResolvers.set(s,{resolve:n,timeoutId:a,cleanup:()=>o?.off("close",c)}),o&&o.readyState!==o.OPEN?i("disconnected"):t.send("template:sync:action-required",{...e,requestId:s})})}async onTemplateSync(e,t){if(this.syncInFlight)return this.logger.warn(n.colors.yellow("Template sync requested while another one is running; ignored")),void this.sendSyncResponse(t,{error:"A template sync is already running. Wait for it to finish, or answer its dialog in the tab that started it.",code:"SYNC_IN_PROGRESS"});const s=this.runTemplateSync(e,t);this.syncInFlight=s;try{await s}finally{this.syncInFlight=null}}async runTemplateSync(e,t){if(!this.opts.distService||!this.opts.miAPI)return this.sendSyncResponse(t,{error:"Dist service or MiAPI is not defined"}),void this.logger.error(n.colors.red("Dist service or MiAPI is not defined"));{const{distService:e,miAPI:s}=this.opts;try{if(this.server.config.clientInjectionPlugin?.v7Features){if(!s?.isV710OrHigher)return void this.sendSyncResponse(t,{error:"This feature is available only for MI v7.1.0 or higher",config:{canSync:!1}});t.send("client:config:update",{config:{canSync:!0}})}const r=await s.getAssets().catch(async e=>{if(await this.reportMiFailure(t,e))return e;throw e});if(r instanceof Error)return;let i;if(r){const s=await(e?.analyzeBackup(r).catch(e=>e));if(s instanceof Error)i=s;else if(s){await(e?.saveBackup(r,s));const n=0===s.unknownFiles.length&&1===s.versionManifestHashMismatches.length&&L.basename(s.versionManifestHashMismatches[0].relativePath)===bs,a=s.versionManifestHashMismatches,o=a.filter(e=>L.basename(e.relativePath)===bs),c=a.filter(e=>L.basename(e.relativePath)!==bs),l=!n&&o.length>0&&c.length>0,d=n?[]:c.map(e=>e.relativePath),u=async()=>{if(!s.templateVariables||!e)return!0;const{templateVariables:r}=s;if(await e.getPublicTemplateVariablesHash()!==r.actualHash){const s=await this.requestSyncAction({title:"Template variables (server backup)",content:"The server backup includes __template_variables.json. It differs from your local public/__template_variables.json (or that file is missing). Replace your project copy with the server backup?",confirmText:"Replace from server",cancelText:"Keep local"},t);if(s.approved)await e.saveTemplateVariablesFile(r.content);else if("cancelled"!==s.reason)return this.cancelSync(t,s.reason),!1}return!0};if(s.unknownFiles.length>0){const e=await this.requestSyncAction({title:"Unknown files found in backup",content:`Backup contains files not listed in VERSION: ${s.unknownFiles.join(", ")}. Continue sync or cancel?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!e.approved)return void this.cancelSync(t,e.reason)}if(l&&!await u())return;if(!n&&d.length>0){const e=40,s=d,r=s.slice(0,e),n=s.length-r.length,i=r.map(e=>`• ${e}`).join("\n"),a=n>0?`\n... and ${n} more file${1===n?"":"s"}`:"",o=await this.requestSyncAction({title:"VERSION manifest out of date",content:`These files no longer match the hashes recorded in the VERSION manifest:\n\n${i}${a}\n\nCancel sync, or override and continue using the files on disk?`,confirmText:"Override and continue",cancelText:"Cancel sync"},t);if(!o.approved)return void this.cancelSync(t,o.reason)}if(!n&&s.buildManifestMismatch&&0===s.versionManifestHashMismatches.length){const{expected:e,actual:r}=s.buildManifestMismatch,n=await this.requestSyncAction({title:"Build manifest fingerprint mismatch",content:`The recomputed backup fingerprint does not match BUILD-MANIFEST.json.\nManifest: ${e.slice(0,12)}...\nComputed: ${r.slice(0,12)}...\nContinue sync anyway?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!n.approved)return void this.cancelSync(t,n.reason)}if(!l&&!await u())return;i=await(e?.buildNewAssets())}}else i=await(e?.buildNewAssets());if(!(i&&i instanceof Buffer))return i instanceof Error?(this.sendSyncResponse(t,{error:i.message}),void this.logger.error(n.colors.red(i.message))):(this.sendSyncResponse(t,{error:"Failed to build new assets"}),void this.logger.error(n.colors.red("Failed to build new assets")));{if(e.stopped)return this.sendSyncResponse(t,{error:"Sync stopped: the dev server is shutting down."}),void this.logger.warn(n.colors.yellow("Sync stopped before the upload: the dev server is shutting down"));let r;try{r=await s.updateAssets(i)}catch(e){if(await this.reportMiFailure(t,e))return;throw e}if("OK"===r?.status){const s=e?.getBackupMeta();this.sendSyncResponse(t,{syncedAt:(new Date).toISOString(),backupFilename:s?.lastBackupName??""}),this.logger.info(n.colors.green("Template synced"))}else{const e=`Failed to update assets: MI answered ${function(e){if("string"==typeof e){const t=e.replace(/\s+/g," ").trim();return`with a non-JSON body: "${t.slice(0,120)}${t.length>120?"…":""}"`}return e&&"object"==typeof e?`with ${JSON.stringify(e).slice(0,200)}`:`with ${String(e)}`}(r)}`;this.sendSyncResponse(t,{error:e}),this.logger.error(n.colors.red(e))}}}catch(e){const s=e instanceof Error?e.message:"Template sync failed";return this.logger.error(n.colors.red(`Template sync failed: ${s}`)),void this.sendSyncResponse(t,{error:s,code:"SYNC_FAILED"})}}}async reportMiFailure(t,s){if(e.isAxiosError(s)){if("SESSION_EXPIRED"===$e(s).code){this.logger.info(n.colors.yellow("Session expired - attempting to validate credentials"));try{const e=await(this.opts.miAPI?.validateCredentials());e&&!e.isValid?(this.logger.error(n.colors.red(`Authentication error: ${e.error}`)),this.sendSyncResponse(t,{error:e.error??"Authentication failed",code:e.code,refresh:!0})):(this.logger.info(n.colors.yellow("Session expired")),this.sendSyncResponse(t,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0}))}catch{this.logger.info(n.colors.yellow("Session expired")),this.sendSyncResponse(t,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0})}return!0}if(s.cause instanceof Error&&("ECONNRESET"===s.cause.code||"ENOTFOUND"===s.cause.code))return this.logger.info(n.colors.yellow("Server in maintenance mode, VPN connection is needed or no internet connection")),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0;const e=s.response?.status;if(502===e||503===e||504===e)return this.logger.info(n.colors.yellow(`Server in maintenance mode or unreachable (HTTP ${e}); VPN may be required`)),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0}return!!le(s)&&(this.logger.info(n.colors.yellow("Server in maintenance mode or non-JSON page / page-template API response (unavailable HTML body)")),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0)}async onPageVariablesReload(e,t){const{miAPI:s}=this.opts;if(!s)return t.send("page-variables:reload:response",{error:"MiAPI is not defined"}),void this.logger.error(n.colors.red("MiAPI is not defined"));try{const e=await s.reloadPageVariables();t.send("page-variables:reload:response",{ok:!0,count:e?e.length:0,skipped:null===e}),this.logger.info(n.colors.green("Page variables reloaded"))}catch(e){const s=e instanceof Error?e.message:"Reload variables failed";this.logger.error(n.colors.red(`Reload variables failed: ${s}`)),t.send("page-variables:reload:response",{error:s})}}}const Us="/@api/users",_s=new WeakMap;function Hs(e,t){const s=Ue(t,e.name);return{name:e.name,kind:e.kind,...e.state?{state:e.state}:{},..."session"===e.kind?{loginUrl:`${s}/login`}:{},miUser:e.miUser,origin:s}}function Vs(e,t,s,r){e.status(t).json({error:r,code:s})}function qs(e){let t;try{t=JSON.parse(B.readFileSync(e,"utf-8"))}catch(t){return"ENOENT"!==t.code&&n.createLogger().warn(n.colors.yellow(`Could not read the saved users from ${e}: ${String(t)}`)),[]}const s=t&&"object"==typeof t&&!Array.isArray(t)?t.users:void 0;return(Array.isArray(s)?s:[]).filter(e=>"string"==typeof e?.name&&"string"==typeof e.token&&Boolean(e.token))}function zs(e,t,s){const r={version:1,...s,users:t};B.mkdirSync(U.dirname(e),{recursive:!0,mode:448}),function(e,t,s){const r=ss(e);try{O.writeFileSync(r,t,s),O.renameSync(r,e)}catch(e){throw O.rmSync(r,{force:!0}),e}}(e,`${JSON.stringify(r,null,2)}\n`,{mode:384}),B.chmodSync(e,384)}const Ws=new WeakMap,Js=new WeakMap;function Ks(e){Ws.delete(e),Js.get(e)?.(),Js.delete(e)}async function Gs(e,t){const s=function(e,t,s=D.homedir()){const r=u.createHash("sha256").update(`${U.resolve(e)}\n${t.replace(/\/+$/,"")}`).digest("hex").slice(0,16);return U.join(s,".pp-dev","users",`${r}.json`)}(t.projectRoot,t.miUrl,t.homeDir),r={project:U.resolve(t.projectRoot),miUrl:t.miUrl},i=n.createLogger();if(Ws.get(e)===s)return;Ks(e),Ws.set(e,s);const a=qs(s);let o=!0,c=!1,l=e.list().some(e=>"token"===e.kind&&e.token);const d=new Set,p=new Set,h=()=>{const t=e.list(),a=t.filter(e=>"token"===e.kind&&e.token).map(e=>({name:e.name,token:e.token})),o=new Set(t.map(e=>e.name)),c=qs(s).filter(e=>!o.has(e.name)&&!p.has(e.name));try{zs(s,[...a,...c],r)}catch(e){i.warn(n.colors.yellow(`Could not save the users to ${s}: ${String(e)}`))}},g=e.onRemove(t=>{Ws.get(e)===s&&(p.add(t.name),o&&d.add(t.name))}),f=e.onChange(()=>{Ws.get(e)===s&&(o?l||=!c:h())});Js.set(e,()=>{g(),f()});try{const r=await Promise.all(a.map(e=>t.checkToken(e.token)));if(Ws.get(e)!==s)return;a.forEach((t,s)=>{if(Me(t.name)||e.get(t.name)||d.has(t.name))return;const a=r[s];c=!0;try{e.add({name:t.name,kind:"token",token:t.token,...a.ok?{miUser:a.miUser}:{},...!a.ok&&a.rejected?{state:"expired"}:{}})}finally{c=!1}a.ok||i.warn(n.colors.yellow(`Restored user ${t.name}: ${a.message}`))})}finally{o=!1}l&&Ws.get(e)===s&&h(),a.length&&i.info(`${n.colors.blue("Restored")} ${a.length} ${n.colors.blue("saved user(s) from")} ${s}`)}function Xs(e){const t=`${U.resolve(e.projectRoot)}\n${e.miUrl.replace(/\/+$/,"")}`;_e.context!==t&&(Ks(_e),_e.useContext(t)),e.persist?e.miAPI.personalAccessToken?Gs(_e,{projectRoot:e.projectRoot,miUrl:e.miUrl,checkToken:t=>Ke(e.miAPI,t)}).catch(e=>{n.createLogger().warn(n.colors.yellow(`Could not restore the saved users: ${String(e)}`))}):n.createLogger().warn(n.colors.yellow("users.persist is on, but users need your own API token (mi.token or MI_ACCESS_TOKEN).")):Ks(_e)}function Zs(e,t,s,r,n){const i={error:s};r&&(i.details=r),n&&(i.code=n),e.status(t).json(i).end()}function Ys(e){return["/@vite","/@metricinsights","/@",e.endsWith("/")?e.slice(0,-1):e]}function Qs(e,t){const s=t instanceof Error?t.message:String(t);n.createLogger().error(n.colors.red(`Request failed: ${s}`)),e.writableEnded||e.destroyed||(e.headersSent?e.destroy():(e.statusCode=500,e.setHeader("content-type","text/plain; charset=utf-8"),e.end(s)))}const er="10mb",tr=(e,t,s,r)=>{const n="number"==typeof e?.status?e.status:void 0;if(!n||n<400||n>=500||"string"!=typeof e.type||s.headersSent)return void r(e);const i="entity.too.large"===e.type?`The request body is larger than the dev server accepts (${er}).`:`The request body could not be read: ${e.message}`;s.status(n).json({error:i})};exports.DistService=class{root;backupFolder;backupNameTemplate;dateFormat;pageName;currentMeta=null;versionFileTemplate;buildInputFolder;nextBuild;maxBackups;buildTimeoutMs;metaDir;builds=new AbortController;metaLoaded;logger;constructor(e,t){this.pageName=e;const{root:s=N.cwd(),backupFolder:r="backups",backupNameTemplate:i=`{${us}}-{${ps}}.zip`,versionFileTemplate:a="VERSION-v{packageversion}-{currentDate}.json",buildInputFolder:o,dateFormat:c=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,""),nextBuild:l,maxBackups:d=ms,buildTimeoutMs:u=as,metaDir:p}=t||{};this.root=s,this.backupFolder=L.resolve(s,r),this.backupNameTemplate=i,this.dateFormat=c,this.versionFileTemplate=n.normalizeRelativeOutputPath(a,"VERSION file name template"),this.buildInputFolder=o,this.nextBuild=l,this.maxBackups="number"==typeof d&&Number.isInteger(d)&&d>0?d:1/0,this.buildTimeoutMs=u,this.metaDir=void 0===p?L.join(this.backupFolder,".pp-dev-meta"):L.resolve(s,p),this.logger=n.createLogger(),this.metaLoaded=this.loadMeta()}stopBuilds(){this.builds.abort()}async checkMeta(){await l.promises.mkdir(this.metaDir,{recursive:!0}),await l.promises.mkdir(this.backupFolder,{recursive:!0})}async loadMeta(){try{const e=JSON.parse(await this.readMetaFile());this.currentMeta=e&&"object"==typeof e?e:{}}catch(e){this.logger.warn(n.colors.yellow(`[DistService] Could not read the sync meta (${e instanceof Error?e.message:String(e)}); starting a new one`)),this.currentMeta={}}}async meta(){return await this.metaLoaded,this.currentMeta||(this.currentMeta={}),this.currentMeta}async readMetaFile(){return await this.checkMeta(),await l.promises.readFile(L.join(this.metaDir,ws),{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await l.promises.writeFile(L.join(this.metaDir,ws),JSON.stringify(e,null,2),{encoding:"utf-8"})}async syncMeta(){await this.writeMetaFile(await this.meta())}async getLatestSavedBackup(){const{lastBackupName:e}=await this.meta();if(!e)return null;const t=L.resolve(this.backupFolder,e);try{return await l.promises.stat(t),t}catch{return null}}backupName(e,t=new Date){return this.backupNameTemplate.replace(`{${us}}`,e).replace(`{${ps}}`,this.dateFormat(t))}getBackupMeta(){return this.currentMeta}async pruneBackups(e){if(Number.isFinite(this.maxBackups))try{const t=function(e,t,s){const r=s.split(/(\d+)/).map((e,t)=>t%2==1?"\\d+":ys(e)).join(""),n=[{token:`{${us}}`,pattern:ys(t)},{token:`{${ps}}`,pattern:r}].map(t=>({...t,at:e.indexOf(t.token)})).filter(e=>-1!==e.at).sort((e,t)=>e.at-t.at);let i="^",a=0;for(const{token:t,pattern:s,at:r}of n)i+=ys(e.slice(a,r))+s,a=r+t.length;return new RegExp(`${i}${ys(e.slice(a))}$`)}(this.backupNameTemplate,this.pageName,this.dateFormat(new Date)),s=new Set([e]),r=await l.promises.readdir(this.backupFolder,{withFileTypes:!0}),i=(await Promise.all(r.filter(e=>e.isFile()&&t.test(e.name)).map(async e=>({name:e.name,mtimeMs:(await l.promises.stat(L.resolve(this.backupFolder,e.name))).mtimeMs})))).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.name.localeCompare(e.name)),a=i.filter(e=>s.has(e.name)).length,o=i.filter(e=>!s.has(e.name)).slice(Math.max(0,this.maxBackups-a));for(const e of o)await l.promises.unlink(L.resolve(this.backupFolder,e.name));o.length>0&&this.logger.info(n.colors.gray(`[DistService] Deleted ${o.length} old backup(s), keeping the latest ${this.maxBackups}`))}catch(e){this.logger.warn(n.colors.yellow(`[DistService] Could not delete old backups: ${e instanceof Error?e.message:String(e)}`))}}pathToPosix(e){return e.replace(/\\/g,"/")}normalizeBackupManifestPath(e){try{return n.normalizeRelativeOutputPath(e,"VERSION manifest file path")}catch{throw new Error(`VERSION manifest file path "${e}" resolves outside the backup root`)}}async normalizeExtractedRootDir(e){let t=e;for(;;){const e=await l.promises.readdir(t,{withFileTypes:!0});if(1!==e.length||!e[0]?.isDirectory())return t;t=L.join(t,e[0].name)}}async listFilesRecursive(e){const t=await l.promises.readdir(e,{withFileTypes:!0}),s=[];for(const r of t){const t=L.join(e,r.name);r.isDirectory()?s.push(...await this.listFilesRecursive(t)):r.isFile()&&s.push(t)}return s}buildManifestChecksum(e){const t=Object.keys(e).sort().map(t=>e[t]).join("");return j.createHash("sha256").update(t).digest("hex")}buildBackupFingerprint(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("\n");return j.createHash("sha256").update(t,"utf-8").digest("hex")}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}versionFileTemplateMatcher(){const e=/\{[^}]+\}/g,t=[];let s=0,r=null;for(;r=e.exec(this.versionFileTemplate),r;){const[e]=r,n=this.versionFileTemplate.slice(s,r.index);t.push(this.escapeRegExp(n)),t.push("[^/]+"),s=r.index+e.length}const n=this.versionFileTemplate.slice(s);return t.push(this.escapeRegExp(n)),new RegExp(`^${t.join("")}$`,"i")}isTemplateVariablesBasename(e){return e===bs}async pickTemplateVariablesFromBackupZip(e,t){const s=e.find(e=>L.basename(e)===bs);if(!s)return null;const r=L.join(t,s),n=await l.promises.readFile(r);return{relativePath:s,content:n,actualHash:j.createHash("sha256").update(n).digest("hex"),manifestHash:null}}async resolveBackupAnalysisFromZip(e){const t=await l.promises.mkdtemp(L.join(R.tmpdir(),"pp-dev-backup-")),s=L.join(t,"backup.zip"),r=L.join(t,"extracted");try{await l.promises.mkdir(r,{recursive:!0}),await l.promises.writeFile(s,e),await ts(s,r);const t=await this.normalizeExtractedRootDir(r),i=(await this.listFilesRecursive(t)).map(e=>this.pathToPosix(L.relative(t,e))),a=i.filter(e=>L.basename(e)===vs);if(a.length>1)throw new Error(`Expected at most one ${vs} in backup ZIP, found ${a.length}`);const o=1===a.length?a[0]:null;let c=null;if(o){const e=L.join(t,o);if(c=JSON.parse(await l.promises.readFile(e,"utf-8")),!(c&&"pp-dev-build-manifest"===c.manifestType&&"string"==typeof c.versionFile&&c.versionFile.trim()&&"string"==typeof c.versionFileTemplate&&c.versionFileTemplate.trim()&&"string"==typeof c.buildFingerprint&&c.buildFingerprint.trim()))throw new Error("Build manifest is missing required fields")}let d=null;if(c){const e=this.pathToPosix(c.versionFile.trim()),t=i.filter(t=>t===e),s=i.filter(t=>L.basename(t)===L.basename(e)),r=t.length>0?t:s;if(r.length>1)throw new Error(`Build manifest version file "${c.versionFile}" must resolve to exactly one file in backup ZIP, found ${r.length}`);if(1===r.length&&(d=r[0]),!0===c.compat?.versionFileRequired&&null===d)throw new Error(`Build manifest requires version file "${c.versionFile}", but it is missing in backup ZIP`)}else{const e=this.versionFileTemplateMatcher(),t=i.filter(t=>e.test(L.basename(t)));if(t.length>1)throw new Error(`Expected exactly one version file matching template "${this.versionFileTemplate}" in backup ZIP, found ${t.length}`);1===t.length&&(d=t[0])}const u={};let p=null,h=null,g=[];if(d){const e=L.join(t,d),s=JSON.parse(await l.promises.readFile(e,"utf-8"));if(!s?.files||"object"!=typeof s.files)throw new Error("VERSION manifest files map is missing or invalid");if("string"!=typeof s.checksum||!s.checksum)throw new Error("VERSION manifest checksum is missing or invalid");h=s.checksum;for(const[e,t]of Object.entries(s.files)){if("string"!=typeof t||!t.trim())throw new Error(`VERSION manifest contains invalid hash for file: ${e}`);const s=this.normalizeBackupManifestPath(e);if(Object.prototype.hasOwnProperty.call(u,s))throw new Error(`VERSION manifest contains duplicate normalized file path: ${s}`);u[s]=t}if(this.buildManifestChecksum(u)!==s.checksum)throw new Error("VERSION manifest checksum does not match its files map");for(const[e,s]of Object.entries(u)){const r=L.join(t,e),n=await l.promises.readFile(r).catch(()=>null);if(!n)throw new Error(`VERSION manifest references missing file: ${e}`);const i=j.createHash("sha256").update(n).digest("hex");i!==s&&g.push({relativePath:e,expected:s,actual:i}),this.isTemplateVariablesBasename(L.basename(e))&&(p={relativePath:e,content:n,actualHash:i,manifestHash:s})}g.length>0&&this.logger.warn(n.colors.yellow(`[DistService] VERSION manifest hash mismatch for ${g.length} file(s) (confirm in UI): ${g.map(e=>e.relativePath).join(", ")}`))}const f={},m=[];for(const e of i){if(e===o)continue;if(d&&e===d)continue;const s=L.join(t,e),r=await l.promises.readFile(s);f[e]=j.createHash("sha256").update(r).digest("hex"),d&&!Object.prototype.hasOwnProperty.call(u,e)&&m.push(e)}p||(p=await this.pickTemplateVariablesFromBackupZip(i,t));const y=this.buildBackupFingerprint(f);let w=null;return c&&d&&y!==c.buildFingerprint&&(w={expected:c.buildFingerprint,actual:y},this.logger.warn(n.colors.yellow(`[DistService] Build manifest fingerprint mismatch (confirm in UI): expected ${c.buildFingerprint}, got ${y}`))),{backupFingerprint:y,unknownFiles:m,templateVariables:p,mainHash:h,buildManifestMismatch:w,versionManifestHashMismatches:g}}finally{await l.promises.rm(t,{recursive:!0,force:!0})}}async analyzeBackup(e){if(!fs.equals(e.subarray(0,fs.length)))throw new Error("Backup file is not a ZIP file");return await this.resolveBackupAnalysisFromZip(e)}async getPublicTemplateVariablesHash(){const e=L.resolve(this.root,"public",bs),t=await l.promises.readFile(e).catch(()=>null);return t?j.createHash("sha256").update(t).digest("hex"):null}async readPublicTemplateVariablesFile(){const e=L.resolve(this.root,"public",bs);return await l.promises.readFile(e).catch(()=>null)}async saveTemplateVariablesFile(e){const t=L.resolve(this.root,"public",bs);return await l.promises.mkdir(L.dirname(t),{recursive:!0}),await function(e,t,s){const r=(rs.get(e)??Promise.resolve()).then(()=>ns(e,t,s),()=>ns(e,t,s)),n=()=>{rs.get(e)===r&&rs.delete(e)};return rs.set(e,r),r.then(n,n),r}(t,e),t}async saveBackup(e,t){const s=(t??await this.analyzeBackup(e)).backupFingerprint,r=await this.getLatestSavedBackup(),i=await this.meta();if(r&&i.lastBackupHash===s)return void this.logger.info(n.colors.yellow(`[DistService] Backup skipped: same backup fingerprint as last saved (${s.slice(0,12)}...)`));const a=new Date,o=this.backupName(this.pageName,a);i.lastBackupName=o,i.lastBackupHash=s,i.lastBackupDate=a.toISOString(),delete i.lastMainHash,await this.syncMeta(),await l.promises.writeFile(L.resolve(this.backupFolder,o),e),this.logger.info(`Backup saved to ${o}`),await this.pruneBackups(o)}async buildNewAssets(){if(this.nextBuild)return await this.buildNextAssets();this.logger.info(n.colors.cyan("[DistService] Build started"));const e=cs("pp-dev build",N.execPath,[L.resolve(gs,"./bin/pp-dev.js"),"build"],{cwd:this.root,env:Object.assign({},N.env,{NODE_ENV:"production"}),timeoutMs:this.buildTimeoutMs,signal:this.builds.signal});try{if(await this.logBuild("Build",e),!this.buildInputFolder)throw new Error("The sync has no build directory to zip (build.outDir or build.zip.inDir)");const t=L.resolve(this.root,this.buildInputFolder);if(!await this.isDirectory(t))throw new Error(`Build input directory ${t} not found`);const s=await es(t);return this.throwIfStopped("pp-dev build"),s}catch(e){throw this.logger.error(e instanceof Error?e.stack??e.message:String(e)),e}}async saveBackupAndBuild(e){return await this.saveBackup(e),await this.buildNewAssets()}async buildNextAssets(){const{projectRoot:e,distDir:t,buildDistDir:s=t,output:i,configWrapped:a}=this.nextBuild,o=a||s===ls?"out":s,c=L.resolve(e,o);if(a&&function(e,t){const s=L.relative(t,e);return""===s||!(".."===s||s.startsWith(`..${L.sep}`)||L.isAbsolute(s))}(L.resolve(e,t),c))throw new Error(`The app's distDir (${t}) is inside the sync's export directory (${o}), which next build empties: set another distDir in next.config.`);const d=is(e,{output:i,distDir:t});if(d&&this.logger.info(n.colors.dim(`[DistService] Removed stale dev route types: ${L.relative(e,d)}`)),a||o!==t||this.logger.warn(n.colors.yellow(`⚠️ next.config is not wrapped with withPPDev(): the sync's build exports into ${t} and removes the dev server's ${L.join(t,"dev")}; restart pp-dev next after the sync`)),a&&await l.promises.rm(c,{recursive:!0,force:!0}),this.logger.info(n.colors.cyan("[DistService] Next.js build started")),await this.logBuild("Next.js build",ds(e,{timeoutMs:this.buildTimeoutMs,signal:this.builds.signal,distDir:a?ls:void 0})),!await this.isDirectory(c))throw new Error(`Next.js build output directory not found: ${c}. The sync needs "output: 'export'" in next.config (static export).`);this.throwIfStopped("next build"),await r.writeBuildVersionManifest({outDir:c,root:e,packageVersion:this.nextBuild.packageVersion,versionFileTemplate:this.versionFileTemplate,packageRepositoryUrl:this.nextBuild.packageRepositoryUrl,packageBranchName:this.nextBuild.packageBranchName}),this.throwIfStopped("next build");const u=await es(c);return this.throwIfStopped("next build"),u}get stopped(){return this.builds.signal.aborted}throwIfStopped(e){if(this.stopped)throw new Error(`${e} was stopped`)}async logBuild(e,t){try{await t}catch(t){const s=this.builds.signal.aborted;throw this.logger.info(n.colors.yellow(`[DistService] ${e} ${s?"stopped":"failed"}`)),t}this.logger.info(n.colors.cyan(`[DistService] ${e} finished`))}async isDirectory(e){try{return(await l.promises.stat(e)).isDirectory()}catch{return!1}}},exports.INSPECTOR_PATH=W,exports.PP_DEV_HMR_WS_PATH="/@pp-dev-hmr",exports.createInternalServer=function({allowedHosts:e=[]}={}){const t=_();return t.use(n.createOriginGuard(e)),t.use(_.json({limit:er})),t.use(_.urlencoded({extended:!0})),t.use(tr),t},exports.createMiddlewareChain=function(e){const{base:t,templateName:s,internalServer:r,backendBaseURL:i,inspector:a,proxy:o}=e,c=[],l=[];if(i){const e=He();c.push(e),l.push(e)}if(a.enabled){const e=new Qt(a.maxMemory);G(r,e,a.captureLimit),c.push(Xt(e,a.captureLimit))}const d=Ce(t,s);if(c.push(d),l.push(d),e.devPanelAssets){const e=n.createDevPanelAssetMiddleware(t);c.push(e),l.push(e)}if(a.enabled||i){const e=(e,t,s)=>{const n=e.url??"";n.startsWith("/@api/")||n.startsWith(W)||n.startsWith(js)?r(e,t,e=>function(e,t){t?Qs(e,t):e.headersSent||e.writableEnded||(e.statusCode=404,e.setHeader("content-type","application/json"),e.end(JSON.stringify({error:"Not found"})))}(t,e)):s()};c.push(e),l.push(e)}let u=null,p=null,h=null;if(i){const r=function(e,t){return{headers:{host:new URL(e).host,referer:e,origin:e.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:t.appId,templateLess:t.templateLess,disableSSLValidation:t.disableSSLValidation,v7Features:t.v7Features,personalAccessToken:t.personalAccessToken??process.env.MI_ACCESS_TOKEN}}(i,e.mi);u=new Re(i,r),o.cache&&(p=function(e){const t=Number(e);return!t||Number.isNaN(t)||t<0?6e5:t}(o.cacheTtl),c.push($t({devServer:o.devServer,ttl:p}))),c.push(Nt(function(e){return new RegExp(`^((${t=e,t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`);var t}(t),u,{...e.mi,base:t,appBase:t})),c.push(ot({baseURL:i,proxyIgnore:[...Ys(t),...o.ignore??[]],disableSSLValidation:e.mi.disableSSLValidation,miAPI:u,templateName:s}));const n=e.rewrite(u,new URL(i).host);h=Mt((e,t)=>n.predicate(e,t),(e,t)=>n.transform(e,t),n.contentType?{contentType:n.contentType}:{})}return{main:c,essential:l,rewrite:h,mi:u,proxyCacheTtl:p}},exports.extractZipSafe=ts,exports.mountMiddlewareChain=function(e,t){for(const s of t.main)e.middlewares.use(s)},exports.removeStaleDevTypes=is,exports.runMiddlewareChain=function(e,t,s,r){let n=0;const i=a=>{if(a)return void Qs(s,a);if(n>=e.length)return void r();const o=e[n];n+=1;try{o(t,s,i)}catch(e){Qs(s,e)}};i()},exports.runNextBuildProcess=ds,exports.startSyncAndUsers=function(e){const{distService:t,miAPI:s,persistUsers:r,projectRoot:i,miUrl:a}=e,o=new Ds(e.server,{distService:t,miAPI:s});return function(e,t){const{miAPI:s,persistUsers:r,projectRoot:i,miUrl:a}=t,o=n.createLogger(),c=(e,t,s)=>{o.error(`${s} token validation error: ${t instanceof Error?t.message:String(t)}`);const r=$e(t),n=t?.tokenErrorInfo;if(n)return Zs(e,n.status||500,n.userFriendlyMessage,n.message,n.code),null;let i,a,c;switch(r.code){case"SESSION_EXPIRED":i=412,a="personal"===s?"Personal access token expired":"Session expired",c="personal"===s?"PAT_EXPIRED":"SESSION_EXPIRED";break;case"UNAUTHORIZED":i=401,a="Unauthorized",c="UNAUTHORIZED";break;case"FORBIDDEN":i=403,a="Access forbidden",c="FORBIDDEN";break;default:i=500,a="Internal server error",c=r.code}return Zs(e,i,a,"personal"===s&&"PAT_EXPIRED"===c?"Your personal access token has expired. Please generate a new token from the portal.":"regular"===s&&"SESSION_EXPIRED"===c?"Your portal session has expired. Please refresh your token or re-authenticate.":r.userFriendlyMessage,c),null};e.post("/@api/login",async(e,t)=>{const{token:n,tokenType:l}=e.body??{};if(De(e.headers.host))Zs(t,409,"Token login is only available on the main host","This tab belongs to a saved pp-dev user. Log in with a token on the main host (localhost).","USER_HOST");else if("string"==typeof n&&n)if(o.info(`Attempting to validate ${String(l)} token...`),"personal"===l){if(!await s.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${n}`},!0).then(e=>"object"!=typeof e.data||null===e.data?(Zs(t,502,"MI is unavailable","The instance may be down or in maintenance mode. Please try again later.","MI_UNAVAILABLE"),null):"number"==typeof e.data?.user?.user_id?(s.personalAccessToken=n,o.info(`Personal access token validated successfully for user ${e.data.user.user_id}`),e):(Zs(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"personal")))return;mt("logged in with a personal access token"),Xs({persist:r,miAPI:s,projectRoot:i,miUrl:a}),Pe(t,"/",302)}else if("regular"===l){if(!await s.get("/api/user",{"Content-Type":"application/json",Accept:"application/json",Token:n},!0).then(r=>r.data?.users?.length?(s.personalAccessToken=void 0,o.info(`Regular token validated successfully for ${r.data.users.length} user(s)`),t.setHeader("set-cookie",ve(r.headers["set-cookie"],he(e))??""),r):(Zs(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"regular")))return;mt("logged in with a token"),Pe(t,"/",302)}else Zs(t,400,"Invalid tokenType",'tokenType must be "personal" or "regular".',"INVALID_TOKEN_TYPE");else Zs(t,400,"Token is required")})}(e.internalServer,{miAPI:s,persistUsers:r,projectRoot:i,miUrl:a}),Fs(e.internalServer,{distService:t,miAPI:s}),function(e,t){const s=_s.get(e);if(s)return void(s.deps=t);const r={deps:t};_s.set(e,r);const i=n.createLogger(),a=()=>r.deps.users??_e;e.get(Us,(e,t)=>{const s=a();t.json({available:Boolean(r.deps.miAPI.personalAccessToken),users:s.list().map(t=>Hs(t,e)),defaultUser:s.defaultUser?.name??null})}),e.put(`${Us}/default`,(e,t)=>{const s=a(),r=(e.body??{}).name;if(null===r||"string"==typeof r)if(null===r||s.get(r)){try{s.setDefaultUser(r??void 0)}catch(e){return void Vs(t,409,"NOT_LOGGED_IN",e instanceof Error?e.message:String(e))}i.info(`${n.colors.blue("Default user:")} ${n.colors.yellow(r??"the original user")}`),t.json({defaultUser:r})}else Vs(t,404,"NOT_FOUND",`There is no user named "${r}"`);else Vs(t,400,"INVALID_NAME","name must be a user name or null")}),e.post(Us,async(e,t)=>{const{miAPI:s}=r.deps,o=a(),c=e.body??{},l="string"==typeof c.name?c.name:"",d="string"==typeof c.token?c.token.trim():"",u=c.kind??"token";if("token"!==u&&"session"!==u)return void Vs(t,400,"INVALID_KIND",'kind must be "token" or "session"');if(!s.personalAccessToken)return void Vs(t,409,"ORIGINAL_TOKEN_REQUIRED","Adding users needs your own API token: set mi.token or MI_ACCESS_TOKEN.");const p=Me(l);if(p)return void Vs(t,400,"INVALID_NAME",p);if(o.get(l))return void Vs(t,409,"NAME_TAKEN",`A user named "${l}" already exists`);if("session"===u){const s=o.add({name:l,kind:"session"});return i.info(`${n.colors.blue("Added user")} ${n.colors.yellow(s.name)}: log in at ${Ue(e,s.name)}/login`),void t.status(201).json({user:Hs(s,e)})}if(!d)return void Vs(t,400,"TOKEN_REQUIRED","The API token is required");const h=o.context,g=await Ke(s,d);if(o.context!==h||r.deps.miAPI!==s||a()!==o)return void Vs(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; add the user again");if(!g.ok)return void(g.rejected?Vs(t,400,"INVALID_TOKEN",g.message):Vs(t,502,"MI_UNAVAILABLE",g.message));const{miUser:f}=g;let m;try{m=o.add({name:l,kind:"token",token:d,miUser:f})}catch(e){return void Vs(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}i.info(`${n.colors.blue("Added user")} ${n.colors.yellow(m.name)} (MI user ${f.id}${f.username?`, ${f.username}`:""}) at ${Ue(e,m.name)}`),t.status(201).json({user:Hs(m,e)})}),e.patch(`${Us}/:name`,async(e,t)=>{const{miAPI:s}=r.deps,o=a(),c=String(e.params.name),l=o.get(c),d=e.body??{},u="string"==typeof d.name&&d.name?d.name:c,p="string"==typeof d.token?d.token.trim():"";if(!l)return void Vs(t,404,"NOT_FOUND",`There is no user named "${c}"`);if("token"!==l.kind)return void Vs(t,400,"NOT_EDITABLE","Only users added with an API token can be edited. Remove this user and add it again.");const h=Me(u);if(h)return void Vs(t,400,"INVALID_NAME",h);if(u!==c&&o.get(u))return void Vs(t,409,"NAME_TAKEN",`A user named "${u}" already exists`);let g,f={...l,name:u};if(p&&(p!==l.token||"expired"===l.state)){const e=o.context,n=await Ke(s,p);if(o.context!==e||r.deps.miAPI!==s||a()!==o)return void Vs(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; edit the user again");if(!n.ok)return void(n.rejected?Vs(t,400,"INVALID_TOKEN",n.message):Vs(t,502,"MI_UNAVAILABLE",n.message));const{state:i,...c}=f;f={...c,token:p,miUser:n.miUser}}if(o.get(c)===l)if(u!==c||f.token!==l.token||f.state!==l.state){try{g=o.replace(c,f)}catch(e){return void Vs(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}i.info(`${n.colors.blue("Edited user")} ${n.colors.yellow(c)}${u!==c?` → ${n.colors.yellow(u)}`:""}${g.token!==l.token?" (new API token)":""}`),t.json({user:Hs(g,e)})}else t.json({user:Hs(l,e)});else Vs(t,409,"USER_CHANGED",`The user "${c}" changed meanwhile; edit it again`)}),e.delete(`${Us}/:name`,(e,t)=>{const s=String(e.params.name);a().remove(s)?(i.info(`${n.colors.blue("Removed user")} ${n.colors.yellow(s)}`),t.status(204).end()):Vs(t,404,"NOT_FOUND",`There is no user named "${s}"`)})}(e.internalServer,{miAPI:s}),Xs({persist:r,miAPI:s,projectRoot:i,miUrl:a}),o},exports.urlReplacer=Te,exports.zipDirectoryToBuffer=es;
2
- //# sourceMappingURL=internal.middleware-63EM6Z98.js.map