@metricinsights/pp-dev 1.5.0-beta.32 → 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 (56) hide show
  1. package/TEMPLATE_VARIABLES.md +25 -25
  2. package/dist/cjs/auth.provider-6rZUaR33.js +2 -0
  3. package/dist/cjs/auth.provider-6rZUaR33.js.map +1 -0
  4. package/dist/cjs/cli.js +1 -1
  5. package/dist/cjs/cli.js.map +1 -1
  6. package/dist/cjs/index-Cc-bAhnE.js +2 -0
  7. package/dist/cjs/index-Cc-bAhnE.js.map +1 -0
  8. package/dist/cjs/index.js +1 -1
  9. package/dist/cjs/internal.middleware-BlM7gqkq.js +2 -0
  10. package/dist/cjs/internal.middleware-BlM7gqkq.js.map +1 -0
  11. package/dist/cjs/migrate-DDdeB-Fj.js +2 -0
  12. package/dist/cjs/{migrate-Gi9k9cLw.js.map → migrate-DDdeB-Fj.js.map} +1 -1
  13. package/dist/cjs/plugin.js +1 -1
  14. package/dist/cjs/plugin.js.map +1 -1
  15. package/dist/cjs/{version-manifest-CVBuIKBS.js → version-manifest-DdWlzzZ6.js} +2 -2
  16. package/dist/cjs/{version-manifest-CVBuIKBS.js.map → version-manifest-DdWlzzZ6.js.map} +1 -1
  17. package/dist/cjs/version-plugin-B1Sb07cW.js +2 -0
  18. package/dist/cjs/{version-plugin-DBdqn2Rn.js.map → version-plugin-B1Sb07cW.js.map} +1 -1
  19. package/dist/client/index.html +1 -3
  20. package/dist/client/request-inspector.html +90 -79
  21. package/dist/client/variables-editor.html +47 -40
  22. package/dist/esm/auth.provider-BFK6x9Df.js +2 -0
  23. package/dist/esm/auth.provider-BFK6x9Df.js.map +1 -0
  24. package/dist/esm/cli.js +1 -1
  25. package/dist/esm/cli.js.map +1 -1
  26. package/dist/esm/index-PvH-M_Io.js +2 -0
  27. package/dist/esm/index-PvH-M_Io.js.map +1 -0
  28. package/dist/esm/index.js +1 -1
  29. package/dist/esm/internal.middleware-CC20He9L.js +2 -0
  30. package/dist/esm/internal.middleware-CC20He9L.js.map +1 -0
  31. package/dist/esm/migrate-C1MkJPzS.js +2 -0
  32. package/dist/esm/{migrate-CCBRuVfj.js.map → migrate-C1MkJPzS.js.map} +1 -1
  33. package/dist/esm/plugin.js +1 -1
  34. package/dist/esm/plugin.js.map +1 -1
  35. package/dist/esm/version-manifest-BVgENnKn.js +2 -0
  36. package/dist/esm/{version-manifest-CyzmnFOe.js.map → version-manifest-BVgENnKn.js.map} +1 -1
  37. package/dist/esm/version-plugin-CA9HNV-6.js +2 -0
  38. package/dist/esm/{version-plugin-6rxIgQ-I.js.map → version-plugin-CA9HNV-6.js.map} +1 -1
  39. package/package.json +1 -1
  40. package/dist/cjs/auth.provider-fI0tFsf5.js +0 -2
  41. package/dist/cjs/auth.provider-fI0tFsf5.js.map +0 -1
  42. package/dist/cjs/index-CZ7sZQJX.js +0 -2
  43. package/dist/cjs/index-CZ7sZQJX.js.map +0 -1
  44. package/dist/cjs/migrate-Gi9k9cLw.js +0 -2
  45. package/dist/cjs/request-capture.middleware-C9SbJkfk.js +0 -2
  46. package/dist/cjs/request-capture.middleware-C9SbJkfk.js.map +0 -1
  47. package/dist/cjs/version-plugin-DBdqn2Rn.js +0 -2
  48. package/dist/esm/auth.provider-DDUsu1H1.js +0 -2
  49. package/dist/esm/auth.provider-DDUsu1H1.js.map +0 -1
  50. package/dist/esm/index-GSdCxN3K.js +0 -2
  51. package/dist/esm/index-GSdCxN3K.js.map +0 -1
  52. package/dist/esm/migrate-CCBRuVfj.js +0 -2
  53. package/dist/esm/request-capture.middleware-B2BGaP0g.js +0 -2
  54. package/dist/esm/request-capture.middleware-B2BGaP0g.js.map +0 -1
  55. package/dist/esm/version-manifest-CyzmnFOe.js +0 -2
  56. package/dist/esm/version-plugin-6rxIgQ-I.js +0 -2
@@ -0,0 +1,2 @@
1
+ import{execSync as e}from"child_process";import{o as t,p as n,q as s,s as i,t as r,P as o,u as a,v as c,n as p,l,e as u,g as f,k as m,c as d,a as v,d as g,f as h,w as _,x as y}from"./auth.provider-BFK6x9Df.js";import{createRequire as j}from"node:module";import{normalizePath as w,loadEnv as b}from"vite";import{readdirSync as E,readFileSync as P,writeFileSync as T,unlinkSync as D}from"fs";import*as I from"path";import $ from"path";import{pathToFileURL as O}from"url";import"./helpers.js";const R=w(I.join(r,"dist/client")),S=new RegExp(`^\\/?${i}\\/client\\/(.*)$`);const N=(e,t)=>` * ${t}`;function F(e){return`/*!\n${"***** DO NOT EDIT THIS CODE! *****\n***** ------- *****".replace(/^(.*)$/gm,N)}\n */`}async function x(){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 L=()=>j(import.meta.url);async function C(){try{return L().resolve("next"),!0}catch{return!1}}async function Z(){try{const e=L()("next/package.json");return"string"==typeof e.version?e.version:null}catch{return null}}let U=new Set;function M(e="development",t=process.cwd()){for(const e of U)delete process.env[e];const n=new Set(Object.keys(process.env).filter(e=>e.startsWith("MI_"))),s=b(e,t,"MI_");for(const[e,t]of Object.entries(s))process.env[e]=t;return U=new Set(Object.keys(s).filter(e=>!n.has(e))),s}const V=Object.freeze({__proto__:null,loadPPDevEnv:M}),k=Symbol.for("@metricinsights/pp-dev:withPPDev");function A(){return globalThis[k]}function B(){delete globalThis[k]}const H=new Map,z=new Map;function q(e=process.cwd()){const t=Date.now(),n=$.resolve(e),s=z.get(n);if(s&&t-s.timestamp<6e4)return s.data;try{const e=JSON.parse(P($.resolve(n,"package.json"),{encoding:"utf-8",flag:"r"}));return z.set(n,{data:e,timestamp:t}),e}catch{const e={};return z.set(n,{data:e,timestamp:t}),e}}let J=null;const W="__pp_dev_injected_dirname",G="__pp_dev_injected_filename",K="__pp_dev_injected_import_meta_url",Y={__dirname:W,__filename:G,"import.meta.url":K,"import.meta.dirname":W,"import.meta.filename":G},Q={name:"pp-dev:config-module-location",setup(e){e.onLoad({filter:/\.([cm]?[jt]s|[jt]sx)$/},e=>{const t=P(e.path,"utf-8").replace(/^#![^\r\n]*/,"");return{contents:`const ${W} = ${JSON.stringify($.dirname(e.path))};const ${G} = ${JSON.stringify(e.path)};const ${K} = ${JSON.stringify(O(e.path).href)};`+t,loader:e.path.endsWith(".tsx")?"tsx":e.path.endsWith(".jsx")?"jsx":/ts$/.test(e.path)?"ts":"js"}})}};async function X(e,t){const n=`bundled:${e}`,s=H.get(n);if(s&&Date.now()-s.timestamp<3e4)return s.data;let i=!1;if(/\.m[jt]s$/.test(e))i=!0;else if(/\.c[jt]s$/.test(e))i=!1;else{const e=q(t);i=!!e&&"module"===e.type}const r=await async function(){return J||(J=await(import("esbuild"))),J}(),o=await r.build({absWorkingDir:t,entryPoints:[e],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:i?"esm":"cjs",mainFields:["main"],sourcemap:"inline",metafile:!0,plugins:[Q],define:Y,...i?{banner:{js:"import { createRequire as __ppDevCreateRequire } from 'node:module';const require = __ppDevCreateRequire(import.meta.url);"}}:{}}),{text:a}=o.outputFiles[0],c=`${`pp-config.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.${i?"mjs":"cjs"}`,p=$.resolve(t,c),l=O(p).toString();T(p,a);let u={};try{const t=(await(import(l))).default;u=t?.default||t,H.set(n,{data:u,timestamp:Date.now(),filePath:e})}finally{try{D(p)}catch{}}return u}async function ee(e){const t=`json:${e}`,n=H.get(t);if(n&&Date.now()-n.timestamp<3e4)return n.data;const s=JSON.parse(P(e,{encoding:"utf-8"}));return H.set(t,{data:s,timestamp:Date.now(),filePath:e}),s}const te=new Map;function ne(e=process.cwd()){return q(e)}async function se(e=process.cwd()){return(await ie(e)).config}async function ie(e=process.cwd()){const t=$.resolve(e),n=function(e){const t=Date.now(),n=te.get(e);if(n&&t-n.timestamp<1e4)return n.files;const s=/\.config\.(([cm]?ts)|([cm]?js)|(json))$/,i=E(e,{withFileTypes:!0}).filter(e=>e.isFile()&&s.test(e.name)).map(e=>e.name);return te.set(e,{files:i,timestamp:t}),i}(t),s=o,i=s.some(e=>n.includes(e)),r=q(t),a=Object.prototype.hasOwnProperty.call(r,"pp-dev"),c=i?await async function(e,t,n){for(const s of t)if(e.includes(s)){const e=$.resolve(n,s);if(/\.[cm]?[jt]s$/i.test(s))return await X(e,n);if(s.endsWith(".json"))return await ee(e)}return null}(n,s,t):null;if(c)return{config:c,found:!0};const p=r["pp-dev"];return p&&"object"==typeof p&&!Array.isArray(p)?{config:p,found:!0}:{config:{},found:i||a}}const re=Object.freeze({__proto__:null,clearConfigCache:function(){H.clear(),z.clear(),te.clear()},findConfig:ie,getConfig:se,getPkg:ne});function oe(e){if(void 0!==e)return"1"===e||"true"===e.toLowerCase()||"0"!==e&&"false"!==e.toLowerCase()&&void 0}function ae(e){return{distZipEnabled:e.distZip??oe(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??oe(process.env.PP_DEV_VERSION_MANIFEST),versionFileTemplate:e.versionFileTemplate??process.env.PP_DEV_VERSION_FILE_TEMPLATE}}function ce(e,t,n){if(!1===t.distZipEnabled)return!1;if(!0!==t.distZipEnabled&&void 0===t.distZipDir&&void 0===t.distZipFilename)return!1!==e&&{...e,outFileName:a(e.outFileName,"ZIP output file name")};const s=!1===e?{outFileName:n,outDir:"dist-zip"}:e,i=t.distZipFilename??s.outFileName;return{...s,...void 0!==t.distZipDir?{outDir:t.distZipDir}:{},outFileName:a(i,"ZIP output file name")}}function pe(e,t){if(!1===t.versionManifestEnabled)return!1;if(!0!==t.versionManifestEnabled&&void 0===t.versionFileTemplate)return!1!==e&&void 0!==e.versionFileTemplate?{...e,versionFileTemplate:a(e.versionFileTemplate,"VERSION file name template")}:e;const n=!1===e?{enabled:!0}:e,s=t.versionFileTemplate??n.versionFileTemplate,i=void 0!==s?a(s,"VERSION file name template"):void 0;return{...n,enabled:!0,...void 0!==i?{versionFileTemplate:i}:{}}}const le=new Set(["mi","app","proxy","build","sync","inspector","devPanel","users","server"]);function ue(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 s=process.env.GITHUB_REPOSITORY;if("string"==typeof s&&s.trim()){return`${(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,"")}/${s.replace(/^\/+/,"")}`}const i=process.env.CI_PROJECT_PATH;if("string"==typeof i&&i.trim()){return`${(process.env.CI_SERVER_URL||"https://gitlab.com").replace(/\/+$/,"")}/${i.replace(/^\/+/,"")}`}const r=process.env.BITBUCKET_REPO_FULL_NAME;if("string"==typeof r&&r.trim())return`https://bitbucket.org/${r.replace(/^\/+/,"")}`;const o=process.env.TRAVIS_REPO_SLUG;if("string"==typeof o&&o.trim())return`https://github.com/${o.replace(/^\/+/,"")}`;try{const t=e("git config --get remote.origin.url",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t)return t}catch{}}async function fe(e,r={}){const o=r.root??process.cwd();M(r.mode,o);const a=ne(o),m=await se(o);c(m,a.name);const d=p(m,a.name),{templateName:v}=d;e&&(d.distZip=ce(d.distZip,e,l(v)),d.versionPlugin=pe(d.versionPlugin,e));const{default:g}=await(import("./plugin.js")),h=[g(d),{name:"pp-dev:client",apply:"serve",config:e=>(e.optimizeDeps?.exclude?.push(`${i}/client`),e),resolveId(e){const t=e.match(S);if(t){const e=w(I.join(R,t[1]));return e.startsWith(`${R}/`)?{id:e}:null}},transformIndexHtml:async(e,t)=>{const i=t.server?.config.base||"",r=n(i),o={html:e,tags:[{tag:"link",injectTo:"head",attrs:{rel:"stylesheet",href:r.css}}]},{templateLess:a=!1,...c}=t.server?.config.clientInjectionPlugin||{};return o.tags.push({tag:"div",injectTo:"body-prepend",children:s({templateLess:a,...c})}),o.tags.push({tag:"script",injectTo:"body-prepend",attrs:{src:r.js,type:"module"}}),o},configureServer(e){const n=w(I.resolve(e.config.root,I.dirname(t)));e.config.server?.fs?.allow&&e.config.server.fs.allow.push(n)}}],{outDir:_,distZip:y,versionPlugin:j,imageOptimizer:b,templateLess:E,integrateMiTopBar:P,allowedHosts:T}=d;if(P&&h.push(function(e){return{name:"mi-topbar-plugin",transformIndexHtml(){const t=[];return(!0===e||"object"==typeof e&&!0===e.addRootElement)&&t.push({tag:"div",injectTo:"body-prepend",attrs:{id:"mi-react-root"}}),(!0===e||"object"==typeof e&&!0===e.addSharedComponentsScripts)&&t.push({tag:"script",injectTo:"head-prepend",attrs:{src:"/auth/info.js"}},{tag:"script",injectTo:"head-prepend",attrs:{src:"/js/main.js",defer:"defer"}},{tag:"link",injectTo:"head-prepend",attrs:{href:"/css/main.css",rel:"stylesheet"}}),t}}}(P)),b){const{ViteImageOptimizer:e}=await(import("vite-plugin-image-optimizer"));h.push(e("object"==typeof b?b:void 0))}if(j){const{versionPlugin:e}=await(import("./version-plugin-CA9HNV-6.js"));h.push(e({outDir:_,packageVersion:a.version??"0.0.0",packageRepositoryUrl:ue(a.repository),..."object"==typeof j?j:{}}))}if(y){const{default:e}=await(import("vite-plugin-zip-pack"));h.push({...e("object"==typeof y?y:{outFileName:l(v)}),enforce:"post"})}return{base:E?`${u}/${v}`:`${f}/${v}`,server:{port:3e3,...!0===T||T.length>0?{allowedHosts:T}:{}},build:{minify:!1,assetsInlineLimit:4096,rollupOptions:{output:{banner:F}},outDir:_},css:{modules:{localsConvention:"dashes"}},ppDevConfig:d,plugins:h}}function me(e){return e?.ppDev||{}}function de(e,t){return async(n,s={})=>{try{const{constants:r}=await x(),{PHASE_DEVELOPMENT_SERVER:o,PHASE_PRODUCTION_BUILD:a}=r;n!==a||process.env[m]||d().warn(v.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=process.env[g]||process.cwd(),j=await se(l),w=ne(l).name,b="function"==typeof e?await e(n,s):e,E=function(...e){const t={},n=t;for(const t of e)if(t)for(const[e,s]of Object.entries(t))void 0!==s&&(le.has(e)&&s&&"object"==typeof s&&!Array.isArray(s)?n[e]={...n[e]??{},...s}:n[e]=s);return t}(j,me(b),t);c(E,w);const P=p(E,w),{templateLess:T,v7Features:D}=P,I=n===o,$=function(e,t,n,s){return n?s?t?`${u}/${e}`:`${h}/${e}`:t?`${u}/${e}`:`${f}/${e}`:`${u}/${e}`}(P.templateName,T,I,D),O={basePath:$,trailingSlash:!!I||void 0};if(!T){const e=I&&D?h:f;O.assetPrefix=`${e}/${P.templateName}`}const R=Object.assign({},O,b),S=_(P.allowedHosts);I&&S.length>0&&(R.allowedDevOrigins=[...R.allowedDevOrigins??[],...S]);const N=process.env[y];return n===a&&N&&(R.distDir=N),Object.defineProperty(R,"ppDev",{value:E,enumerable:!1,configurable:!0}),Object.defineProperty(R,"ppDevWrapped",{value:!0,enumerable:!1,configurable:!0}),i={ppDev:E,wrapped:!0},globalThis[k]=i,R}catch(e){throw d().error("Error in withPPDev:",{error:e instanceof Error?e:new Error(String(e))}),e}var i}}export{ae as a,ce as b,B as c,pe as d,Z as e,me as f,fe as g,V as h,C as i,re as j,M as l,A as r,x as s,de as w};
2
+ //# sourceMappingURL=index-PvH-M_Io.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-PvH-M_Io.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","url","isNextAvailable","resolve","getNextVersion","nextPkg","version","previouslyLoadedKeys","Set","loadPPDevEnv","mode","envDir","process","cwd","key","env","fromEnvironment","Object","keys","filter","startsWith","loadEnv","value","entries","has","HANDOFF_KEY","Symbol","for","readWithPPDevHandoff","globalThis","clearWithPPDevHandoff","configCache","Map","packageJsonCache","getPackageJson","projectRoot","now","Date","root","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","findConfig","dirContent","files","endsWithRegExp","readdirSync","withFileTypes","isFile","map","getDirectoryContent","configNames","PP_DEV_CONFIG_NAMES","hasConfigFile","some","includes","hasPackageConfig","prototype","hasOwnProperty","call","newConfig","dirFiles","configName","configPath","loadConfig","found","packageConfig","Array","isArray","clear","parseBooleanFlag","undefined","toLowerCase","resolveBuildCliOverrides","options","distZipEnabled","distZip","PP_DEV_DIST_ZIP","distZipDir","PP_DEV_DIST_ZIP_DIR","distZipFilename","PP_DEV_DIST_ZIP_FILENAME","versionManifestEnabled","versionManifest","PP_DEV_VERSION_MANIFEST","versionFileTemplate","PP_DEV_VERSION_FILE_TEMPLATE","applyDistZipOverride","base","overrides","defaultFileName","outFileName","normalizeRelativeOutputPath","baseConfig","outDir","applyVersionManifestOverride","enabled","normalizedVersionFileTemplate","PP_DEV_CONFIG_GROUPS","resolveRepositoryUrl","repository","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","getViteConfig","environment","ppDevConfig","validatePPDevConfig","normalizedPPDevConfig","normalizePPDevConfig","templateName","createDefaultZipFileName","versionPlugin","vitePPDev","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","getPPDevConfigFromNextConfig","nextConfig","ppDev","withPPDev","nextjsConfig","phase","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_BUILD","PP_DEV_NEXT_BUILD_ENV_VAR","createLogger","warn","colors","yellow","PP_DEV_PROJECT_ROOT_ENV_VAR","nextConfiguration","mergedConfig","configs","merged","mutableMerged","mergePPDevConfigs","normalized","v7Features","isDevelopment","basePath","PATH_TEMPLATE_LOCAL_PREFIX","createBasePath","trailingSlash","prefix","assetPrefix","assign","tunnelOrigins","exactAllowedHosts","allowedDevOrigins","buildDist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eJ,QAAuBtI,GAGxC,IAAK8E,EAAc,CACjB,MAAM6D,EAASL,GAAiBD,EAAaG,EAA6BjC,EAE1EjF,EAAWsH,YAAc,GAAGD,KAAUP,EAAW/E,cACnD,CAKA,MAAMrH,EAAS5D,OAAOyQ,OAAO,CAAA,EAAIvH,EAAYwG,GAMvCgB,EAAgBC,EAAkBX,EAAWzC,cAE/C2C,GAAiBQ,EAAcrC,OAAS,IAC1CzK,EAAOgN,kBAAoB,IAAKhN,EAAOgN,mBAAqB,MAAQF,IAKtE,MAAMG,EAAelR,QAAQG,IAAIgR,GAejC,OAbI7B,IAAUE,GAA0B0B,IACtCjN,EAAOmN,QAAUF,GAGnB7Q,OAAOgR,eAAepN,EAAQ,QAAS,CACrCvD,MAAOsP,EACPsB,YAAY,EACZC,cAAc,IAEhBlR,OAAOgR,eAAepN,EAAQ,eAAgB,CAAEvD,OAAO,EAAM4Q,YAAY,EAAOC,cAAc,IH5a7DC,EG8aV,CAAErC,MAAOa,EAAcyB,SAAS,GH7a1DxQ,WAA6BJ,GAAe2Q,EG+alCvN,CACT,CAAE,MAAOhF,GAKP,MAJeyQ,IAERzQ,MAAM,sBAAuB,CAAEA,MAAOA,aAAiBC,MAAQD,EAAQ,IAAIC,MAAMwS,OAAOzS,MAEzFA,CACR,CHvbE,IAAiCuS,EGybvC"}
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import"child_process";export{A as AuthProvider,t as authProvider,n as normalizePPDevConfig,v as validatePPDevConfig}from"./auth.provider-DDUsu1H1.js";export{f as getNextVersion,h as getPPDevConfigFromNextConfig,g as getViteConfig,j as isNextAvailable,s as safeNextImport,w as withPPDev}from"./index-GSdCxN3K.js";export{defineConfig}from"./helpers.js";import"fs";import"path";import"url";import"picocolors";import"node:path";import"node:net";import"vite";import"node:module";import"ejs";
1
+ import"child_process";export{A as AuthProvider,y as authProvider,n as normalizePPDevConfig,v as validatePPDevConfig}from"./auth.provider-BFK6x9Df.js";export{e as getNextVersion,f as getPPDevConfigFromNextConfig,g as getViteConfig,i as isNextAvailable,s as safeNextImport,w as withPPDev}from"./index-PvH-M_Io.js";export{defineConfig}from"./helpers.js";import"picocolors";import"node:path";import"fs";import"path";import"ejs";import"url";import"node:net";import"vite";import"node:module";
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ import e,{isAxiosError as t}from"axios";import s from"node:http";import n from"node:https";import{g as r,w as i}from"./version-manifest-BVgENnKn.js";import{o as a,a as o,c,g as l,f as d,y as u,k as p,x as h,u as f,z as g,B as m}from"./auth.provider-BFK6x9Df.js";import{URL as y,fileURLToPath as w}from"url";import{createProxyMiddleware as v,responseInterceptor as b}from"http-proxy-middleware";import{StringDecoder as k}from"node:string_decoder";import{inflateSync as $,brotliDecompressSync as x,unzipSync as S,deflateSync as A,brotliCompressSync as T,gzipSync as E}from"zlib";import*as I from"fs";import{promises as j}from"fs";import*as N from"path";import{randomUUID as P,randomBytes as L,createHash as R}from"node:crypto";import*as F from"crypto";import{randomUUID as C}from"crypto";import*as O from"process";import*as B from"os";import M from"jszip";import*as D from"node:fs";import U from"node:fs";import*as H from"node:fs/promises";import*as _ from"child_process";import{createRequire as V}from"module";import z from"node:os";import q from"node:path";import W from"express";const J="/@pp-dev-hmr",K=N.dirname(a),G={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function Z(e,t){const s=t.clientDir??K,n=new Set([`${t.name}.js`,`${t.name}.css`,`${t.name}.js.map`,`${t.name}.css.map`]);e.get(t.path,(e,n)=>{I.readFile(N.join(s,`${t.name}.html`),"utf-8",(e,s)=>{if(e)return void n.status(500).type("text/plain").end(`${t.name} page not built (${e.message})`);const r=t.values?.()??{};n.setHeader("Content-Type","text/html; charset=utf-8"),n.setHeader("Cache-Control","no-cache"),n.end(s.replace(/\{\{(\w+)\}\}/g,(e,t)=>r[t]??e))})}),e.get(`${t.path}/:file`,(e,t,r)=>{const i=e.params.file;n.has(i)?I.readFile(N.join(s,i),(e,s)=>{e?r():(t.setHeader("Content-Type",G[N.extname(i)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(s))}):r()})}function X(e,t,s={}){switch(t){case"gzip":return S(e,s);case"br":return x(e,s);case"deflate":return $(e,s);default:return e}}const Y="/@pp-dev/inspector",Q=new WeakMap;function ee(e){const t=Array.isArray(e)?e[0]:e;return"string"==typeof t?t:void 0}function te(e,t,s=10485760,n=K){const r=Q.get(e);if(r)return r.store=t,void(r.captureLimit=s);const i={store:t,captureLimit:s};Q.set(e,i),e.get("/@api/requests",(e,t)=>{const{store:s}=i,n=ee(e.query.limit),r=ee(e.query.offset),a=ee(e.query.method),o=ee(e.query.search),c=void 0!==n?parseInt(n,10):void 0,l=s.list({limit:Number.isFinite(c)?c:500,offset:void 0!==r&&Number.isFinite(parseInt(r,10))?parseInt(r,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:ne(s.memoryUsage),maxMemoryFormatted:ne(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 n=se(s.requestHeaders["content-type"]),r=se(s.responseHeaders["content-type"]),a=s.responseBody?function(e,t,s){const n=Array.isArray(t)?t.join(", "):String(t??"");try{return X(e,n.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:n,responseHeaders:s.responseHeaders,responseBody:a?a.toString("base64"):null,responseBodySize:s.responseBody?.byteLength??0,responseBodyTruncated:s.responseBodyTruncated||null!==s.responseBody&&null===a,responseContentType:r})}),e.delete("/@api/requests",(e,t)=>{i.store.clear(),t.json({ok:!0})}),Z(e,{path:Y,name:"request-inspector",clientDir:n,values:()=>({captureLimit:String(i.captureLimit)})})}function se(e){return Array.isArray(e)?e[0]??"":String(e??"")}function ne(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 re{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 ie extends re{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 n=new FormData;return n.append("file",new File([new Uint8Array(t)],"file.zip",{type:"application/zip"}),"file.zip"),this.axios.post(e,n,{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 ae extends ie{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 oe="Something went wrong when fetching page data",ce="Something went wrong when fetching page template data",le="Something went wrong when fetching page variables",de="Something went wrong when checking who the credentials belong to",ue=" The instance may be down or in maintenance mode. Please try again later.",pe=[oe,ce,le,de];function he(){return new Error(`${oe}.${ue}`)}function fe(){return new Error(`${ce}.${ue}`)}function ge(e){return e instanceof Error&&pe.some(t=>e.message.includes(t))}class me extends re{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 he();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 he();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 he();return s.page}}class ye extends re{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 fe();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 fe();return s.page_template}}class we extends re{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(`${le}.${ue}`);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 ve(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 be(e,t){const[s,...n]=e.split(";"),r=n.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(),...r].join("; ")}const ke="metric_insights_session";function $e(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 xe(e,t){return e?$e(e.split(";"),t):void 0}function Se(e,t){if(void 0===e||"number"==typeof e)return;return $e((Array.isArray(e)?e:[e]).map(e=>e.split(";",1)[0]),t)}function Ae(e,t){return void 0===e?e:Array.isArray(e)?e.map(e=>be(e,t)):be(e,t)}const Te=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,n,r){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",n.placeholder=i.placeholder,r.replaceChildren(`You can get the ${i.label} `,a)}function n(e,t){t.textContent=e,t.classList.add("show")}function r(e){e.classList.remove("show")}function i(e,t,s,i){s.addEventListener("click",async s=>{if(s.preventDefault(),r(i),!t.value.trim())return n(`${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,r){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();n(`Login failed: ${e?.error||"Unknown error occurred"}`,r)}catch(e){n("Login failed: Unable to parse response",r)}else window.location.href=i.url}catch(e){n("Login failed: Network error. Please check your connection.",r)}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",()=>{r(i)})}function a(e){const t=e.firstChild;if(!t)return;const n=t.lastChild?.cloneNode(!0);if(!n)return;n.innerHTML="";const r=n.cloneNode(!0);r.innerText="OR",r.setAttribute("role","separator"),r.setAttribute("aria-label","Alternative login method");const a=n.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(r),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"),f=o.querySelector(".helper-login-wrapper");l&&d&&u&&p&&h&&f?(!function(e,t,n){const r=e.querySelectorAll(".token-type-option"),i=e=>{const i=e.dataset.value;r.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,n)};r.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(f,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 Ee(e){const{message:t,response:s}="object"==typeof e&&null!==e?e:{},n="number"==typeof s?.status?s.status:0,r=s?.data?.message;return"string"==typeof r&&r?{status:n,message:r}:"string"==typeof t&&t?{status:n,message:t}:{status:n,message:"string"==typeof e&&e?e:"Unknown error"}}function Ie(e){const{status:t,message:s}=Ee(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 je(e){const{status:t}=Ee(e);return 401===t||403===t||412===t}const Ne=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Pe=new Map,Le=new Map;const Re=(e,t,s)=>{let n=Pe.get(e);if(!n){const t=/:\d+$/.test(e)?"":"(?::(?<port>\\d+))?";n=new RegExp(`(?<keep>!!)?(?<url>http(?<secure>s)?(?<slashes>:(?:\\\\)?/(?:\\\\)?/)${Ne(e)}${t})`,"gi"),Pe.set(e,n)}return s.replace(n,(...e)=>{const{keep:s,url:n,secure:r,slashes:i,port:a}=e.at(-1);return s||a&&a!==(r?"443":"80")?n:`http${i}${t}`})},Fe=(e,t,s)=>{const n=new RegExp(`${e.replace(/\\*\//gi,"\\\\/")}`,"gi"),r=new RegExp(`${e}`,"gi"),i=s.replace(n,t);return i===s?i.replace(r,t):i},Ce=(e,t,s)=>{e.setHeader("location",t),e.statusCode=s,e.end()};function Oe(e){return e.split("?")[0]}const Be="[DEV PAGE. DO NOT DELETE]",Me=new Map;class De{#e;#t;#s=null;#n;#r;#i=!1;#a=null;#o=null;#c;#l;#d;#u;#p;internalPageName;appId;templateLess;assetsApi;pageApi;pageTemplateApi;pageVariableApi;logger;constructor(t,r){const{headers:i={},appId:a,templateLess:o=!0,disableSSLValidation:l=!1,v7Features:d=!1,personalAccessToken:u}=r||{};this.#e=i,this.#r=[],this.#n="",this.#c=d,this.#l=u,this.#d=!1,this.#u=Promise.resolve(!1);const p=`${t}:${l}`;if(Me.has(p))this.#t=Me.get(p);else{const r=new n.Agent({keepAlive:!1,...l?{rejectUnauthorized:!1}:{}});this.#t=e.create({baseURL:t,headers:i,timeout:3e4,maxRedirects:5,httpAgent:new s.Agent({keepAlive:!1}),httpsAgent:r}),Me.set(p,this.#t)}this.appId=a,this.templateLess=o,this.assetsApi=new(d?ae:ie)(this.#t),this.pageApi=new me(this.#t),this.pageTemplateApi=new ye(this.#t),this.pageVariableApi=new we(this.#t),this.logger=c()}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}#f(){return this.#h(this.#e)}#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(o.green("Page fetched")),e)).catch(async t=>{if(this.#p(!1),ge(t))throw t;throw await this.pageApi.checkAuth(this.#h(e))?(this.logger.error(o.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(o.green("Local page template fetched")),this.#p(!0),this.#s}let t=(await this.pageApi.getAll(this.#h(e)).then(e=>(this.logger.info(o.green("Page list fetched")),e)).catch(async t=>{throw this.#p(!1),await this.pageApi.checkAuth(this.#h(e))?(this.logger.error(o.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===Be);return t||(this.logger.warn(o.yellow("Creating dev page template...")),t=await this.pageApi.create({enabled:"Y",name:Be,internal_name:"dev-page-template",visible_in_homepage:"Y"},this.#h(e)).then(e=>(this.logger.info(o.green("Dev page created")),e)).catch(e=>{throw this.logger.error(o.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 "${Be}" 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(o.green("Page template fetched")),e)).catch(e=>{throw this.#p(!1),this.logger.error(o.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:n}=e;if(n&&t){const e=JSON.parse(t);return this.#r=e,this.#i=!0,this.#n=s,e}return this.#r=[],this.#i=!0,this.#n=s,[]}).catch(t=>{if(this.logger.error(o.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(o.cyan(`[page-variables] Fetching live variables for page ID ${t} (page_id lookup)`));const n=await this.pageVariableApi.getById(t,this.#h(e));return this.logger.info(o.green(`[page-variables] Fetched ${n.length} live variable(s) for page ID ${t} in ${Date.now()-s}ms`)),n}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,n=Date.now();this.logger.info(o.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(o.green(`[page-variables] Applied variables to page ID ${s} in ${Date.now()-n}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.#r.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),n=this.appId;try{return this.#c?await this.#m(n,s):await this.#y(n,s)}catch(e){this.#w(e,n)}}async#m(e,t){const s=await this.pageApi.get(e,t);return this.logger.info(o.green("Page fetched")),void 0!==s.template_id&&(this.#d=!0),this.internalPageName=s.internal_name,s}async#y(e,t){return await this.pageApi.get(e,t)}#w(e,t){if(ge(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(o.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.#v())s=s.replace(e,()=>t);if(t){return new(r())(s).serialize()}const{before:n,after:i}=this.#b();return n+s+i}#v(){return this.#a?.vars!==this.#r&&(this.#a={vars:this.#r,replacements:this.#r.map(({name:e,value:t})=>({regExp:new RegExp(`\\[${this.#g(e)}\\]`,"g"),value:t}))}),this.#a.replacements}#b(){const e=this.#s,t=this.#n;if(this.#o?.template===e&&this.#o.title===t)return this.#o;const s=new(r())(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){const e=this.#f();if(this.templateLess)return await this.assetsApi.downloadPageAssets(this.appId,e);{const t=await this.pageApi.get(this.appId,e);if(this.#d){const s=await this.pageTemplateApi.get(t.template_id,e);return await this.assetsApi.downloadTemplateAssets(s.id,e)}if(t.template)return await this.assetsApi.downloadTemplateAssets(t.template,e)}}}async updateAssets(e){if(this.appId){const t=this.#f();if(this.templateLess)return await this.assetsApi.uploadPageAssets(this.appId,e,t);{const s=await this.pageApi.get(this.appId,t);if(this.#d){const n=await this.pageTemplateApi.get(s.template_id,t);return await this.assetsApi.uploadTemplateAssets(n.id,e,t)}if(s.template)return await this.assetsApi.uploadTemplateAssets(s.template,e,t)}}}async validateCredentials(e){try{const t=e?this.#h(e):this.#f();return await this.get("/api/user",t,!0),{isValid:!0}}catch(e){const t=Ie(e);return{isValid:!1,error:t.userFriendlyMessage,code:t.code}}}async get(e,t,s=!1,n={}){const r=s?t:Object.assign({},this.#h(this.#e),t);try{return await this.#t.get(e,{headers:r})}catch(e){if("UNKNOWN_ERROR"!==Ie(e).code){const t=Ie(e);throw n.quiet||(this.logger.error(o.red(`API request failed: ${t.userFriendlyMessage}`)),function(e,t,s){const n=Ie(t),r=`[${s}] `;e.error(o.red(`${r}${n.userFriendlyMessage}`)),e.error(o.red(`Status: ${n.status} (${n.code})`)),e.error(o.red(`Details: ${n.message}`)),n.suggestions.length>0&&(e.info(o.yellow("Suggestions:")),n.suggestions.forEach((t,s)=>{e.info(o.yellow(` ${s+1}. ${t}`))}))}(this.logger,e,"API Request")),e.tokenErrorInfo=t,e}throw e}}}function Ue(e,t){const s=(e=(e=e.startsWith("/")?e:`/${e}`).endsWith("/")?e:`${e}/`).endsWith("/")?e.slice(0,-1):e,n=c();return(r,i,a)=>{const c=new y(r.url??"","http://localhost"),{pathname:u,search:p}=c,h=["/",s];if(t&&(h.push(`${l}/${t}`),h.push(`${d}/${t}`)),h.includes(u)){const t=`${e}${p}`;return n.info(o.yellow(`Redirecting to: ${t}`)),Ce(i,t,302)}a()}}const He=String.raw`[a-z](?:[a-z0-9\-]*[a-z0-9])?`,_e=new RegExp(`^(?:${He})$`),Ve=".localhost";function ze(e){return e?e.length>32?"The name must be at most 32 characters long":_e.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 qe(e){if(!e)return;const t=e.toLowerCase().replace(/:\d+$/,"");if(!t.endsWith(Ve))return;const s=t.slice(0,-10);return s&&!s.includes(".")?s:void 0}function We(e,t){const s=/:(\d+)$/.exec(e.headers.host??"")?.[1];return`${ve(e)?"https":"http"}://${t?`${t}.`:""}localhost${s?`:${s}`:""}`}const Je=new class{#k=new Map;#$=new Set;#x=new Set;#S=!1;#A=new Set;#T;#E=new Map;#I=new WeakMap;#j;useContext(e){void 0!==this.#j&&this.#j!==e&&this.clear(),this.#j=e}get context(){return this.#j}list(){return[...this.#k.values()]}get(e){return this.#k.get(e)}add(e){const t=ze(e.name);if(t)throw new Error(t);if(this.#k.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.#k.set(s.name,s),this.#N(),s}replace(e,t){if(!this.#k.has(e))throw new Error(`There is no user named "${e}"`);const s=ze(t.name);if(s)throw new Error(s);if(t.name!==e&&this.#k.has(t.name))throw new Error(`A user named "${t.name}" already exists`);const n=this.#T===e,r=[...this.#E].filter(([,t])=>t===e).map(([e])=>e);let i;this.#S=!0;try{this.remove(e),i=this.add(t)}catch(s){throw this.#S=!1,this.#N(),s}finally{this.#S=!1}for(const s of t.name===e?r:[...r,e])this.#E.set(s,i.name);return n&&(this.#T=i.name),this.#N(),i}#N(){this.#S||this.#x.forEach(e=>e())}renamedTo(e){return this.#E.get(e)}remove(e){const t=this.#k.get(e);if(!t)return!1;this.#T===e&&(this.#T=void 0);for(const[t,s]of this.#E)s===e&&this.#E.delete(t);return this.#k.delete(e),this.#$.forEach(e=>e(t)),this.#N(),!0}clear(){for(const e of[...this.#k.keys()])this.remove(e)}onRemove(e){return this.#$.add(e),()=>{this.#$.delete(e)}}onSessionChange(e){return this.#A.add(e),()=>{this.#A.delete(e)}}sessionChanged(e){this.#k.get(e.name)===e&&this.#A.forEach(t=>t(e))}onChange(e){return this.#x.add(e),()=>{this.#x.delete(e)}}get defaultUser(){return void 0===this.#T?void 0:this.#k.get(this.#T)}setDefaultUser(e){if(void 0===e)return void(this.#T=void 0);const t=this.#k.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.#T=e}resolve(e){if(this.#I.has(e))return this.#I.get(e);const t=qe(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.#k.get(t)??this.#k.get(this.#E.get(t)??"");s=e?{key:e.name,user:e}:void 0}return this.#I.set(e,s),s}};function Ke(e=Je){return(t,s,n)=>{const r=e.resolve(t),i=qe(t.headers.host)??"";if(r?.user&&i&&r.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",`${We(t,r.key)}${e}`),s.setHeader("Cache-Control","no-store"),void s.end()}r?n():(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 Ge=/(?:^|\/\/[^/]+)\/(?:login|auth\/saml\/login)(?:[/?#]|$)/i;function Ze(e){return(e??"").split(";").map(e=>e.trim()).filter(e=>e&&e.split("=",1)[0].trim()!==ke)}function Xe({statusCode:e=200,headers:t}){return 401===e||412===e||e>=300&&e<400&&Ge.test(String(t.location??""))}class Ye{#k;#P;#L=c();#R=new WeakMap;#F=new WeakMap;#C=new WeakMap;#O=new WeakMap;constructor(e,t){this.#k=e,this.#P=t}isLeftBehindRequest(e,t,s){const n=qe(t.headers.host)===e.name?xe(t.headers.cookie,ke):s;return void 0!==n&&this.#B(e,n)}observe(e,t,s,n){if("session"!==e.kind||this.#k.get(e.name)!==e)return;const r=qe(t.headers.host)===e.name,i=r?xe(t.headers.cookie,ke):n,a=Se(s.headers["set-cookie"],ke),o=this.#C.get(e);let c,l,d=r;return a&&a!==i?(c=a,l=i):r&&i!==e.session&&!Xe(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&&Xe(s)&&i===e.session&&this.#M(e,`MI turned away ${t.method} ${t.url}`),c&&c!==e.session&&c!==this.#R.get(e)&&c!==this.#F.get(e)&&!this.#B(e,c)?this.#D(e,c,l,d):void 0}async#D(e,t,s,n){let r;this.#R.set(e,t);try{r=await this.#P(t)}catch(r){return this.#R.get(e)===t&&(this.#R.delete(e),this.#C.set(e,{session:t,replaced:s,ownHost:n,retryAt:Date.now()+5e3})),void this.#L.warn(o.yellow(`Could not check the MI session of user ${e.name}: ${String(r)}`))}if(this.#R.get(e)===t&&this.#k.get(e.name)===e)if(this.#R.delete(e),this.#C.get(e)?.session===t&&this.#C.delete(e),r){if(this.#B(e,t)||void 0!==s&&this.#B(e,s))return;const i="active"===e.state;n&&(this.#U(e),void 0!==s&&s!==t&&this.#U(e,s)),this.#C.delete(e),Object.assign(e,{state:"active",session:t,miUser:r}),this.#F.delete(e),this.#k.sessionChanged(e),i||this.#L.info(`${o.blue("User")} ${o.yellow(e.name)} ${o.blue("logged in")} (MI user ${r.id}${r.username?`, ${r.username}`:""})`)}else this.#F.set(e,t),"active"===e.state&&s===e.session&&this.#M(e,"MI started a guest session")}#B(e,t){return"active"===e.state&&Boolean(this.#O.get(e)?.has(t))}#U(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)}#M(e,t){this.#U(e),e.state="expired",e.session=void 0,this.#R.delete(e),this.#C.delete(e),this.#k.sessionChanged(e),this.#k.defaultUser===e&&this.#k.setDefaultUser(void 0),this.#L.warn(`${o.yellow(`The MI session of user ${e.name} ended`)} (${t}). Log in again on its host.`)}}async function Qe(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(`${de}.${ue}`);const n=s.user;return"number"==typeof n?.user_id?{miUser:{id:n.user_id,username:"string"==typeof n.username?n.username:""}}:{miUser:void 0}}catch(e){if(je(e))return{miUser:void 0,refused:Ie(e).userFriendlyMessage};throw e}}async function et(e,t){try{const s=await Qe(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: ${Ie(e).userFriendlyMessage}`}}}const tt=/^(https?:\/\/)([^/]+)(\/.*)?$/i,st="X-PP-Proxy";const nt=/^\/login(?:\/|$)/i,rt="/auth/saml/login";const it=/^\/auth\/(?:index\/)?logout(?:[/?#]|$)/i;const at=new WeakMap,ot=new WeakMap;const ct=[/^text\//,/^application\/(?:[\w.-]+\+)?(?:json|xml)$/,/^application\/(?:x-)?(?:java|ecma)script$/,/^[\w.-]+\/[\w.-]+\+(?:json|xml)$/];function lt(e){const t=e.split(";",1)[0].trim().toLowerCase();return ct.some(e=>e.test(t))}const dt=/[\w.:/\\!-]/;function ut(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&&lt(s)}function pt(e){return async(t,s,n)=>{const r=e&&ut(t.headers);n.statusCode=t.statusCode??n.statusCode,t.statusMessage&&(n.statusMessage=t.statusMessage),n.setHeader(st,1);for(const[e,s]of Object.entries(t.headers))void 0!==s&&(r&&"content-length"===e.toLowerCase()||n.setHeader(e,s));if(!r)return void t.pipe(n);const i=new k("utf8");let a="",o=!1;const c=s=>{if(!s)return;n.write(e(Buffer.from(s,"utf8"),"utf8"))||o||(o=!0,t.pause(),n.once("drain",()=>{o=!1,t.resume()}))};t.on("data",e=>{a+=i.write(e);const t=a.lastIndexOf("\n");if(-1!==t&&(c(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(!dt.test(e[t]))return t;return-1}(a)+1||a.length;c(a.slice(0,e)),a=a.slice(e)}}),t.on("end",()=>{c(a+i.end()),a="",n.end()}),t.on("error",()=>{n.end()})}}function ht(e){const{rewritePath:t=/^\/(?!p[tl]).*/i,baseURL:s="",disableSSLValidation:n=!1,miAPI:r,templateName:i,users:a=Je}=e;if(!s)throw new Error("Base url is required");const l=function(e){try{return new URL(e).host}catch{return e.replace(tt,"$2")}}(s),d=s.replace(tt,"$1$2"),u=import("file-type"),p=c(),h=e.sessionUsers??new Ye(a,function(e){return async t=>(await Qe(e,{Cookie:`${ke}=${t}`})).miUser}(r));return v({selfHandleResponse:!0,pathFilter:(s,n)=>!(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:!n,headers:{host:l,origin:d},on:{proxyReq(e,t,n){const c=t.headers.host,l=e.getHeader("referer");c&&l&&"string"==typeof l&&e.setHeader("referer",l.replace(function(e){let t=Le.get(e);return t||(t=new RegExp(`^https?://${Ne(e)}(?=[/?#]|$)`,"i"),Le.set(e,t)),t}(c),s));const d=a.resolve(t);let u;d?.user?u=d.user.token:d&&(u=r.personalAccessToken),u?(e.setHeader("Authorization",`Bearer ${u}`),at.set(t,u)):"session"===d?.user?.kind&&e.removeHeader("Authorization"),d?.user&&e.removeHeader("Token");const h="session"===d?.user?.kind?d.user:void 0;let f;if(h&&qe(t.headers.host)!==h.name){f=h.session;const s=f?(g=t.headers.cookie,m=f,[...Ze(g),`${ke}=${m}`].join("; ")):function(e){const t=Ze(e);return t.length?t.join("; "):void 0}(t.headers.cookie);s?e.setHeader("cookie",s):e.removeHeader("cookie")}var g,m;ot.set(t,{user:d?.user,sentSession:f}),e.removeHeader("if-none-match"),e.removeHeader("if-modified-since");const w=t.url??"/",v=function(e,t,s,n){if(!t||!s||!n||s===n)return e;try{const t=new y(e,"http://localhost"),r=t.pathname.match(/^\/data\/page\/([^/]+)(\/.*)?$/);if(!r)return e;let i;try{i=decodeURIComponent(r[1])}catch{i=r[1]}if(i!==s)return e;return`/data/page/${n}${r[2]??""}`+t.search+t.hash}catch{return e}}(w,r.v7Features,i,r.internalPageName);v!==w&&(t.url=v,e.path=v,console.info(`${o.cyan("Rewrites data page to correct internal page name")}: ${o.yellow(w)} ${o.blue("→")} ${o.green(v)}`)),p.info(`${o.blue("Proxies request:")} ${o.green(t.method)} ${t.url} -> ${o.green(e.method)} ${e.protocol}//${e.host}${e.path}${d?.user?` ${o.blue("as")} ${o.yellow(d.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(st,1),e.headers["set-cookie"]&&(e.headers["set-cookie"]=Ae(e.headers["set-cookie"],ve(t))),e.headers.location&&(e.headers.location=function(e,t,s){const n=s.headers.host;let r;try{r=new URL(e)}catch{return e}return n&&/^https?:$/.test(r.protocol)&&r.host===t.toLowerCase()?e.replace(/^https?:\/\/[^/?#]*/i,`${ve(s)?"https":"http"}://${n}`):e}(e.headers.location,l,t));const n=function(e,t){if(!it.test(e.url??""))return;const s=qe(e.headers.host);return void 0===s?void 0:t.get(s)}(t,a),r=ot.get(t);if(n){e.resume();const i={"cache-control":"no-store"};r?.user===n&&(a.remove(n.name),p.info(`${o.blue("Logged out user")} ${o.yellow(n.name)}, back to the main host`),e.headers["set-cookie"]&&(i["set-cookie"]=e.headers["set-cookie"]));const c=t.headers["sec-fetch-mode"];return c&&"navigate"!==c?s.writeHead(204,i):s.writeHead(302,{...i,location:`${We(t)}/`}),void s.end()}const i=r?.user;let c=!0;if(i&&a.get(i.name)!==i)c=!1;else if(i){let s=!1;"session"===i.kind&&(s=h.isLeftBehindRequest(i,t,r?.sentSession),h.observe(i,t,e,r?.sentSession)),c=qe(t.headers.host)===i.name&&!s}if(!c){const t=function(e){const t=(e??[]).filter(e=>void 0===Se(e,ke));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 d=(e,s)=>Buffer.from(Fe(rt,"/login",Re(l,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 p.info(`${o.blue("Start streaming for request:")} ${o.green(t.method)} ${t.url}`),pt(d)(e,t,s);const f=function(e){const t=e["content-type"];if("string"==typeof t&&t.trim()&&!lt(t))return"pipe";const s=Number(e["content-length"]);return Number.isFinite(s)&&s>=10485760&&ut(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 pt("stream"===f?d:void 0)(e,t,s);const g=b(async(e,t,s,n)=>{n.setHeader(st,1);if(await(await u).fileTypeFromBuffer(e))return e;{let t=e.toString("utf8");try{const e=new URL(s.url??"",`http://${l}`);if(e.searchParams&&e.searchParams.has("proxyRedirect")){t+=`<script>(${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 n=window.location.href;const r=function(){const i=new URLSearchParams(window.location.search);if(!i.has("proxyRedirect"))return console.debug("No proxyRedirect param. Cleaning up."),void localStorage.removeItem(e);n!==window.location.href?(n=window.location.href,setTimeout(r,s<3?3e3:5e3)):window.location.href=i.get("proxyRedirect"),localStorage.setItem(e,""+ ++s),localStorage.setItem(t,(new Date).toISOString())};setTimeout(r,3e3)}.toString()})()<\/script>`}const n=t.slice(0,100);nt.test(e.pathname)&&(n.includes("<html")||n.includes("<body")||n.includes("<head")||n.includes("html>"))&&!qe(s.headers.host)&&(t+=`<script>(${Te.toString()})(${r=l,JSON.stringify(r).replace(/</g,"\\u003c")})<\/script>`)}catch{}const n=s.headers.host??"";return Fe(rt,"/login",Re(l,n,t))}var r});return g(e,t,s)},error(e,t,s){!function(e,t,s,n){const r=`Proxy error: "${e.message}" when trying to "${t.method} ${t.url}"`;if(n(`${r}\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(r)))}(e,t,s,e=>p.error(e))}}})}const ft=/\.(?:[a-z0-9]+)$/i,gt=6e5,mt=104857600,yt=1e3,wt=10485760;const vt=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=gt){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)}}(mt,yt),bt=new Set,kt=new Map;function $t(e){vt.clear(),kt.clear(),bt.forEach(e=>e()),c().info(o.blue(`Proxy cache cleared: ${e}`))}const xt=new WeakSet;function St(e,t){return t?e.startsWith(`@${t}@`):!e.startsWith("@")}function At(e,t){if(e){for(const t of vt.keys())St(t,e)&&vt.del(t);kt.delete(e),c().info(o.blue(`Proxy cache cleared for ${e}: ${t}`))}else $t(t)}function Tt(e,t,s){const n=function(e){return at.get(e)}(e);if(void 0!==n){const e=kt.get(s),t=void 0!==e&&n!==e;return kt.set(s,n),t?"personal access token changed":void 0}const r=Se(t.getHeader("set-cookie"),ke);return void 0!==r&&r!==xe(e.headers.cookie,ke)?"MI session changed":void 0}function Et(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 It(e){const{devServer:t,ttl:s=gt,maxSize:n=mt,maxItems:r=yt,users:i=Je}=e,a=c();return n===mt&&r===yt||(vt.maxSize=n,vt.maxItems=r),t&&(t.cache=vt),xt.has(i)||(xt.add(i),i.onRemove(e=>At(e.name,"user removed")),i.onSessionChange(e=>At(e.name,"MI session changed or ended"))),(e,t,n)=>{const r=i.resolve(e);if(!r)return n();t.once("finish",()=>{const s=t.hasHeader(st)?Tt(e,t,r.key):void 0;s&&At(r.key,`${s} (${e.method} ${Oe(e.url??"")})`)});const l=r.user?.session,d=e.originalUrl||e.url||"",u="GET"===e.method?function(e,t,s){const n=e.split("?")[0];return ft.test(n)?n.includes("/auth/info.js")?"":t?`@${t}@${s}:${e}`:`${s}:${e}`:""}(d,r.key,e.headers.host??""):"";if(!u||!function(e,t){const{user:s}=t;return"session"!==s?.kind||!!s.session&&(qe(e.headers.host)!==s.name||xe(e.headers.cookie,ke)===s.session)}(e,r))return n();const p=vt.get(u);if(p)return a.info(`${o.blue("Proxies request:")} ${o.green(e.method)} ${d} -> ${o.blue("Cache")} ${u}`),function(e,t){try{for(const[s,n]of Object.entries(t))null!=n&&e.setHeader(s,n)}catch(e){c().warn(`Failed to set some response headers: ${e instanceof Error?e.message:String(e)}`)}}(t,p.headers),t.setHeader("X-PP-Cache","hit"),t.write(p.content),void t.end();const h=t.end,f=t.write,g=[];let m=0,y="undecided";const w=(e,t)=>null==e?null:"string"==typeof e?Buffer.from(e,t||"utf8"):e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf8"),v=()=>{y="pass";for(const e of g.splice(0))f.call(t,e)},b=()=>{"undecided"===y&&(t.hasHeader(st)?!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>=wt)}(t)?v():y="buffer":y="pass")};t.write=function(e,t,s){if(b(),"pass"===y)return f.call(this,e,t,s);const n="function"==typeof t?t:s,r=w(e,"string"==typeof t?t:void 0);return r&&(g.push(r),m+=r.length),m>wt&&v(),n&&process.nextTick(n),!0},t.end=function(e,n,c){if(b(),"pass"===y)return h.call(this,e,n,c);"function"==typeof e?(c=e,e=void 0):"function"==typeof n&&(c=n,n=void 0);const d=w(e,"string"==typeof n?n:void 0);let p;d&&g.push(d);try{p=Et(g);const e=Buffer.byteLength(p);if(200===t.statusCode&&e>0&&e<wt&&function(e,t,s){return!e.user||s.get(e.key)===e.user&&e.user.session===t}(r,l,i)){const{"set-cookie":n,...r}=t.getHeaders(),i={headers:r,content:p,timestamp:Date.now(),size:e};vt.put(u,i,s),a.info(`${o.blue("[Cached]")} ${u} (${(e/1024).toFixed(1)}KB)`)}}catch(e){a.error(`Failed to cache response for ${u}: ${e}`),p=Et(g)}return h.call(this,p,c)},n()}}const jt=new WeakMap;let Nt=0;function Pt(e){let t=jt.get(e);return t||(t=new Map,jt.set(e,t)),t}function Lt(e,t){const s=Pt(e),n=s.get(t);return n?n.epoch!==Nt||Date.now()-n.timestamp>18e4?(s.delete(t),null):n.data:null}function Rt(e,t,s){Pt(e).set(t,{timestamp:Date.now(),epoch:Nt,data:s})}var Ft;Ft=()=>{Nt+=1},bt.add(Ft);let Ct=!1;function Ot(e){Ct||(Ct=!0,e.info(o.blue("Clearing proxy cache after successful login")),vt.clear())}function Bt(){Ct=!1,u.reset()}const Mt="/home?proxyRedirect=",Dt=`${Mt}${encodeURIComponent("/")}`;function Ut(e){const t=e.headers??{},s=Boolean(qe(e.headers?.host));if(!s&&!Je.resolve(e)?.user)return t;const{cookie:n,authorization:r,token:i,...a}=t;return s||void 0===n?a:{...a,cookie:n}}function Ht(e,t,s){const{templateLess:n=!1,miHudLess:r=!1,appId:i,base:a,appBase:l}=s,d=c();if(n&&r&&void 0===i)throw new Error("Custom App ID is required when both templateLess and miHudLess are true");return async(s,c,p)=>{try{const h=!(n&&r),f=Oe(s.url??""),g=e.test(f),m=!g&&!f.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)}(f,l)&&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=u.getState();if(!y.isAuthenticated&&!y.isRedirected&&s.url?.startsWith("/home")&&!s.url?.startsWith(Mt)){let e;d.info(o.blue("Trying to authenticate and redirect to base"));const l=t=>{e=t};try{if(h?await Vt(t,{templateLess:n,miHudLess:r,appId:i,redirectUrl:Dt},s,c,l,d):await _t(t,{templateLess:n,miHudLess:r,appId:i,redirectUrl:Dt},s,c,l,d),c.headersSent||c.writableEnded)return;return e?p(e):(u.setRedirected(!0),d.info(o.blue("Successfully authenticated. Redirecting to base")),Ce(c,a??"/",302))}catch(e){if(c.headersSent||c.writableEnded)return;return p()}}if(!g&&!m)return p();if(!h){return await _t(t,{templateLess:n,miHudLess:r,appId:i,redirectUrl:Dt},s,c,p,d)}return await Vt(t,{templateLess:n,miHudLess:r,appId:i,redirectUrl:Dt},s,c,p,d)}catch(e){return d.error(o.red(`Unexpected error in load-pp-data middleware: ${e instanceof Error?e.message:String(e)}`)),Bt(),p(e)}}}async function _t(e,t,s,n,r,i){const{appId:a,redirectOnAuthFailure:c,redirectUrl:l}=t;if(void 0===a){const e=new Error("Custom App ID is required for page info only mode");return i.error(o.red(e.message)),r(e)}const d=Ut(s);i.info(o.green("Start loading page info"));try{const t=`pageInfo:${a}`;return Lt(e,t)?(i.info(o.green("Page info loaded from cache")),r()):(await e.getPageInfo(a,d),Ot(i),Rt(e,t,{success:!0}),u.updateState({isAuthenticated:!0}),i.info(o.green("Page info loaded successfully")),r())}catch(e){return Bt(),zt(e,c??!0,l||Dt,n,r,i,"Page info")}}async function Vt(e,t,s,n,r,i){const{templateLess:a,appId:c,redirectOnAuthFailure:l,redirectUrl:d}=t,u=Ut(s);i.info(o.green("Start loading page data"));try{const t=`pageData:${a}:${c}`;if(Lt(e,t))return i.info(o.green("Page data loaded from cache")),r();const s=a||void 0===c?e.getPageTemplate(u):e.getPageVariables(c,u);return await s,Ot(i),Rt(e,t,{success:!0}),i.info(o.green("Page data loaded successfully")),r()}catch(e){return Bt(),zt(e,l??!0,d||Dt,n,r,i,"Page data")}}function zt(e,t,s,n,r,i,a){if(function(e){return null!==e&&"object"==typeof e&&je(e)}(e)&&(i.info(o.red(`${a} loading failed. Not authorized`)),t)){const e=`${s}`;return i.info(o.yellow(`Redirecting to: ${e}`)),Ce(n,e,302)}const c=e instanceof Error?e.message:String(e);return i.info(o.red(`${a} loading failed. Error: ${c}`)),r(e)}function qt(e){return"string"==typeof e?e:void 0}function Wt(e,t){return"string"==typeof e?Buffer.from(e,t):e instanceof Uint8Array?Buffer.from(e):null}function Jt(e,t,s={}){return async(n,r,i)=>{if(await e(n.url??"",n,r)){const e=c();"GET"!==n.method&&"HEAD"!==n.method||!(n.headers.accept??"").includes("text/html")||delete n.headers["if-none-match"];const a=r.end;if("HEAD"===n.method)return r.end=function(e,t,n){const i=[e,t,n].find(e=>"function"==typeof e),o=r.getHeader("content-type"),c=!s.contentType||s.contentType(void 0===o?"":String(o));return!r.headersSent&&c&&r.removeHeader("content-length"),a.call(this,i),this},void i();e.info(`Rewrite response for ${n.url}`);const o=[],l=r.write,d=r.writeHead,u=r.flushHeaders;let p=null,h=!1;const f=()=>{h=!0,p&&!r.headersSent&&d.apply(r,p),p=null;for(const e of o.splice(0))l.call(r,e)},g=(e=!1)=>{if(h)return!0;if(!s.contentType)return!1;const t=r.getHeader("content-type");return!(void 0===t&&!e)&&(!s.contentType(void 0===t?"":String(t))&&(f(),!0))};r.flushHeaders=function(){g()&&u.call(this)},r.writeHead=function(e,...t){if(h)return d.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 n=String(t[e]),r=s.get(n.toLowerCase())??{name:n,values:[]};r.values.push(String(t[e+1])),s.set(n.toLowerCase(),r)}for(const{name:t,values:n}of s.values())e.setHeader(t,1===n.length?n[0]:n);return}if(t&&"object"==typeof t)for(const[s,n]of Object.entries(t))void 0!==n&&e.setHeader(s,n)}(this,void 0===s?t[0]:t[1]),this.statusCode=e,p=void 0===s?[e]:[e,s],g(),this},r.write=function(e,t,s){if(g())return l.call(this,e,t,s);const n=Wt(e,qt(t));n&&o.push(n);const r="function"==typeof t?t:s;return"function"==typeof r&&process.nextTick(r),!0},r.end=function(s,i,c){if(g(!0))return a.call(this,s,i,c);"function"==typeof s&&(c=s,s=void 0);const l=Wt(s,qt(i));l&&o.push(l);const u="function"==typeof i?i:c,h=r.getHeader("content-encoding"),f=X(Buffer.concat(o),h),m=function(e,t){switch(t){case"gzip":return E(e);case"br":return T(e);case"deflate":return A(e);default:return e}}(t(f,n,r),h);return void 0!==r.getHeader("content-length")&&(r.headersSent?e.warn(`Rewrite response for ${n.url}: headers already sent, Content-Length left as is`):r.setHeader("content-length",m.length)),r.headersSent||r.removeHeader("etag"),r.writeHead=d,p&&!r.headersSent&&d.apply(this,p),a.call(this,m,u),this}}i()}}const Kt="<redacted>",Gt=new RegExp(`(^|;\\s*)(${ke}=)[^;]*`,"gi"),Zt=new RegExp(`^(\\s*${ke}=)[^;]*`,"i");function Xt(e){const t={...e};if("string"==typeof t.authorization){const[e,s]=t.authorization.split(/\s+/,2);t.authorization=void 0===s?Kt:`${e} ${Kt}`}return void 0!==t.token&&(t.token=Kt),"string"==typeof t.cookie&&(t.cookie=t.cookie.replace(Gt,`$1$2${Kt}`)),t}function Yt(e){const t={...e},s=t["set-cookie"],n=e=>e.replace(Zt,`$1${Kt}`);return Array.isArray(s)?t["set-cookie"]=s.map(n):"string"==typeof s&&(t["set-cookie"]=n(s)),t}const Qt=/^\/(?:login|auth)(?:[/?#]|$)/i,es=/pass(?:word|wd|code)?|pwd|secret|token|otp|mfa|2fa/i;function ts(e,t){return Array.isArray(e)?e.map(e=>ts(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,s])=>es.test(e)?(t.any=!0,[e,Kt]):[e,ts(s,t)])):e}function ss(e,t,s){if(!s)return s;if(Qt.test(e))return Buffer.from(Kt);const n=(t??"").split(";",1)[0].trim().toLowerCase();try{if("application/x-www-form-urlencoded"===n){const e=new URLSearchParams(s.toString("utf8")),t=[...new Set(e.keys())].filter(e=>es.test(e));return t.forEach(t=>e.set(t,Kt)),t.length?Buffer.from(e.toString()):s}if("application/json"===n||n.endsWith("+json")){const e={any:!1},t=ts(JSON.parse(s.toString("utf8")),e);return e.any?Buffer.from(JSON.stringify(t)):s}}catch{}return s}const ns=["/@","/_next/","/__nextjs_"],rs=new Set(["/favicon.ico","/installHook.js.map"]);function is(e){return(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0)+512}function as(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,aborted:e.aborted}}class os{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-=is(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 P()}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 n=is(t);for(;(this.totalSize+n>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+=n}get(e){return this.entries.get(e)}list(e){const t=e?.method?.toUpperCase(),s=e?.search?.toLowerCase(),n=e=>(!t||e.method===t)&&(!s||e.url.toLowerCase().includes(s)),r=Number.isFinite(e?.limit)?e.limit:1/0,i=[];if(r<=0)return i;if(void 0===e?.offset){for(let e=this.insertOrder.length-1;e>=this.head&&i.length<r;e-=1){const t=this.entries.get(this.insertOrder[e]);t&&n(t)&&i.push(as(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<r;e+=1){const t=this.entries.get(this.insertOrder[e]);t&&n(t)&&(a>0?a-=1:i.push(as(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 cs(e){const t=new M,s=async n=>{const r=await j.readdir(n,{withFileTypes:!0});for(const i of r){const r=N.join(n,i.name);if(i.isDirectory())await s(r);else if(i.isFile()){const s=N.relative(e,r).replace(/\\/g,"/");t.file(s,await j.readFile(r))}}};return await s(e),await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"})}async function ls(e,t){const s=await M.loadAsync(await j.readFile(e),{createFolders:!1}),n=N.resolve(t),r=Object.values(s.files).filter(e=>!e.name.startsWith("__MACOSX/"));for(const e of r){const t=e.unsafeOriginalName??e.name,s=N.resolve(n,t);if(s!==n&&!s.startsWith(n+N.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 j.mkdir(n,{recursive:!0});for(const e of r){const t=N.resolve(n,e.unsafeOriginalName??e.name);e.dir?await j.mkdir(t,{recursive:!0}):(await j.mkdir(N.dirname(t),{recursive:!0}),await j.writeFile(t,await e.async("nodebuffer")))}}function ds(e){return`${e}.${process.pid}.${L(4).toString("hex")}.tmp`}const us=new Map;async function ps(e,t,s){const n=ds(e);try{await H.writeFile(n,t,s),await H.rename(n,e)}catch(e){throw await H.rm(n,{force:!0}),e}}function hs(e){return(e?.distDirRoot||e?.distDir||".next").replace(/\\/g,"/").replace(/\/+$/,"")}function fs(e,t){const s=t?.distDir;if("export"!==t?.output||!s||".next"===s)return null;const n=N.resolve(e,s,"dev","types");return I.existsSync(n)?(I.rmSync(n,{recursive:!0,force:!0}),n):null}const gs=6e5;function ms(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&&_.spawn("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore"}).on("error",()=>{})}function ys(e,t,s,{cwd:n,env:r,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=_.spawn(t,s,{cwd:n,env:r,stdio:"inherit",detached:d});let p,h;const f=(e,t)=>{p?t||void 0===h||(clearTimeout(h),h=void 0,ms(u,"SIGKILL",d)):(p=e,t?(ms(u,"SIGTERM",d),h=setTimeout(()=>{h=void 0,ms(u,"SIGKILL",d)},o)):ms(u,"SIGKILL",d))},g=()=>f(`${e} was stopped`,!1),m=void 0===i?void 0:setTimeout(()=>f(`${e} timed out after ${Math.round(i/1e3)} s`,!0),i);a?.addEventListener("abort",g,{once:!0});const y=e=>{clearTimeout(m),clearTimeout(h),a?.removeEventListener("abort",g),d&&ms(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 ws=".next";async function vs(e,t={}){let s;try{const t=V(N.join(e,"package.json")).resolve("next/package.json");s=N.resolve(N.dirname(t),"dist/bin/next")}catch{throw new Error(`Unable to resolve the "next" binary from ${e}. Is Next.js installed?`)}const{distDir:n,...r}=t,i=Object.assign({},process.env,{NODE_ENV:"production",[p]:"1"});n?i[h]=n:delete i[h],await ys("next build",process.execPath,[s,"build"],{...r,cwd:e,env:i})}const bs="pageName",ks="date",$s=N.dirname("undefined"!=typeof __filename&&__filename||w(import.meta.url)),xs=N.resolve($s,"..",".."),Ss=Buffer.from([80,75,3,4]),As=20,Ts=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const Es="sync-service.meta.json",Is="BUILD-MANIFEST.json",js="__template_variables.json";class Ns{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=O.cwd(),backupFolder:n="backups",backupNameTemplate:r=`{${bs}}-{${ks}}.zip`,versionFileTemplate:i="VERSION-v{packageversion}-{currentDate}.json",buildInputFolder:a,dateFormat:o=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,""),nextBuild:l,maxBackups:d=As,buildTimeoutMs:u=gs,metaDir:p}=t||{};this.root=s,this.backupFolder=N.resolve(s,n),this.backupNameTemplate=r,this.dateFormat=o,this.versionFileTemplate=f(i,"VERSION file name template"),this.buildInputFolder=a,this.nextBuild=l,this.maxBackups="number"==typeof d&&Number.isInteger(d)&&d>0?d:1/0,this.buildTimeoutMs=u,this.metaDir=void 0===p?N.join(this.backupFolder,".pp-dev-meta"):N.resolve(s,p),this.logger=c(),this.metaLoaded=this.loadMeta()}stopBuilds(){this.builds.abort()}async checkMeta(){await j.mkdir(this.metaDir,{recursive:!0}),await j.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(o.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 j.readFile(N.join(this.metaDir,Es),{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await j.writeFile(N.join(this.metaDir,Es),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=N.resolve(this.backupFolder,e);try{return await j.stat(t),t}catch{return null}}backupName(e,t=new Date){return this.backupNameTemplate.replace(`{${bs}}`,e).replace(`{${ks}}`,this.dateFormat(t))}getBackupMeta(){return this.currentMeta}async pruneBackups(e){if(Number.isFinite(this.maxBackups))try{const t=function(e,t,s){const n=s.split(/(\d+)/).map((e,t)=>t%2==1?"\\d+":Ts(e)).join(""),r=[{token:`{${bs}}`,pattern:Ts(t)},{token:`{${ks}}`,pattern:n}].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:n}of r)i+=Ts(e.slice(a,n))+s,a=n+t.length;return new RegExp(`${i}${Ts(e.slice(a))}$`)}(this.backupNameTemplate,this.pageName,this.dateFormat(new Date)),s=new Set([e]),n=await j.readdir(this.backupFolder,{withFileTypes:!0}),r=(await Promise.all(n.filter(e=>e.isFile()&&t.test(e.name)).map(async e=>({name:e.name,mtimeMs:(await j.stat(N.resolve(this.backupFolder,e.name))).mtimeMs})))).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.name.localeCompare(e.name)),i=r.filter(e=>s.has(e.name)).length,a=r.filter(e=>!s.has(e.name)).slice(Math.max(0,this.maxBackups-i));for(const e of a)await j.unlink(N.resolve(this.backupFolder,e.name));a.length>0&&this.logger.info(o.gray(`[DistService] Deleted ${a.length} old backup(s), keeping the latest ${this.maxBackups}`))}catch(e){this.logger.warn(o.yellow(`[DistService] Could not delete old backups: ${e instanceof Error?e.message:String(e)}`))}}pathToPosix(e){return e.replace(/\\/g,"/")}normalizeBackupManifestPath(e){try{return f(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 j.readdir(t,{withFileTypes:!0});if(1!==e.length||!e[0]?.isDirectory())return t;t=N.join(t,e[0].name)}}async listFilesRecursive(e){const t=await j.readdir(e,{withFileTypes:!0}),s=[];for(const n of t){const t=N.join(e,n.name);n.isDirectory()?s.push(...await this.listFilesRecursive(t)):n.isFile()&&s.push(t)}return s}buildManifestChecksum(e){const t=Object.keys(e).sort().map(t=>e[t]).join("");return F.createHash("sha256").update(t).digest("hex")}buildBackupFingerprint(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("\n");return F.createHash("sha256").update(t,"utf-8").digest("hex")}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}versionFileTemplateMatcher(){const e=/\{[^}]+\}/g,t=[];let s=0,n=null;for(;n=e.exec(this.versionFileTemplate),n;){const[e]=n,r=this.versionFileTemplate.slice(s,n.index);t.push(this.escapeRegExp(r)),t.push("[^/]+"),s=n.index+e.length}const r=this.versionFileTemplate.slice(s);return t.push(this.escapeRegExp(r)),new RegExp(`^${t.join("")}$`,"i")}isTemplateVariablesBasename(e){return e===js}async pickTemplateVariablesFromBackupZip(e,t){const s=e.find(e=>N.basename(e)===js);if(!s)return null;const n=N.join(t,s),r=await j.readFile(n);return{relativePath:s,content:r,actualHash:F.createHash("sha256").update(r).digest("hex"),manifestHash:null}}async resolveBackupAnalysisFromZip(e){const t=await j.mkdtemp(N.join(B.tmpdir(),"pp-dev-backup-")),s=N.join(t,"backup.zip"),n=N.join(t,"extracted");try{await j.mkdir(n,{recursive:!0}),await j.writeFile(s,e),await ls(s,n);const t=await this.normalizeExtractedRootDir(n),r=(await this.listFilesRecursive(t)).map(e=>this.pathToPosix(N.relative(t,e))),i=r.filter(e=>N.basename(e)===Is);if(i.length>1)throw new Error(`Expected at most one ${Is} in backup ZIP, found ${i.length}`);const a=1===i.length?i[0]:null;let c=null;if(a){const e=N.join(t,a);if(c=JSON.parse(await j.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 l=null;if(c){const e=this.pathToPosix(c.versionFile.trim()),t=r.filter(t=>t===e),s=r.filter(t=>N.basename(t)===N.basename(e)),n=t.length>0?t:s;if(n.length>1)throw new Error(`Build manifest version file "${c.versionFile}" must resolve to exactly one file in backup ZIP, found ${n.length}`);if(1===n.length&&(l=n[0]),!0===c.compat?.versionFileRequired&&null===l)throw new Error(`Build manifest requires version file "${c.versionFile}", but it is missing in backup ZIP`)}else{const e=this.versionFileTemplateMatcher(),t=r.filter(t=>e.test(N.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&&(l=t[0])}const d={};let u=null,p=null,h=[];if(l){const e=N.join(t,l),s=JSON.parse(await j.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");p=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(d,s))throw new Error(`VERSION manifest contains duplicate normalized file path: ${s}`);d[s]=t}if(this.buildManifestChecksum(d)!==s.checksum)throw new Error("VERSION manifest checksum does not match its files map");for(const[e,s]of Object.entries(d)){const n=N.join(t,e),r=await j.readFile(n).catch(()=>null);if(!r)throw new Error(`VERSION manifest references missing file: ${e}`);const i=F.createHash("sha256").update(r).digest("hex");i!==s&&h.push({relativePath:e,expected:s,actual:i}),this.isTemplateVariablesBasename(N.basename(e))&&(u={relativePath:e,content:r,actualHash:i,manifestHash:s})}h.length>0&&this.logger.warn(o.yellow(`[DistService] VERSION manifest hash mismatch for ${h.length} file(s) (confirm in UI): ${h.map(e=>e.relativePath).join(", ")}`))}const f={},g=[];for(const e of r){if(e===a)continue;if(l&&e===l)continue;const s=N.join(t,e),n=await j.readFile(s);f[e]=F.createHash("sha256").update(n).digest("hex"),l&&!Object.prototype.hasOwnProperty.call(d,e)&&g.push(e)}u||(u=await this.pickTemplateVariablesFromBackupZip(r,t));const m=this.buildBackupFingerprint(f);let y=null;return c&&l&&m!==c.buildFingerprint&&(y={expected:c.buildFingerprint,actual:m},this.logger.warn(o.yellow(`[DistService] Build manifest fingerprint mismatch (confirm in UI): expected ${c.buildFingerprint}, got ${m}`))),{backupFingerprint:m,unknownFiles:g,templateVariables:u,mainHash:p,buildManifestMismatch:y,versionManifestHashMismatches:h}}finally{await j.rm(t,{recursive:!0,force:!0})}}async analyzeBackup(e){if(!Ss.equals(e.subarray(0,Ss.length)))throw new Error("Backup file is not a ZIP file");return await this.resolveBackupAnalysisFromZip(e)}async getPublicTemplateVariablesHash(){const e=N.resolve(this.root,"public",js),t=await j.readFile(e).catch(()=>null);return t?F.createHash("sha256").update(t).digest("hex"):null}async readPublicTemplateVariablesFile(){const e=N.resolve(this.root,"public",js);return await j.readFile(e).catch(()=>null)}async saveTemplateVariablesFile(e){const t=N.resolve(this.root,"public",js);return await j.mkdir(N.dirname(t),{recursive:!0}),await function(e,t,s){const n=(us.get(e)??Promise.resolve()).then(()=>ps(e,t,s),()=>ps(e,t,s)),r=()=>{us.get(e)===n&&us.delete(e)};return us.set(e,n),n.then(r,r),n}(t,e),t}async saveBackup(e,t){const s=(t??await this.analyzeBackup(e)).backupFingerprint,n=await this.getLatestSavedBackup(),r=await this.meta();if(n&&r.lastBackupHash===s)return void this.logger.info(o.yellow(`[DistService] Backup skipped: same backup fingerprint as last saved (${s.slice(0,12)}...)`));const i=new Date,a=this.backupName(this.pageName,i);r.lastBackupName=a,r.lastBackupHash=s,r.lastBackupDate=i.toISOString(),delete r.lastMainHash,await this.syncMeta(),await j.writeFile(N.resolve(this.backupFolder,a),e),this.logger.info(`Backup saved to ${a}`),await this.pruneBackups(a)}async buildNewAssets(){if(this.nextBuild)return await this.buildNextAssets();this.logger.info(o.cyan("[DistService] Build started"));const e=ys("pp-dev build",O.execPath,[N.resolve(xs,"./bin/pp-dev.js"),"build"],{cwd:this.root,env:Object.assign({},O.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=N.resolve(this.root,this.buildInputFolder);if(!await this.isDirectory(t))throw new Error(`Build input directory ${t} not found`);const s=await cs(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:n,configWrapped:r}=this.nextBuild,a=r||s===ws?"out":s,c=N.resolve(e,a);if(r&&function(e,t){const s=N.relative(t,e);return""===s||!(".."===s||s.startsWith(`..${N.sep}`)||N.isAbsolute(s))}(N.resolve(e,t),c))throw new Error(`The app's distDir (${t}) is inside the sync's export directory (${a}), which next build empties: set another distDir in next.config.`);const l=fs(e,{output:n,distDir:t});if(l&&this.logger.info(o.dim(`[DistService] Removed stale dev route types: ${N.relative(e,l)}`)),r||a!==t||this.logger.warn(o.yellow(`⚠️ next.config is not wrapped with withPPDev(): the sync's build exports into ${t} and removes the dev server's ${N.join(t,"dev")}; restart pp-dev next after the sync`)),r&&await j.rm(c,{recursive:!0,force:!0}),this.logger.info(o.cyan("[DistService] Next.js build started")),await this.logBuild("Next.js build",vs(e,{timeoutMs:this.buildTimeoutMs,signal:this.builds.signal,distDir:r?ws: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 i({outDir:c,root:e,packageVersion:this.nextBuild.packageVersion,versionFileTemplate:this.versionFileTemplate,packageRepositoryUrl:this.nextBuild.packageRepositoryUrl,packageBranchName:this.nextBuild.packageBranchName}),this.throwIfStopped("next build");const d=await cs(c);return this.throwIfStopped("next build"),d}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(o.yellow(`[DistService] ${e} ${s?"stopped":"failed"}`)),t}this.logger.info(o.cyan(`[DistService] ${e} finished`))}async isDirectory(e){try{return(await j.stat(e)).isDirectory()}catch{return!1}}}const Ps=["text","select","multiselect","file","list","color","boolean"];function Ls(e){return Ps.includes(e)}const Rs=["true","false","Y","N","1","0"],Fs=/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function Cs(e,t){return e.id===t||e.text===t}function Os(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,n="string"==typeof t||"number"==typeof t?String(t):void 0;return{id:n,text:"string"==typeof s?s:n??""}}function Bs(e,t,s,n){const r="select"===s.type||"multi-select"===s.type;if("string"!=typeof n&&(!r||"number"!=typeof n))return[{name:e,severity:"warning",message:`${t}: field "${s.name}" should be a string, got ${typeof n}.`}];const i=String(n);if(!i)return[];switch(s.type){case"color":return Fs.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 n=s.options.map(Os);return n.some(e=>Cs(e,i))?[]:[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${i}" is not one of the declared options (${n.map(e=>e.text).join(", ")}).`}]}case"multi-select":{if(!Array.isArray(s.options)||!s.options.length)return[];const n=s.options.map(Os),r=i.split(",").map(e=>e.trim()).filter(e=>!n.some(t=>Cs(t,e)));return r.length?[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${r.join(", ")}" is not among the declared options (${n.map(e=>e.text).join(", ")}).`}]:[]}default:return[]}}function Ms(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 n=new Set(s.map(e=>e.name)),r=[];return t.forEach((t,i)=>{const a=`"${e.name}" item #${i+1}`;if("object"!=typeof t||null===t||Array.isArray(t))return void r.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?r.push(...Bs(e.name,a,t,o[t.name])):r.push({name:e.name,severity:"warning",message:`${a} is missing field "${t.name}".`});const c=Object.keys(o).filter(e=>!n.has(e));c.length&&r.push({name:e.name,severity:"warning",message:`${a} has unexpected field(s) not declared in additional_options: ${c.join(", ")}.`})}),r}function Ds(e,t){const s=[];switch(e.tag_type){case"boolean":Rs.includes(t)||s.push({name:e.name,severity:"warning",message:`Value "${t}" is not a recognized boolean encoding (expected one of ${Rs.join(", ")}).`});break;case"list":try{const n=JSON.parse(t);Array.isArray(n)?s.push(...Ms(e,n)):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 n=e.additional_options.map(Os),r=("multiselect"===e.tag_type?t.split(",").map(e=>e.trim()):[t]).filter(e=>!n.some(t=>Cs(t,e)));r.length&&s.push({name:e.name,severity:"warning",message:`Value "${r.join(", ")}" does not match any declared option for "${e.name}".`})}}return s}function Us(e,t){switch(e.tag_type){case"boolean":return Rs.includes(t)?null:`Not a recognized boolean value ("${t}").`;case"color":return""===t||Fs.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 Hs="/@pp-dev/variables-editor",_s=/^[A-Za-z0-9_\s-]+$/,Vs="Dist service or MiAPI is not defined",zs=new WeakMap;async function qs(e){const t=await e.readPublicTemplateVariablesFile();if(!t)return null;const s=t.toString("utf-8");let n;try{n=JSON.parse(s)}catch(e){return{raw:s,schema:null,parseError:e instanceof Error?e.message:"Invalid JSON"}}return"object"!=typeof n||null===n||Array.isArray(n)||!Array.isArray(n.tags)?{raw:s,schema:null,parseError:'The root value must be a JSON object with a "tags" array.'}:{raw:s,schema:n}}async function Ws(e){const t=e?(await qs(e))?.schema??null:null;return t&&{...t,tags:t.tags.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.name&&""!==e.name)}}function Js(e,t,s){const n=zs.get(e);if(n)return void(n.deps=t);const r={deps:t};zs.set(e,r),e.get("/@api/variables/schema",async(e,t)=>{const{distService:s}=r.deps;if(!s)return void t.status(503).json({error:Vs});const n=await qs(s);t.json(n?{exists:!0,...n}:{exists:!1,schema:null,raw:null})}),e.put("/@api/variables/schema",async(e,t)=>{const{distService:s}=r.deps;if(!s)return void t.status(503).json({error:Vs});const n=e.body?.raw;if("string"!=typeof n)return void t.status(400).json({error:"Request body must be { raw: string }."});let i;try{i=JSON.parse(n)}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&&!Ls(e.tag_type)&&c.push(`"${e.name}" has an unrecognized tag_type "${e.tag_type}".`),_s.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(n,"utf-8"))}catch(e){return void t.status(500).json({error:`Failed to write ${js}.`,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:n}=r.deps;try{const e=await Ws(s),r=await n.getLivePageVariables(),i=function(e,t){const s=(e?.tags??[]).filter(e=>"string"==typeof e?.name&&""!==e.name),n=new Map(s.map(e=>[e.name,e])),r=new Map(t.map(e=>[e.name,e.value])),i=new Set([...n.keys(),...r.keys()]);return Array.from(i).map(e=>({name:e,value:r.get(e)??n.get(e)?.default_value??""}))}(e,r);t.json({schema:e,live:r,combined:i,local:n.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:n}=r.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:n}=e;if("string"!=typeof t||!t||"string"!=typeof n)return null;s.push({name:t,value:n})}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 Ws(s),r=new Map((e?.tags??[]).map(e=>[e.name,e])),a=[];for(const e of i){const t=r.get(e.name);t&&a.push(...Ds(t,e.value))}let o;await n.applyPageVariables(i);try{await n.reloadPageVariables()}catch(e){o=e instanceof Error?e.message:String(e)}t.json({ok:!0,warnings:a,local:n.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}=r.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}=r.deps;try{const e=await s.listPages(),n=e=>void 0!==s.pageId?e.id===s.pageId:e.internal_name===s.internalPageName,r=e.find(n)??null,i=e.filter(e=>!n(e)).map(e=>({id:e.id,name:e.name,internal_name:e.internal_name,sameTemplate:!!r&&(null!=r.template_id?e.template_id===r.template_id:!!r.template&&e.template===r.template)}));t.json({pages:i,currentPageName:r?.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:n}=r.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 Ws(s),r=await n.getPageVariablesFor(i);t.json(function(e,t){const s=new Map((e?.tags??[]).map(e=>[e.name,e])),n=[],r=[];for(const e of t){const t=s.get(e.name);if(!t){r.push({name:e.name,sourceValue:e.value,reason:"Not in the current page's schema."});continue}const i=Us(t,e.value);i?r.push({name:e.name,sourceValue:e.value,reason:i}):n.push({name:e.name,sourceValue:e.value,tagType:t.tag_type||"text"})}return{importable:n,skipped:r}}(e,r))}catch(e){t.status(502).json({error:"Failed to fetch values from the selected page.",details:e instanceof Error?e.message:String(e)})}}),Z(e,{path:Hs,name:"variables-editor",clientDir:s,values:()=>({templateLess:String(Boolean(r.deps.miAPI.isTemplateLess))})})}const Ks=12e4;class Gs{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=c(),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??Ks)/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(o.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=C(),n=this.opts.syncActionTimeoutMs??Ks;return await new Promise(r=>{const i=e=>this.resolveSyncAction(s,{approved:!1,reason:e}),a=setTimeout(()=>i("timeout"),n),{socket:o}=t,c=()=>i("disconnected");o?.once("close",c),this.syncActionResolvers.set(s,{resolve:r,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(o.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(o.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 n=await s.getAssets().catch(async e=>{if(await this.reportMiFailure(t,e))return e;throw e});if(n instanceof Error)return;let r;if(n){const s=await(e?.analyzeBackup(n).catch(e=>e));if(s instanceof Error)r=s;else if(s){await(e?.saveBackup(n,s));const i=0===s.unknownFiles.length&&1===s.versionManifestHashMismatches.length&&N.basename(s.versionManifestHashMismatches[0].relativePath)===js,a=s.versionManifestHashMismatches,o=a.filter(e=>N.basename(e.relativePath)===js),c=a.filter(e=>N.basename(e.relativePath)!==js),l=!i&&o.length>0&&c.length>0,d=i?[]:c.map(e=>e.relativePath),u=async()=>{if(!s.templateVariables||!e)return!0;const{templateVariables:n}=s;if(await e.getPublicTemplateVariablesHash()!==n.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(n.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(!i&&d.length>0){const e=40,s=d,n=s.slice(0,e),r=s.length-n.length,i=n.map(e=>`• ${e}`).join("\n"),a=r>0?`\n... and ${r} more file${1===r?"":"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(!i&&s.buildManifestMismatch&&0===s.versionManifestHashMismatches.length){const{expected:e,actual:n}=s.buildManifestMismatch,r=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: ${n.slice(0,12)}...\nContinue sync anyway?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!r.approved)return void this.cancelSync(t,r.reason)}if(!l&&!await u())return;r=await(e?.buildNewAssets())}}else r=await(e?.buildNewAssets());if(!(r&&r instanceof Buffer))return r instanceof Error?(this.sendSyncResponse(t,{error:r.message}),void this.logger.error(o.red(r.message))):(this.sendSyncResponse(t,{error:"Failed to build new assets"}),void this.logger.error(o.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(o.yellow("Sync stopped before the upload: the dev server is shutting down"));let n;try{n=await s.updateAssets(r)}catch(e){if(await this.reportMiFailure(t,e))return;throw e}if("OK"===n?.status){const s=e?.getBackupMeta();this.sendSyncResponse(t,{syncedAt:(new Date).toISOString(),backupFilename:s?.lastBackupName??""}),this.logger.info(o.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)}`}(n)}`;this.sendSyncResponse(t,{error:e}),this.logger.error(o.red(e))}}}catch(e){const s=e instanceof Error?e.message:"Template sync failed";return this.logger.error(o.red(`Template sync failed: ${s}`)),void this.sendSyncResponse(t,{error:s,code:"SYNC_FAILED"})}}}async reportMiFailure(e,s){if(t(s)){if("SESSION_EXPIRED"===Ie(s).code){this.logger.info(o.yellow("Session expired - attempting to validate credentials"));try{const t=await(this.opts.miAPI?.validateCredentials());t&&!t.isValid?(this.logger.error(o.red(`Authentication error: ${t.error}`)),this.sendSyncResponse(e,{error:t.error??"Authentication failed",code:t.code,refresh:!0})):(this.logger.info(o.yellow("Session expired")),this.sendSyncResponse(e,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0}))}catch{this.logger.info(o.yellow("Session expired")),this.sendSyncResponse(e,{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(o.yellow("Server in maintenance mode, VPN connection is needed or no internet connection")),this.sendSyncResponse(e,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0;const t=s.response?.status;if(502===t||503===t||504===t)return this.logger.info(o.yellow(`Server in maintenance mode or unreachable (HTTP ${t}); VPN may be required`)),this.sendSyncResponse(e,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0}return!!ge(s)&&(this.logger.info(o.yellow("Server in maintenance mode or non-JSON page / page-template API response (unavailable HTML body)")),this.sendSyncResponse(e,{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(o.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(o.green("Page variables reloaded"))}catch(e){const s=e instanceof Error?e.message:"Reload variables failed";this.logger.error(o.red(`Reload variables failed: ${s}`)),t.send("page-variables:reload:response",{error:s})}}}const Zs="/@api/users",Xs=new WeakMap;function Ys(e,t){const s=We(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 Qs(e,t,s,n){e.status(t).json({error:n,code:s})}function en(e){let t;try{t=JSON.parse(U.readFileSync(e,"utf-8"))}catch(t){return"ENOENT"!==t.code&&c().warn(o.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 tn(e,t,s){const n={version:1,...s,users:t};U.mkdirSync(q.dirname(e),{recursive:!0,mode:448}),function(e,t,s){const n=ds(e);try{D.writeFileSync(n,t,s),D.renameSync(n,e)}catch(e){throw D.rmSync(n,{force:!0}),e}}(e,`${JSON.stringify(n,null,2)}\n`,{mode:384}),U.chmodSync(e,384)}const sn=new WeakMap,nn=new WeakMap;function rn(e){sn.delete(e),nn.get(e)?.(),nn.delete(e)}async function an(e,t){const s=function(e,t,s=z.homedir()){const n=R("sha256").update(`${q.resolve(e)}\n${t.replace(/\/+$/,"")}`).digest("hex").slice(0,16);return q.join(s,".pp-dev","users",`${n}.json`)}(t.projectRoot,t.miUrl,t.homeDir),n={project:q.resolve(t.projectRoot),miUrl:t.miUrl},r=c();if(sn.get(e)===s)return;rn(e),sn.set(e,s);const i=en(s);let a=!0,l=!1,d=e.list().some(e=>"token"===e.kind&&e.token);const u=new Set,p=new Set,h=()=>{const t=e.list(),i=t.filter(e=>"token"===e.kind&&e.token).map(e=>({name:e.name,token:e.token})),a=new Set(t.map(e=>e.name)),c=en(s).filter(e=>!a.has(e.name)&&!p.has(e.name));try{tn(s,[...i,...c],n)}catch(e){r.warn(o.yellow(`Could not save the users to ${s}: ${String(e)}`))}},f=e.onRemove(t=>{sn.get(e)===s&&(p.add(t.name),a&&u.add(t.name))}),g=e.onChange(()=>{sn.get(e)===s&&(a?d||=!l:h())});nn.set(e,()=>{f(),g()});try{const n=await Promise.all(i.map(e=>t.checkToken(e.token)));if(sn.get(e)!==s)return;i.forEach((t,s)=>{if(ze(t.name)||e.get(t.name)||u.has(t.name))return;const i=n[s];l=!0;try{e.add({name:t.name,kind:"token",token:t.token,...i.ok?{miUser:i.miUser}:{},...!i.ok&&i.rejected?{state:"expired"}:{}})}finally{l=!1}i.ok||r.warn(o.yellow(`Restored user ${t.name}: ${i.message}`))})}finally{a=!1}d&&sn.get(e)===s&&h(),i.length&&r.info(`${o.blue("Restored")} ${i.length} ${o.blue("saved user(s) from")} ${s}`)}function on(e){const t=`${q.resolve(e.projectRoot)}\n${e.miUrl.replace(/\/+$/,"")}`;Je.context!==t&&(rn(Je),Je.useContext(t)),e.persist?e.miAPI.personalAccessToken?an(Je,{projectRoot:e.projectRoot,miUrl:e.miUrl,checkToken:t=>et(e.miAPI,t)}).catch(e=>{c().warn(o.yellow(`Could not restore the saved users: ${String(e)}`))}):c().warn(o.yellow("users.persist is on, but users need your own API token (mi.token or MI_ACCESS_TOKEN).")):rn(Je)}function cn(e,t,s,n,r){const i={error:s};n&&(i.details=n),r&&(i.code=r),e.status(t).json(i).end()}function ln(e){return["/@vite","/@metricinsights","/@",(e.endsWith("/")?e.slice(0,-1):e)||"/"]}function dn(e){const{distService:t,miAPI:s,persistUsers:n,projectRoot:r,miUrl:i}=e,a=new Gs(e.server,{distService:t,miAPI:s});return function(e,t){const{miAPI:s,persistUsers:n,projectRoot:r,miUrl:i}=t,a=c(),o=(e,t,s)=>{a.error(`${s} token validation error: ${t instanceof Error?t.message:String(t)}`);const n=Ie(t),r=t?.tokenErrorInfo;if(r)return cn(e,r.status||500,r.userFriendlyMessage,r.message,r.code),null;let i,o,c;switch(n.code){case"SESSION_EXPIRED":i=412,o="personal"===s?"Personal access token expired":"Session expired",c="personal"===s?"PAT_EXPIRED":"SESSION_EXPIRED";break;case"UNAUTHORIZED":i=401,o="Unauthorized",c="UNAUTHORIZED";break;case"FORBIDDEN":i=403,o="Access forbidden",c="FORBIDDEN";break;default:i=500,o="Internal server error",c=n.code}return cn(e,i,o,"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.":n.userFriendlyMessage,c),null};e.post("/@api/login",async(e,t)=>{const{token:c,tokenType:l}=e.body??{};if(qe(e.headers.host))cn(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 c&&c)if(a.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 ${c}`},!0).then(e=>"object"!=typeof e.data||null===e.data?(cn(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=c,a.info(`Personal access token validated successfully for user ${e.data.user.user_id}`),e):(cn(t,400,"Token expired or invalid"),null)).catch(e=>o(t,e,"personal")))return;$t("logged in with a personal access token"),on({persist:n,miAPI:s,projectRoot:r,miUrl:i}),Ce(t,"/",302)}else if("regular"===l){if(!await s.get("/api/user",{"Content-Type":"application/json",Accept:"application/json",Token:c},!0).then(n=>n.data?.users?.length?(s.personalAccessToken=void 0,a.info(`Regular token validated successfully for ${n.data.users.length} user(s)`),t.setHeader("set-cookie",Ae(n.headers["set-cookie"],ve(e))??""),n):(cn(t,400,"Token expired or invalid"),null)).catch(e=>o(t,e,"regular")))return;$t("logged in with a token"),Ce(t,"/",302)}else cn(t,400,"Invalid tokenType",'tokenType must be "personal" or "regular".',"INVALID_TOKEN_TYPE");else cn(t,400,"Token is required")})}(e.internalServer,{miAPI:s,persistUsers:n,projectRoot:r,miUrl:i}),Js(e.internalServer,{distService:t,miAPI:s}),function(e,t){const s=Xs.get(e);if(s)return void(s.deps=t);const n={deps:t};Xs.set(e,n);const r=c(),i=()=>n.deps.users??Je;e.get(Zs,(e,t)=>{const s=i();t.json({available:Boolean(n.deps.miAPI.personalAccessToken),users:s.list().map(t=>Ys(t,e)),defaultUser:s.defaultUser?.name??null})}),e.put(`${Zs}/default`,(e,t)=>{const s=i(),n=(e.body??{}).name;if(null===n||"string"==typeof n)if(null===n||s.get(n)){try{s.setDefaultUser(n??void 0)}catch(e){return void Qs(t,409,"NOT_LOGGED_IN",e instanceof Error?e.message:String(e))}r.info(`${o.blue("Default user:")} ${o.yellow(n??"the original user")}`),t.json({defaultUser:n})}else Qs(t,404,"NOT_FOUND",`There is no user named "${n}"`);else Qs(t,400,"INVALID_NAME","name must be a user name or null")}),e.post(Zs,async(e,t)=>{const{miAPI:s}=n.deps,a=i(),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 Qs(t,400,"INVALID_KIND",'kind must be "token" or "session"');if(!s.personalAccessToken)return void Qs(t,409,"ORIGINAL_TOKEN_REQUIRED","Adding users needs your own API token: set mi.token or MI_ACCESS_TOKEN.");const p=ze(l);if(p)return void Qs(t,400,"INVALID_NAME",p);if(a.get(l))return void Qs(t,409,"NAME_TAKEN",`A user named "${l}" already exists`);if("session"===u){const s=a.add({name:l,kind:"session"});return r.info(`${o.blue("Added user")} ${o.yellow(s.name)}: log in at ${We(e,s.name)}/login`),void t.status(201).json({user:Ys(s,e)})}if(!d)return void Qs(t,400,"TOKEN_REQUIRED","The API token is required");const h=a.context,f=await et(s,d);if(a.context!==h||n.deps.miAPI!==s||i()!==a)return void Qs(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; add the user again");if(!f.ok)return void(f.rejected?Qs(t,400,"INVALID_TOKEN",f.message):Qs(t,502,"MI_UNAVAILABLE",f.message));const{miUser:g}=f;let m;try{m=a.add({name:l,kind:"token",token:d,miUser:g})}catch(e){return void Qs(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}r.info(`${o.blue("Added user")} ${o.yellow(m.name)} (MI user ${g.id}${g.username?`, ${g.username}`:""}) at ${We(e,m.name)}`),t.status(201).json({user:Ys(m,e)})}),e.patch(`${Zs}/:name`,async(e,t)=>{const{miAPI:s}=n.deps,a=i(),c=String(e.params.name),l=a.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 Qs(t,404,"NOT_FOUND",`There is no user named "${c}"`);if("token"!==l.kind)return void Qs(t,400,"NOT_EDITABLE","Only users added with an API token can be edited. Remove this user and add it again.");const h=ze(u);if(h)return void Qs(t,400,"INVALID_NAME",h);if(u!==c&&a.get(u))return void Qs(t,409,"NAME_TAKEN",`A user named "${u}" already exists`);let f,g={...l,name:u};if(p&&(p!==l.token||"expired"===l.state)){const e=a.context,r=await et(s,p);if(a.context!==e||n.deps.miAPI!==s||i()!==a)return void Qs(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; edit the user again");if(!r.ok)return void(r.rejected?Qs(t,400,"INVALID_TOKEN",r.message):Qs(t,502,"MI_UNAVAILABLE",r.message));const{state:o,...c}=g;g={...c,token:p,miUser:r.miUser}}if(a.get(c)===l)if(u!==c||g.token!==l.token||g.state!==l.state){try{f=a.replace(c,g)}catch(e){return void Qs(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}r.info(`${o.blue("Edited user")} ${o.yellow(c)}${u!==c?` → ${o.yellow(u)}`:""}${f.token!==l.token?" (new API token)":""}`),t.json({user:Ys(f,e)})}else t.json({user:Ys(l,e)});else Qs(t,409,"USER_CHANGED",`The user "${c}" changed meanwhile; edit it again`)}),e.delete(`${Zs}/:name`,(e,t)=>{const s=String(e.params.name);i().remove(s)?(r.info(`${o.blue("Removed user")} ${o.yellow(s)}`),t.status(204).end()):Qs(t,404,"NOT_FOUND",`There is no user named "${s}"`)})}(e.internalServer,{miAPI:s}),on({persist:n,miAPI:s,projectRoot:r,miUrl:i}),a}function un(e,t){const s=t instanceof Error?t.message:String(t);c().error(o.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)))}function pn(e,t,s,n){let r=0;const i=a=>{if(a)return void un(s,a);if(r>=e.length)return void n();const o=e[r];r+=1;try{o(t,s,i)}catch(e){un(s,e)}};i()}function hn(e){const{templateName:t,internalServer:s,backendBaseURL:n,inspector:r,proxy:i}=e,a=e.base.endsWith("/")?e.base:`${e.base}/`,l=[],d=[];if(n){const e=Ke();l.push(e),d.push(e)}if(r.enabled){const e=new os(r.maxMemory);te(s,e,r.captureLimit),l.push(function(e,t=10485760,s=Je){return(n,r,i)=>{const a=n.url||"/",o=a.split("?")[0];if(ns.some(e=>a.startsWith(e))||rs.has(o))return void i();const c=e.allocateId(),l=s.resolve(n)?.user?.name,d=Date.now(),u=[];let p=0,h=!1;const f=n.emit.bind(n);n.emit=(e,...s)=>{if("data"===e&&!h){const e=s[0],n=Buffer.isBuffer(e)?e:Buffer.from(String(e));p+=n.byteLength,p<=t?u.push(n):(h=!0,u.length=0)}return f(e,...s)};const g=[];let m=0,y=!1;const w=r.write.bind(r),v=r.end.bind(r);function b(e,s){if(!y&&null!=e)try{const n=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+=n.byteLength,m<=t?g.push(n):(y=!0,g.length=0)}catch{}}function k(e){return"string"==typeof e[0]?e[0]:void 0}function $(){const e=r.getHeaders();return e["x-pp-proxy"]?"hit"===e["x-pp-cache"]?"proxy-cache":"proxy":"local"}let x=!1;function S(t=!1){if(x)return;x=!0;const s=ss(a,"string"==typeof n.headers["content-type"]?n.headers["content-type"]:void 0,!h&&u.length>0?Buffer.concat(u):null),i=!y&&g.length>0?Buffer.concat(g):null;e.add({id:c,timestamp:d,method:n.method||"GET",url:a,statusCode:r.statusCode??null,duration:Date.now()-d,source:$(),user:l,requestHeaders:Xt(n.headers),requestBody:s,requestBodyTruncated:h,responseHeaders:Yt(r.getHeaders()),responseBody:i,responseBodyTruncated:y,...t?{aborted:t}:{}})}r.once("close",()=>S(!0)),r.write=(e,...t)=>(b(e,k(t)),w(e,...t)),r.end=(e,...t)=>("function"!=typeof e&&b(e,k(t)),S(),v(e,...t)),i()}}(e,r.captureLimit))}const u=Ue(a,t);if(l.push(u),d.push(u),e.devPanelAssets){const e=g(a);l.push(e),d.push(e)}if(r.enabled||n){const e=(e,t,n)=>{const r=e.url??"";r.startsWith("/@api/")||r.startsWith(Y)||r.startsWith(Hs)?s(e,t,e=>function(e,t){t?un(e,t):e.headersSent||e.writableEnded||(e.statusCode=404,e.setHeader("content-type","application/json"),e.end(JSON.stringify({error:"Not found"})))}(t,e)):n()};l.push(e),d.push(e)}let p=null,h=null,f=null;if(n){"/"===a&&c().warn(o.yellow("⚠️ The app's base is '/': MI's paths can't be told from the app's files, so nothing is proxied to MI. Give the app a base path (withPPDev() does, from app.name)."));const s=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}}(n,e.mi);p=new De(n,s),i.cache&&(h=function(e){const t=Number(e);return!t||Number.isNaN(t)||t<0?6e5:t}(i.cacheTtl),l.push(It({devServer:i.devServer,ttl:h}))),l.push(Ht(function(e){return new RegExp(`^((${t=e,t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`);var t}(a),p,{...e.mi,base:a,appBase:a})),l.push(ht({baseURL:n,proxyIgnore:[...ln(a),...i.ignore??[]],disableSSLValidation:e.mi.disableSSLValidation,miAPI:p,templateName:t}));const r=e.rewrite(p,new URL(n).host);f=Jt((e,t)=>r.predicate(e,t),(e,t)=>r.transform(e,t),r.contentType?{contentType:r.contentType}:{})}return{main:l,essential:d,rewrite:f,mi:p,proxyCacheTtl:h}}function fn(e,t){for(const s of t.main)e.middlewares.use(s)}const gn="10mb",mn=(e,t,s,n)=>{const r="number"==typeof e?.status?e.status:void 0;if(!r||r<400||r>=500||"string"!=typeof e.type||s.headersSent)return void n(e);const i="entity.too.large"===e.type?`The request body is larger than the dev server accepts (${gn}).`:`The request body could not be read: ${e.message}`;s.status(r).json({error:i})};function yn({allowedHosts:e=[]}={}){const t=W();return t.use(m(e)),t.use(W.json({limit:gn})),t.use(W.urlencoded({extended:!0})),t.use(mn),t}export{Ns as D,Y as I,J as P,hs as a,hn as b,yn as c,fs as d,ls as e,vs as f,fn as m,pn as r,dn as s,Re as u,cs as z};
2
+ //# sourceMappingURL=internal.middleware-CC20He9L.js.map