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

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 (35) hide show
  1. package/README.md +17 -9
  2. package/dist/cjs/auth.provider-D5AI-ujG.js +2 -0
  3. package/dist/cjs/auth.provider-D5AI-ujG.js.map +1 -0
  4. package/dist/cjs/index.js +1 -1
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/plugin.js +1 -1
  7. package/dist/cjs/plugin.js.map +1 -1
  8. package/dist/cjs/{version-manifest-DdWlzzZ6.js → version-manifest-DuXhzqGr.js} +2 -2
  9. package/dist/cjs/{version-manifest-DdWlzzZ6.js.map → version-manifest-DuXhzqGr.js.map} +1 -1
  10. package/dist/cjs/version-plugin-DrG2-mQf.js +2 -0
  11. package/dist/cjs/{version-plugin-B1Sb07cW.js.map → version-plugin-DrG2-mQf.js.map} +1 -1
  12. package/dist/client/client.js +113 -53
  13. package/dist/client/client.js.map +1 -1
  14. package/dist/client/request-inspector.js +12 -1
  15. package/dist/client/request-inspector.js.map +1 -1
  16. package/dist/client/variables-editor.js +169 -36
  17. package/dist/client/variables-editor.js.map +1 -1
  18. package/dist/esm/cli.js +1 -1
  19. package/dist/esm/cli.js.map +1 -1
  20. package/dist/esm/{internal.middleware-CC20He9L.js → internal.middleware-wi0Mb4oZ.js} +2 -2
  21. package/dist/esm/internal.middleware-wi0Mb4oZ.js.map +1 -0
  22. package/dist/esm/plugin.js +1 -1
  23. package/package.json +6 -8
  24. package/dist/cjs/auth.provider-6rZUaR33.js +0 -2
  25. package/dist/cjs/auth.provider-6rZUaR33.js.map +0 -1
  26. package/dist/cjs/cli.js +0 -2
  27. package/dist/cjs/cli.js.map +0 -1
  28. package/dist/cjs/index-Cc-bAhnE.js +0 -2
  29. package/dist/cjs/index-Cc-bAhnE.js.map +0 -1
  30. package/dist/cjs/internal.middleware-BlM7gqkq.js +0 -2
  31. package/dist/cjs/internal.middleware-BlM7gqkq.js.map +0 -1
  32. package/dist/cjs/migrate-DDdeB-Fj.js +0 -2
  33. package/dist/cjs/migrate-DDdeB-Fj.js.map +0 -1
  34. package/dist/cjs/version-plugin-B1Sb07cW.js +0 -2
  35. package/dist/esm/internal.middleware-CC20He9L.js.map +0 -1
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("axios"),t=require("node:http"),s=require("node:https"),r=require("./version-manifest-DdWlzzZ6.js"),n=require("./auth.provider-6rZUaR33.js"),i=require("url"),a=require("http-proxy-middleware"),o=require("node:string_decoder"),c=require("zlib"),l=require("fs"),d=require("path"),u=require("node:crypto"),p=require("crypto"),h=require("process"),g=require("os"),f=require("jszip"),m=require("node:fs"),y=require("node:fs/promises"),w=require("child_process"),v=require("module"),b=require("node:os"),k=require("node:path"),$=require("express");var x="undefined"!=typeof document?document.currentScript:null;const S=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function A(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const s in e)t[s]=e[s];return t.default=e,Object.freeze(t)}const T=S(e),E=S(t),I=S(s),P=A(l),L=A(d),j=A(p),N=A(h),R=A(g),C=S(f),O=A(m),M=S(m),B=A(y),F=A(w),D=S(b),_=S(k),U=S($),H=L.dirname(n.PP_DEV_CLIENT_ENTRY),V={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function q(e,t){const s=t.clientDir??H,r=new Set([`${t.name}.js`,`${t.name}.css`,`${t.name}.js.map`,`${t.name}.css.map`]);e.get(t.path,(e,r)=>{P.readFile(L.join(s,`${t.name}.html`),"utf-8",(e,s)=>{if(e)return void r.status(500).type("text/plain").end(`${t.name} page not built (${e.message})`);const n=t.values?.()??{};r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-cache"),r.end(s.replace(/\{\{(\w+)\}\}/g,(e,t)=>n[t]??e))})}),e.get(`${t.path}/:file`,(e,t,n)=>{const i=e.params.file;r.has(i)?P.readFile(L.join(s,i),(e,s)=>{e?n():(t.setHeader("Content-Type",V[L.extname(i)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(s))}):n()})}function z(e,t,s={}){switch(t){case"gzip":return c.unzipSync(e,s);case"br":return c.brotliDecompressSync(e,s);case"deflate":return c.inflateSync(e,s);default:return e}}const W="/@pp-dev/inspector",J=new WeakMap;function G(e){const t=Array.isArray(e)?e[0]:e;return"string"==typeof t?t:void 0}function K(e,t,s=10485760,r=H){const n=J.get(e);if(n)return n.store=t,void(n.captureLimit=s);const i={store:t,captureLimit:s};J.set(e,i),e.get("/@api/requests",(e,t)=>{const{store:s}=i,r=G(e.query.limit),n=G(e.query.offset),a=G(e.query.method),o=G(e.query.search),c=void 0!==r?parseInt(r,10):void 0,l=s.list({limit:Number.isFinite(c)?c:500,offset:void 0!==n&&Number.isFinite(parseInt(n,10))?parseInt(n,10):void 0,method:a,search:o});t.json({requests:l,total:s.size,memoryUsage:s.memoryUsage,maxMemory:s.maxMemory})}),e.get("/@api/requests/stats",(e,t)=>{const{store:s}=i;t.json({total:s.size,memoryUsage:s.memoryUsage,maxMemory:s.maxMemory,memoryUsageFormatted:Z(s.memoryUsage),maxMemoryFormatted:Z(s.maxMemory)})}),e.get("/@api/requests/:id",(e,t)=>{const s=i.store.get(e.params.id);if(!s)return void t.status(404).json({error:"Not found",id:e.params.id});const r=X(s.requestHeaders["content-type"]),n=X(s.responseHeaders["content-type"]),a=s.responseBody?function(e,t,s){const r=Array.isArray(t)?t.join(", "):String(t??"");try{return z(e,r.trim().toLowerCase(),{maxOutputLength:s})}catch(t){return t instanceof RangeError?null:e}}(s.responseBody,s.responseHeaders["content-encoding"],i.captureLimit):null;t.json({id:s.id,timestamp:s.timestamp,method:s.method,url:s.url,statusCode:s.statusCode,duration:s.duration,source:s.source,user:s.user,requestHeaders:s.requestHeaders,requestBody:s.requestBody?s.requestBody.toString("base64"):null,requestBodySize:s.requestBody?.byteLength??0,requestBodyTruncated:s.requestBodyTruncated,requestContentType:r,responseHeaders:s.responseHeaders,responseBody:a?a.toString("base64"):null,responseBodySize:s.responseBody?.byteLength??0,responseBodyTruncated:s.responseBodyTruncated||null!==s.responseBody&&null===a,responseContentType:n})}),e.delete("/@api/requests",(e,t)=>{i.store.clear(),t.json({ok:!0})}),q(e,{path:W,name:"request-inspector",clientDir:r,values:()=>({captureLimit:String(i.captureLimit)})})}function X(e){return Array.isArray(e)?e[0]??"":String(e??"")}function Z(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/1073741824).toFixed(2)} GB`}class Y{axios;constructor(e){this.axios=e}async checkAuth(e){return this.axios.get("/data/page/index/auth/info",{headers:Object.assign({},e,{accept:"text/html"}),maxRedirects:0}).then(()=>!0).catch(()=>!1)}}class Q extends Y{getDownloadUrl(e){return`/admin/page/downloadassets/id/${e}`}getDownloadTemplateUrl(e){return`/admin/pagetemplate/downloadassets/id/${e}`}getUploadUrl(e){return`/admin/page/uploadassets/id/${e}`}getUploadTemplateUrl(e){return`/admin/pagetemplate/uploadassets/id/${e}`}async downloadPageAssets(e,t){return this.download(this.getDownloadUrl(e),t)}async uploadPageAssets(e,t,s){return this.upload(this.getUploadUrl(e),t,s)}async downloadTemplateAssets(e,t){return this.download(this.getDownloadTemplateUrl(e),t)}async uploadTemplateAssets(e,t,s){return this.upload(this.getUploadTemplateUrl(e),t,s)}async download(e,t){return this.axios.get(e,{withCredentials:!0,headers:Object.assign({},t,{accept:"*/*"}),responseType:"arraybuffer"}).then(e=>e.data)}async upload(e,t,s){const r=new FormData;return r.append("file",new File([new Uint8Array(t)],"file.zip",{type:"application/zip"}),"file.zip"),this.axios.post(e,r,{withCredentials:!0,headers:Object.assign({},s,{accept:"application/json","Content-Type":"multipart/form-data",Referer:this.axios.getUri({url:e})})}).then(e=>e.data)}}class ee extends Q{getDownloadUrl(e){return`/api/page/id/${e}/asset/download`}getDownloadTemplateUrl(e){return`/api/page_template/id/${e}/asset/download`}getUploadUrl(e){return`/api/page/id/${e}/asset/upload`}getUploadTemplateUrl(e){return`/api/page_template/id/${e}/asset/upload`}}const te="Something went wrong when fetching page data",se="Something went wrong when fetching page template data",re="Something went wrong when fetching page variables",ne="Something went wrong when checking who the credentials belong to",ie=" The instance may be down or in maintenance mode. Please try again later.",ae=[te,se,re,ne];function oe(){return new Error(`${te}.${ie}`)}function ce(){return new Error(`${se}.${ie}`)}function le(e){return e instanceof Error&&ae.some(t=>e.message.includes(t))}class de extends Y{async getAll(e){const t=(await this.axios.get("/api/page",{withCredentials:!0,headers:Object.assign({},e,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"})})).data;if("object"!=typeof t||null===t||!Array.isArray(t.pages))throw oe();return t.pages}async get(e,t){const s=(await this.axios.get(`/api/page/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page||null===s.page)throw oe();return s.page}async getPageContent(e,t){return(await this.axios.get(`/p/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"text/html","content-type":"application/json"})})).data}async create(e,t){const s=(await this.axios.post("/api/page",e,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page||null===s.page)throw oe();return s.page}}class ue extends Y{async getAll(e,t){const s=(await this.axios.get("/api/page_template",{withCredentials:!0,headers:Object.assign({},t,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"}),params:{internal_name:e}})).data;if("object"!=typeof s||null===s||!Array.isArray(s.page_templates))throw ce();return s.page_templates}async get(e,t){const s=(await this.axios.get(`/api/page_template/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page_template||null===s.page_template)throw ce();return s.page_template}}class pe extends Y{async getById(e,t){const s=(await this.axios.get("/api/page_variable",{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"}),params:{page_id:e}})).data;if("object"!=typeof s||null===s)throw new Error(`${re}.${ie}`);return function(e){let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch{throw new TypeError('Page variable response contains invalid JSON in "tags".')}if(!Array.isArray(t))throw new TypeError('Page variable response must contain a "tags" array.');const s=t.findIndex(e=>{return!("object"==typeof(t=e)&&null!==t&&"string"==typeof t.name&&"string"==typeof t.value);var t});if(-1!==s)throw new TypeError(`Page variable response contains a malformed entry at index ${s}.`);return t}(s.tags)}async updateById(e,t,s){await this.axios.put("/api/page_variable",{tags:JSON.stringify(t)},{withCredentials:!0,headers:Object.assign({},s,{accept:"application/json","content-type":"application/json"}),params:{page_id:e}})}}function he(e){if(e.socket?.encrypted)return!0;const t=e.headers?.["x-forwarded-proto"],s=Array.isArray(t)?t[0]:t;return"string"==typeof s&&"https"===s.split(",",1)[0].trim().toLowerCase()}function ge(e,t){const[s,...r]=e.split(";"),n=r.map(e=>e.trim()).filter(e=>{if(!e)return!1;const s=e.split("=",1)[0].trim().toLowerCase();return"domain"!==s&&(t||"secure"!==s)}).map(e=>!t&&/^samesite\s*=\s*none$/i.test(e)?"SameSite=Lax":e);return[s.trim(),...n].join("; ")}const fe="metric_insights_session";function me(e,t){for(const s of e){const e=s.indexOf("=");if(-1!==e&&s.slice(0,e).trim()===t)return s.slice(e+1).trim()}}function ye(e,t){return e?me(e.split(";"),t):void 0}function we(e,t){if(void 0===e||"number"==typeof e)return;return me((Array.isArray(e)?e:[e]).map(e=>e.split(";",1)[0]),t)}function ve(e,t){return void 0===e?e:Array.isArray(e)?e.map(e=>ge(e,t)):ge(e,t)}const be=function(e){const t={personal:{placeholder:"API Token",label:"API Token",path:"/api-token"},regular:{placeholder:"Legacy Token",label:"Legacy Token",path:"/api/get_token"}};function s(s,r,n){const i=t[s],a=document.createElement("a");a.href=`https://${e}${i.path}`,a.target="_blank",a.style.color="#007bff",a.style.textDecoration="none",a.textContent="here",r.placeholder=i.placeholder,n.replaceChildren(`You can get the ${i.label} `,a)}function r(e,t){t.textContent=e,t.classList.add("show")}function n(e){e.classList.remove("show")}function i(e,t,s,i){s.addEventListener("click",async s=>{if(s.preventDefault(),n(i),!t.value.trim())return r(`${t.placeholder} is required`,i),void t.focus();const a=document.getElementById("token-type-switcher"),o=a?.querySelector(".token-type-option.active"),c=o?.dataset.value||"personal";await async function(e,t,s,n){try{s.classList.add("loading");const i=await fetch("/@api/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,tokenType:t}),redirect:"follow"}),a=i.url&&new URL(i.url,window.location.origin);if(!a||a.pathname.startsWith("/login")||a.pathname.startsWith("/@api/"))try{const e=await i.json();r(`Login failed: ${e?.error||"Unknown error occurred"}`,n)}catch(e){r("Login failed: Unable to parse response",n)}else window.location.href=i.url}catch(e){r("Login failed: Network error. Please check your connection.",n)}finally{s.classList.remove("loading")}}(t.value.trim(),c,e,i)}),t.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),s.click())}),t.addEventListener("input",()=>{n(i)})}function a(e){const t=e.firstChild;if(!t)return;const r=t.lastChild?.cloneNode(!0);if(!r)return;r.innerHTML="";const n=r.cloneNode(!0);n.innerText="OR",n.setAttribute("role","separator"),n.setAttribute("aria-label","Alternative login method");const a=r.cloneNode(!0),o=document.createElement("div"),c=document.createElement("style");c.textContent="\n.helper-login-wrapper {\n font-family: Arial, sans-serif;\n color: #222;\n padding: 8px;\n background-color: #f8f9fa;\n border-radius: 8px;\n border: 1px solid #ddd;\n width: 100%;\n max-width: 400px;\n margin: 0 auto;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n}\n\n.helper-login-wrapper .title {\n font-weight: bold;\n font-size: 18px;\n margin-bottom: 12px;\n text-align: center;\n}\n\n.helper-login-wrapper .control {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.helper-login-wrapper .control input {\n border: 1px solid #ddd;\n border-radius: 4px;\n width: 100%;\n box-sizing: border-box;\n text-align: center;\n height: 26px;\n padding: 0 8px;\n font-size: 14px;\n}\n\n.helper-login-wrapper .control input:focus {\n outline: none;\n border-color: #007bff;\n box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);\n}\n\n.helper-login-wrapper .control .caption {\n font-size: 12px;\n color: #666;\n text-align: center;\n}\n\n.helper-login-wrapper .footer {\n margin-top: 16px;\n text-align: center;\n}\n\n.helper-login-wrapper .footer .btn.submit {\n background-color: #007bff;\n color: white;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n width: 100%;\n font-size: 14px;\n transition: background-color 0.3s;\n height: 26px;\n font-weight: 500;\n}\n\n.helper-login-wrapper .footer .btn.submit:hover {\n background-color: #0056b3;\n}\n\n.helper-login-wrapper .footer .btn.submit:disabled {\n background-color: #6c757d;\n cursor: not-allowed;\n}\n\n.helper-login-wrapper .token-type-switcher {\n display: flex;\n border: 1px solid #ccc;\n border-radius: 4px;\n overflow: hidden;\n margin-bottom: 12px;\n width: 100%;\n}\n\n.helper-login-wrapper .token-type-option {\n padding: 4px 8px;\n cursor: pointer;\n background-color: #f8f9fa;\n color: #666;\n font-size: 12px;\n text-align: center;\n transition: background-color 0.2s, color 0.2s;\n border-right: 1px solid #ccc;\n flex: 1;\n user-select: none;\n}\n\n.helper-login-wrapper .token-type-option:last-child {\n border-right: none;\n}\n\n.helper-login-wrapper .token-type-option.active {\n background-color: #007bff;\n color: white;\n font-weight: bold;\n}\n\n.helper-login-wrapper .token-type-option:not(.active):hover {\n background-color: #e9ecef;\n}\n\n.helper-login-wrapper .error-message {\n color: #dc3545;\n font-size: 12px;\n text-align: center;\n margin-top: 8px;\n display: none;\n}\n\n.helper-login-wrapper .error-message.show {\n display: block;\n}\n\n.helper-login-wrapper .loading {\n opacity: 0.6;\n pointer-events: none;\n}\n",document.head.appendChild(c),o.innerHTML='\n<div class="helper-login-wrapper" role="form" aria-label="PP Dev Helper Login">\n <div class="title" role="heading" aria-level="2">PP Dev Helper</div>\n\n <div class="token-type-switcher" id="token-type-switcher" role="tablist" aria-label="Token type selection">\n <div class="token-type-option active" data-value="personal" role="tab" aria-selected="true" tabindex="0">\n API Token\n </div>\n <div class="token-type-option" data-value="regular" role="tab" aria-selected="false" tabindex="0">\n Legacy Token\n </div>\n </div>\n\n <div class="control">\n <input \n type="password" \n id="helper-token" \n placeholder="API Token"\n aria-label="Token input"\n aria-describedby="token-caption"\n >\n <span class="caption" id="token-caption"></span>\n </div>\n\n <div class="error-message" id="error-message" role="alert" aria-live="polite"></div>\n\n <div class="footer">\n <button id="helper-token-submit" class="btn submit" type="button">\n Token Login\n </button>\n </div>\n</div>',a.appendChild(o),t.appendChild(n),t.appendChild(a);const l=document.getElementById("token-type-switcher"),d=document.getElementById("helper-token"),u=document.getElementById("token-caption"),p=document.getElementById("helper-token-submit"),h=document.getElementById("error-message"),g=o.querySelector(".helper-login-wrapper");l&&d&&u&&p&&h&&g?(!function(e,t,r){const n=e.querySelectorAll(".token-type-option"),i=e=>{const i=e.dataset.value;n.forEach(e=>{e.classList.remove("active"),e.setAttribute("aria-selected","false"),e.setAttribute("tabindex","-1")}),e.classList.add("active"),e.setAttribute("aria-selected","true"),e.setAttribute("tabindex","0"),s(i,t,r)};n.forEach(e=>{e.addEventListener("click",e=>{const t=e.currentTarget;i(t)}),e.addEventListener("keydown",t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),i(e))})})}(l,d,u),i(g,d,p,h),s("personal",d,u)):console.error("Failed to find required form elements")}const o='#mi-react-root form:not([id]):has(input[name="login"]):has(input[name="password"])',c=new MutationObserver(e=>{for(const t of e)if("childList"===t.type){const e=document.querySelector(o);if(e){c.disconnect(),a(e);break}}});c.observe(document.body,{childList:!0,subtree:!0});const l=document.querySelector(o);l&&(c.disconnect(),a(l))};function ke(e){const{message:t,response:s}="object"==typeof e&&null!==e?e:{},r="number"==typeof s?.status?s.status:0,n=s?.data?.message;return"string"==typeof n&&n?{status:r,message:n}:"string"==typeof t&&t?{status:r,message:t}:{status:r,message:"string"==typeof e&&e?e:"Unknown error"}}function $e(e){const{status:t,message:s}=ke(e);switch(t){case 412:{const e=s.toLowerCase();return e.includes("session expired")||e.includes("session has expired")?{status:t,message:s,code:"SESSION_EXPIRED",userFriendlyMessage:"Your session has expired",suggestions:["Refresh your token in the portal","Re-authenticate with the portal","Check if your token has been revoked","Ensure your token has the correct permissions"]}:{status:t,message:s,code:"AUTH_FAILED",userFriendlyMessage:"Authentication failed",suggestions:["Verify your token is correct","Check token permissions","Ensure the token hasn't expired","Try generating a new token"]}}case 401:return{status:t,message:s,code:"UNAUTHORIZED",userFriendlyMessage:"Unauthorized access",suggestions:["Check if your token is valid","Verify you have the required permissions","Ensure the token hasn't been revoked","Try logging in again"]};case 403:return{status:t,message:s,code:"FORBIDDEN",userFriendlyMessage:"Access forbidden",suggestions:["Check your user permissions","Verify the portal page ID is correct","Ensure your token has the right scope","Contact your administrator"]};default:return{status:t,message:s,code:"UNKNOWN_ERROR",userFriendlyMessage:"An unexpected error occurred",suggestions:["Check your network connection","Verify the portal URL is correct","Try again in a few moments","Check the portal status"]}}}function xe(e){const{status:t}=ke(e);return 401===t||403===t||412===t}const Se=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ae=new Map,Te=new Map;const Ee=(e,t,s)=>{let r=Ae.get(e);if(!r){const t=/:\d+$/.test(e)?"":"(?::(?<port>\\d+))?";r=new RegExp(`(?<keep>!!)?(?<url>http(?<secure>s)?(?<slashes>:(?:\\\\)?/(?:\\\\)?/)${Se(e)}${t})`,"gi"),Ae.set(e,r)}return s.replace(r,(...e)=>{const{keep:s,url:r,secure:n,slashes:i,port:a}=e.at(-1);return s||a&&a!==(n?"443":"80")?r:`http${i}${t}`})},Ie=(e,t,s)=>{const r=new RegExp(`${e.replace(/\\*\//gi,"\\\\/")}`,"gi"),n=new RegExp(`${e}`,"gi"),i=s.replace(r,t);return i===s?i.replace(n,t):i},Pe=(e,t,s)=>{e.setHeader("location",t),e.statusCode=s,e.end()};function Le(e){return e.split("?")[0]}const je="[DEV PAGE. DO NOT DELETE]",Ne=new Map;class Re{#e;#t;#s=null;#r;#n;#i=!1;#a=null;#o=null;#c;#l;#d;#u;#p;internalPageName;appId;templateLess;assetsApi;pageApi;pageTemplateApi;pageVariableApi;logger;constructor(e,t){const{headers:s={},appId:r,templateLess:i=!0,disableSSLValidation:a=!1,v7Features:o=!1,personalAccessToken:c}=t||{};this.#e=s,this.#n=[],this.#r="",this.#c=o,this.#l=c,this.#d=!1,this.#u=Promise.resolve(!1);const l=`${e}:${a}`;if(Ne.has(l))this.#t=Ne.get(l);else{const t=new I.Agent({keepAlive:!1,...a?{rejectUnauthorized:!1}:{}});this.#t=T.create({baseURL:e,headers:s,timeout:3e4,maxRedirects:5,httpAgent:new E.Agent({keepAlive:!1}),httpsAgent:t}),Ne.set(l,this.#t)}this.appId=r,this.templateLess=i,this.assetsApi=new(o?ee:Q)(this.#t),this.pageApi=new de(this.#t),this.pageTemplateApi=new ue(this.#t),this.pageVariableApi=new pe(this.#t),this.logger=n.createLogger()}async isTemplateLoaded(){return this.#u}get isV710OrHigher(){return this.#d}get v7Features(){return this.#c}get pageId(){return this.appId}#h(e){const t=Object.assign({},e,{host:void 0,referer:void 0});return Object.keys(t).forEach(e=>void 0===t[e]&&delete t[e]),this.#e=t,!t.authorization&&this.#l&&(t.authorization=`Bearer ${this.#l}`),t}#g(){return this.#h(this.#e)}#f(e){return e.replace(/[.*+?^${}()|[\]\\\/]/g,"\\$&")}get personalAccessToken(){return this.#l}set personalAccessToken(e){this.#l=e}get localTemplateHTML(){return'<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>%%PAGE TITLE%%</title>\n <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />\n <meta name="theme-color" content="rgba(255, 255, 255, 1)" />\n <link rel="shortcut icon" type="image/x-icon" sizes="any" href="/img/favicon/favicon.ico" />\n <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon/favicon-16x16.png" />\n <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon/favicon-32x32.png" />\n <link rel="icon" type="image/png" sizes="48x48" href="/img/favicon/favicon-48x48.png" />\n <meta name="msapplication-config" content="/auth/browserconfig.xml" />\n <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon/apple-touch-icon.png" />\n <link rel="manifest" href="/auth/site.webmanifest" />\n <link rel="manifest" href="/auth/manifest.json" />\n <link rel="stylesheet" type="text/css" href="/auth/theme-vars.css" />\n <link rel="icon" type="image/svg+xml" href="/favicon.ico" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <script src="/js/libs/underscore-latest.min.js" charset="utf-8"><\/script>\n <script src="/js/jquery/jquery-latest.min.js" charset="utf-8"><\/script>\n <script src="/js/application/rating_component.js" charset="utf-8"><\/script>\n </head>\n <body>\n <div id="mi-react-root"></div>\n <script src="/auth/info.js"><\/script>\n <script src="/js/main.js" defer><\/script>\n <link rel="stylesheet" href="/css/main.css" />\n </body>\n </html>'}async getPageTemplate(e){if(await this.#u||this.#s||(this.#u=new Promise(e=>{this.#p=e})),this.#s)return Promise.resolve(this.#s);if(void 0===this.templateLess&&(this.templateLess=!1),this.#c){const t=await this.pageApi.get(this.appId,this.#h(e)).then(e=>(this.logger.info(n.colors.green("Page fetched")),e)).catch(async t=>{if(this.#p(!1),le(t))throw t;throw await this.pageApi.checkAuth(this.#h(e))?(this.logger.error(n.colors.red(`Error fetching page data: ${t.message}\n${t.stack}`)),new Error("The current user does not have access to this page. Check your configuration to ensure app.id is correct.")):t});return void 0!==t.template_id&&(this.#d=!0),this.internalPageName=t.internal_name,this.#s=this.localTemplateHTML,this.#s=this.#s.replace(/%%PAGE TITLE%%/g,t.name||"Local template"),this.logger.info(n.colors.green("Local page template fetched")),this.#p(!0),this.#s}let t=(await this.pageApi.getAll(this.#h(e)).then(e=>(this.logger.info(n.colors.green("Page list fetched")),e)).catch(async t=>{throw this.#p(!1),await this.pageApi.checkAuth(this.#h(e))?(this.logger.error(n.colors.red(`Error fetching page list: ${t.message}\n${t.stack}`)),new Error("Current user does not have access to page list")):t})).find(e=>e.name===je);return t||(this.logger.warn(n.colors.yellow("Creating dev page template...")),t=await this.pageApi.create({enabled:"Y",name:je,internal_name:"dev-page-template",visible_in_homepage:"Y"},this.#h(e)).then(e=>(this.logger.info(n.colors.green("Dev page created")),e)).catch(e=>{throw this.logger.error(n.colors.red(`Error creating dev page: ${e.message}`)),this.#p(!1),new Error(`Error when creating dev page.\n That can be caused by missing permissions or page with name "${je}" already exists`)})),await this.pageApi.getPageContent(t.internal_name,this.#h(e)).then(e=>(this.#s=e,e)).then(e=>(this.#p(!0),this.logger.info(n.colors.green("Page template fetched")),e)).catch(e=>{throw this.#p(!1),this.logger.error(n.colors.red(`Error fetching page template: ${e.message}`)),new Error("Error fetching page template")})}async getPageVariables(e,t){return void 0===this.appId&&(this.appId=e,this.templateLess=!1),this.#s=await this.getPageTemplate(t),await this.pageApi.get(e,this.#h(t)).then(e=>{const{tags:t="[]",name:s,template:r}=e;if(r&&t){const e=JSON.parse(t);return this.#n=e,this.#i=!0,this.#r=s,e}return this.#n=[],this.#i=!0,this.#r=s,[]}).catch(t=>{if(this.logger.error(n.colors.red(`Error fetching page variables: ${t.message}`)),404===t.response?.status)throw new Error(`Portal Page with id "${e}" not found on instance ${this.#t.getUri()}`);if(401===t.response?.status)throw this.logger.warn(`Unauthorized error: ${t}`),new Error(`Current user does not have access to page with id "${e}" on instance ${this.#t.getUri()}`);throw t})}async getLivePageVariables(e=this.#e){if(void 0===this.appId)throw new Error("Cannot fetch live page variables before the page ID is known");const t=this.appId,s=Date.now();this.logger.info(n.colors.cyan(`[page-variables] Fetching live variables for page ID ${t} (page_id lookup)`));const r=await this.pageVariableApi.getById(t,this.#h(e));return this.logger.info(n.colors.green(`[page-variables] Fetched ${r.length} live variable(s) for page ID ${t} in ${Date.now()-s}ms`)),r}async applyPageVariables(e,t=this.#e){if(void 0===this.appId)throw new Error("Cannot apply page variables before the page ID is known");const s=this.appId,r=Date.now();this.logger.info(n.colors.cyan(`[page-variables] Applying ${e.length} variable(s) to page ID ${s} (page_id lookup)`)),await this.pageVariableApi.updateById(s,e,this.#h(t)),this.logger.info(n.colors.green(`[page-variables] Applied variables to page ID ${s} in ${Date.now()-r}ms`))}async listPages(e=this.#e){return this.pageApi.getAll(this.#h(e))}async getPageVariablesFor(e,t=this.#e){return this.pageVariableApi.getById(e,this.#h(t))}get localPageVariables(){return this.templateLess||!this.#i?null:this.#n.map(({name:e,value:t})=>({name:e,value:t}))}get isTemplateLess(){return!!this.templateLess}async reloadPageVariables(e=this.#e){return this.templateLess||void 0===this.appId?null:this.getPageVariables(this.appId,e)}async getPageInfo(e,t){void 0===this.appId&&(this.appId=e);const s=this.#h(t),r=this.appId;try{return this.#c?await this.#m(r,s):await this.#y(r,s)}catch(e){this.#w(e,r)}}async#m(e,t){const s=await this.pageApi.get(e,t);return this.logger.info(n.colors.green("Page fetched")),void 0!==s.template_id&&(this.#d=!0),this.internalPageName=s.internal_name,s}async#y(e,t){return await this.pageApi.get(e,t)}#w(e,t){if(le(e))throw e;if(this.#c&&e.message?.includes("access"))throw new Error("The current user does not have access to this page. Check your configuration to ensure app.id is correct.");if(404===e.response?.status)throw new Error(`Portal Page with id "${t}" not found on instance ${this.#t.getUri()}`);throw 401===e.response?.status&&this.logger.error(n.colors.red(`Current user does not have access to page with id "${t}" on instance ${this.#t.getUri()}`)),e}buildPage(e,t=!1){let s="string"==typeof e?e:e.toString("utf-8");for(const{regExp:e,value:t}of this.#v())s=s.replace(e,()=>t);if(t){return new(r.getJSDOM())(s).serialize()}const{before:n,after:i}=this.#b();return n+s+i}#v(){return this.#a?.vars!==this.#n&&(this.#a={vars:this.#n,replacements:this.#n.map(({name:e,value:t})=>({regExp:new RegExp(`\\[${this.#f(e)}\\]`,"g"),value:t}))}),this.#a.replacements}#b(){const e=this.#s,t=this.#r;if(this.#o?.template===e&&this.#o.title===t)return this.#o;const s=new(r.getJSDOM())(e),{document:n}=s.window,i="%%PLACEHOLDER%%",a=n.createElement("div");a.innerHTML=i;const o=n.querySelector(".main-side");if(o){const e=o.querySelectorAll("script");e.length?o.insertBefore(a,e.item(e.length-1)):o.append(a)}else{const e=n.createElement("div");e.append(a),n.body.append(e)}const c=n.querySelector("head"),l=c.querySelector("title");if(l)l.text=t;else{const e=n.createElement("title");e.textContent=t,c.appendChild(e)}const d=s.serialize(),u=new RegExp(`<div>\\s*${i}\\s*<\\/div>`,"i").exec(d);return this.#o={template:e,title:t,before:d.slice(0,u.index),after:d.slice(u.index+u[0].length)},this.#o}async getAssets(){if(this.appId){const e=this.#g();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.#g();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 r=await this.pageTemplateApi.get(s.template_id,t);return await this.assetsApi.uploadTemplateAssets(r.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.#g();return await this.get("/api/user",t,!0),{isValid:!0}}catch(e){const t=$e(e);return{isValid:!1,error:t.userFriendlyMessage,code:t.code}}}async get(e,t,s=!1,r={}){const i=s?t:Object.assign({},this.#h(this.#e),t);try{return await this.#t.get(e,{headers:i})}catch(e){if("UNKNOWN_ERROR"!==$e(e).code){const t=$e(e);throw r.quiet||(this.logger.error(n.colors.red(`API request failed: ${t.userFriendlyMessage}`)),function(e,t,s){const r=$e(t),i=`[${s}] `;e.error(n.colors.red(`${i}${r.userFriendlyMessage}`)),e.error(n.colors.red(`Status: ${r.status} (${r.code})`)),e.error(n.colors.red(`Details: ${r.message}`)),r.suggestions.length>0&&(e.info(n.colors.yellow("Suggestions:")),r.suggestions.forEach((t,s)=>{e.info(n.colors.yellow(` ${s+1}. ${t}`))}))}(this.logger,e,"API Request")),e.tokenErrorInfo=t,e}throw e}}}function Ce(e,t){const s=(e=(e=e.startsWith("/")?e:`/${e}`).endsWith("/")?e:`${e}/`).endsWith("/")?e.slice(0,-1):e,r=n.createLogger();return(a,o,c)=>{const l=new i.URL(a.url??"","http://localhost"),{pathname:d,search:u}=l,p=["/",s];if(t&&(p.push(`${n.PATH_TEMPLATE_PREFIX}/${t}`),p.push(`${n.PATH_TEMPLATE_LOCAL_PREFIX}/${t}`)),p.includes(d)){const t=`${e}${u}`;return r.info(n.colors.yellow(`Redirecting to: ${t}`)),Pe(o,t,302)}c()}}const Oe=String.raw`[a-z](?:[a-z0-9\-]*[a-z0-9])?`,Me=new RegExp(`^(?:${Oe})$`),Be=".localhost";function Fe(e){return e?e.length>32?"The name must be at most 32 characters long":Me.test(e)?void 0:'The name may contain only lowercase latin letters, digits and "-", must start with a letter and must not end with "-"':"The name is required"}function De(e){if(!e)return;const t=e.toLowerCase().replace(/:\d+$/,"");if(!t.endsWith(Be))return;const s=t.slice(0,-10);return s&&!s.includes(".")?s:void 0}function _e(e,t){const s=/:(\d+)$/.exec(e.headers.host??"")?.[1];return`${he(e)?"https":"http"}://${t?`${t}.`:""}localhost${s?`:${s}`:""}`}const Ue=new class{#k=new Map;#$=new Set;#x=new Set;#S=!1;#A=new Set;#T;#E=new Map;#I=new WeakMap;#P;useContext(e){void 0!==this.#P&&this.#P!==e&&this.clear(),this.#P=e}get context(){return this.#P}list(){return[...this.#k.values()]}get(e){return this.#k.get(e)}add(e){const t=Fe(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.#L(),s}replace(e,t){if(!this.#k.has(e))throw new Error(`There is no user named "${e}"`);const s=Fe(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 r=this.#T===e,n=[...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.#L(),s}finally{this.#S=!1}for(const s of t.name===e?n:[...n,e])this.#E.set(s,i.name);return r&&(this.#T=i.name),this.#L(),i}#L(){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.#L(),!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=De(e.headers.host);let s;if(void 0===t){const t="localhost"===(e.headers.host??"").toLowerCase().replace(/:\d+$/,"")?this.defaultUser:void 0;s={key:t?.name??"",user:t}}else{const e=this.#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 He(e=Ue){return(t,s,r)=>{const n=e.resolve(t),i=De(t.headers.host)??"";if(n?.user&&i&&n.key!==i&&function(e){if("GET"!==e.method&&"HEAD"!==e.method)return!1;const t=e.headers["sec-fetch-mode"];return"string"==typeof t?"navigate"===t:String(e.headers.accept??"").includes("text/html")}(t)){const e=t.originalUrl??t.url??"/";return s.statusCode=302,s.setHeader("Location",`${_e(t,n.key)}${e}`),s.setHeader("Cache-Control","no-store"),void s.end()}n?r():(s.statusCode=404,s.setHeader("Content-Type","text/plain; charset=utf-8"),s.setHeader("Cache-Control","no-store"),s.end(`pp-dev has no user named "${i}". Open users from the pp-dev dev panel on the main host.`))}}const Ve=/(?:^|\/\/[^/]+)\/(?:login|auth\/saml\/login)(?:[/?#]|$)/i;function qe(e){return(e??"").split(";").map(e=>e.trim()).filter(e=>e&&e.split("=",1)[0].trim()!==fe)}function ze({statusCode:e=200,headers:t}){return 401===e||412===e||e>=300&&e<400&&Ve.test(String(t.location??""))}class We{#k;#j;#N=n.createLogger();#R=new WeakMap;#C=new WeakMap;#O=new WeakMap;#M=new WeakMap;constructor(e,t){this.#k=e,this.#j=t}isLeftBehindRequest(e,t,s){const r=De(t.headers.host)===e.name?ye(t.headers.cookie,fe):s;return void 0!==r&&this.#B(e,r)}observe(e,t,s,r){if("session"!==e.kind||this.#k.get(e.name)!==e)return;const n=De(t.headers.host)===e.name,i=n?ye(t.headers.cookie,fe):r,a=we(s.headers["set-cookie"],fe),o=this.#O.get(e);let c,l,d=n;return a&&a!==i?(c=a,l=i):n&&i!==e.session&&!ze(s)?c=i:o&&Date.now()>=o.retryAt&&(c=o.session,d=o.ownHost),c&&c===o?.session&&void 0===l&&(l=o.replaced),"active"===e.state&&ze(s)&&i===e.session&&this.#F(e,`MI turned away ${t.method} ${t.url}`),c&&c!==e.session&&c!==this.#R.get(e)&&c!==this.#C.get(e)&&!this.#B(e,c)?this.#D(e,c,l,d):void 0}async#D(e,t,s,r){let i;this.#R.set(e,t);try{i=await this.#j(t)}catch(i){return this.#R.get(e)===t&&(this.#R.delete(e),this.#O.set(e,{session:t,replaced:s,ownHost:r,retryAt:Date.now()+5e3})),void this.#N.warn(n.colors.yellow(`Could not check the MI session of user ${e.name}: ${String(i)}`))}if(this.#R.get(e)===t&&this.#k.get(e.name)===e)if(this.#R.delete(e),this.#O.get(e)?.session===t&&this.#O.delete(e),i){if(this.#B(e,t)||void 0!==s&&this.#B(e,s))return;const a="active"===e.state;r&&(this.#_(e),void 0!==s&&s!==t&&this.#_(e,s)),this.#O.delete(e),Object.assign(e,{state:"active",session:t,miUser:i}),this.#C.delete(e),this.#k.sessionChanged(e),a||this.#N.info(`${n.colors.blue("User")} ${n.colors.yellow(e.name)} ${n.colors.blue("logged in")} (MI user ${i.id}${i.username?`, ${i.username}`:""})`)}else this.#C.set(e,t),"active"===e.state&&s===e.session&&this.#F(e,"MI started a guest session")}#B(e,t){return"active"===e.state&&Boolean(this.#M.get(e)?.has(t))}#_(e,t=e.session){if(!t)return;const s=this.#M.get(e)??new Set;s.add(t),s.size>20&&s.delete(s.values().next().value),this.#M.set(e,s)}#F(e,t){this.#_(e),e.state="expired",e.session=void 0,this.#R.delete(e),this.#O.delete(e),this.#k.sessionChanged(e),this.#k.defaultUser===e&&this.#k.setDefaultUser(void 0),this.#N.warn(`${n.colors.yellow(`The MI session of user ${e.name} ended`)} (${t}). Log in again on its host.`)}}async function Je(e,t){try{const s=(await e.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",...t},!0,{quiet:!0})).data;if("object"!=typeof s||null===s)throw new Error(`${ne}.${ie}`);const r=s.user;return"number"==typeof r?.user_id?{miUser:{id:r.user_id,username:"string"==typeof r.username?r.username:""}}:{miUser:void 0}}catch(e){if(xe(e))return{miUser:void 0,refused:$e(e).userFriendlyMessage};throw e}}async function Ge(e,t){try{const s=await Je(e,{Authorization:`Bearer ${t}`});return s.miUser?{ok:!0,miUser:s.miUser}:{ok:!1,rejected:!0,message:s.refused?`The API token was rejected: ${s.refused}`:"The API token is expired or invalid"}}catch(e){return{ok:!1,rejected:!1,message:`Could not check the API token with MI: ${$e(e).userFriendlyMessage}`}}}const Ke=/^(https?:\/\/)([^/]+)(\/.*)?$/i,Xe="X-PP-Proxy";const Ze=/^\/login(?:\/|$)/i,Ye="/auth/saml/login";const Qe=/^\/auth\/(?:index\/)?logout(?:[/?#]|$)/i;const et=new WeakMap,tt=new WeakMap;const st=[/^text\//,/^application\/(?:[\w.-]+\+)?(?:json|xml)$/,/^application\/(?:x-)?(?:java|ecma)script$/,/^[\w.-]+\/[\w.-]+\+(?:json|xml)$/];function rt(e){const t=e.split(";",1)[0].trim().toLowerCase();return st.some(e=>e.test(t))}const nt=/[\w.:/\\!-]/;function it(e){const t=e["content-encoding"];if("string"==typeof t&&t.trim()&&"identity"!==t.trim())return!1;const s=e["content-type"];return"string"==typeof s&&rt(s)}function at(e){return async(t,s,r)=>{const n=e&&it(t.headers);r.statusCode=t.statusCode??r.statusCode,t.statusMessage&&(r.statusMessage=t.statusMessage),r.setHeader(Xe,1);for(const[e,s]of Object.entries(t.headers))void 0!==s&&(n&&"content-length"===e.toLowerCase()||r.setHeader(e,s));if(!n)return void t.pipe(r);const i=new o.StringDecoder("utf8");let a="",c=!1;const l=s=>{if(!s)return;r.write(e(Buffer.from(s,"utf8"),"utf8"))||c||(c=!0,t.pause(),r.once("drain",()=>{c=!1,t.resume()}))};t.on("data",e=>{a+=i.write(e);const t=a.lastIndexOf("\n");if(-1!==t&&(l(a.slice(0,t+1)),a=a.slice(t+1)),a.length>=65536){const e=function(e){for(let t=e.length-1;t>=0;t-=1)if(!nt.test(e[t]))return t;return-1}(a)+1||a.length;l(a.slice(0,e)),a=a.slice(e)}}),t.on("end",()=>{l(a+i.end()),a="",r.end()}),t.on("error",()=>{r.end()})}}function ot(e){const{rewritePath:t=/^\/(?!p[tl]).*/i,baseURL:s="",disableSSLValidation:r=!1,miAPI:o,templateName:c,users:l=Ue}=e;if(!s)throw new Error("Base url is required");const d=function(e){try{return new URL(e).host}catch{return e.replace(Ke,"$2")}}(s),u=s.replace(Ke,"$1$2"),p=import("file-type"),h=n.createLogger(),g=e.sessionUsers??new We(l,function(e){return async t=>(await Je(e,{Cookie:`${fe}=${t}`})).miUser}(o));return a.createProxyMiddleware({selfHandleResponse:!0,pathFilter:(s,r)=>!(e.proxyIgnore||[]).some(e=>"string"==typeof e?s.startsWith(e):"function"!=typeof e.test||e.test(s))&&("string"==typeof t?s.startsWith(t):Array.isArray(t)?t.some(e=>s.startsWith(e)):"function"==typeof t.test&&t.test(s)),target:s,changeOrigin:!0,logger:{info:()=>{},warn:()=>{},error:()=>{}},secure:!r,headers:{host:d,origin:u},on:{proxyReq(e,t,r){const a=t.headers.host,d=e.getHeader("referer");a&&d&&"string"==typeof d&&e.setHeader("referer",d.replace(function(e){let t=Te.get(e);return t||(t=new RegExp(`^https?://${Se(e)}(?=[/?#]|$)`,"i"),Te.set(e,t)),t}(a),s));const u=l.resolve(t);let p;u?.user?p=u.user.token:u&&(p=o.personalAccessToken),p?(e.setHeader("Authorization",`Bearer ${p}`),et.set(t,p)):"session"===u?.user?.kind&&e.removeHeader("Authorization"),u?.user&&e.removeHeader("Token");const g="session"===u?.user?.kind?u.user:void 0;let f;if(g&&De(t.headers.host)!==g.name){f=g.session;const s=f?(m=t.headers.cookie,y=f,[...qe(m),`${fe}=${y}`].join("; ")):function(e){const t=qe(e);return t.length?t.join("; "):void 0}(t.headers.cookie);s?e.setHeader("cookie",s):e.removeHeader("cookie")}var m,y;tt.set(t,{user:u?.user,sentSession:f}),e.removeHeader("if-none-match"),e.removeHeader("if-modified-since");const w=t.url??"/",v=function(e,t,s,r){if(!t||!s||!r||s===r)return e;try{const t=new i.URL(e,"http://localhost"),n=t.pathname.match(/^\/data\/page\/([^/]+)(\/.*)?$/);if(!n)return e;let a;try{a=decodeURIComponent(n[1])}catch{a=n[1]}if(a!==s)return e;return`/data/page/${r}${n[2]??""}`+t.search+t.hash}catch{return e}}(w,o.v7Features,c,o.internalPageName);v!==w&&(t.url=v,e.path=v,console.info(`${n.colors.cyan("Rewrites data page to correct internal page name")}: ${n.colors.yellow(w)} ${n.colors.blue("→")} ${n.colors.green(v)}`)),h.info(`${n.colors.blue("Proxies request:")} ${n.colors.green(t.method)} ${t.url} -> ${n.colors.green(e.method)} ${e.protocol}//${e.host}${e.path}${u?.user?` ${n.colors.blue("as")} ${n.colors.yellow(u.user.name)}`:""}`);const{socket:b}=t,k=()=>{setTimeout(()=>{e.destroyed||e.destroy()},200)};return b.once("close",k),e.once("close",()=>b.off("close",k)),e},proxyRes:(e,t,s)=>{s.setHeader(Xe,1),e.headers["set-cookie"]&&(e.headers["set-cookie"]=ve(e.headers["set-cookie"],he(t))),e.headers.location&&(e.headers.location=function(e,t,s){const r=s.headers.host;let n;try{n=new URL(e)}catch{return e}return r&&/^https?:$/.test(n.protocol)&&n.host===t.toLowerCase()?e.replace(/^https?:\/\/[^/?#]*/i,`${he(s)?"https":"http"}://${r}`):e}(e.headers.location,d,t));const r=function(e,t){if(!Qe.test(e.url??""))return;const s=De(e.headers.host);return void 0===s?void 0:t.get(s)}(t,l),i=tt.get(t);if(r){e.resume();const a={"cache-control":"no-store"};i?.user===r&&(l.remove(r.name),h.info(`${n.colors.blue("Logged out user")} ${n.colors.yellow(r.name)}, back to the main host`),e.headers["set-cookie"]&&(a["set-cookie"]=e.headers["set-cookie"]));const o=t.headers["sec-fetch-mode"];return o&&"navigate"!==o?s.writeHead(204,a):s.writeHead(302,{...a,location:`${_e(t)}/`}),void s.end()}const o=i?.user;let c=!0;if(o&&l.get(o.name)!==o)c=!1;else if(o){let s=!1;"session"===o.kind&&(s=g.isLeftBehindRequest(o,t,i?.sentSession),g.observe(o,t,e,i?.sentSession)),c=De(t.headers.host)===o.name&&!s}if(!c){const t=function(e){const t=(e??[]).filter(e=>void 0===we(e,fe));return t.length?t:void 0}(e.headers["set-cookie"]);t?e.headers["set-cookie"]=t:delete e.headers["set-cookie"]}e.headers["cache-control"]="no-store",delete e.headers.expires,delete e.headers.pragma;const u=(e,s)=>Buffer.from(Ie(Ye,"/login",Ee(d,t.headers.host??"",e.toString(s))),s);if(e.headers["content-type"]?.includes("text/event-stream")||e.headers["transfer-encoding"]?.includes("chunked")&&"no"===e.headers["x-accel-buffering"])return h.info(`${n.colors.blue("Start streaming for request:")} ${n.colors.green(t.method)} ${t.url}`),at(u)(e,t,s);const f=function(e){const t=e["content-type"];if("string"==typeof t&&t.trim()&&!rt(t))return"pipe";const s=Number(e["content-length"]);return Number.isFinite(s)&&s>=10485760&&it(e)&&!function(e){const t="string"==typeof e?e.split(";",1)[0].trim().toLowerCase():"";return"text/html"===t||"application/xhtml+xml"===t}(t)?"stream":"buffer"}(e.headers);if("stream"===f&&(e.headers["x-accel-buffering"]="no"),"buffer"!==f)return at("stream"===f?u:void 0)(e,t,s);const m=a.responseInterceptor(async(e,t,s,r)=>{r.setHeader(Xe,1);if(await(await p).fileTypeFromBuffer(e))return e;{let t=e.toString("utf8");try{const e=new URL(s.url??"",`http://${d}`);if(e.searchParams&&e.searchParams.has("proxyRedirect")){const e=function(){const e="pp-dev::redirectCount",t="pp-dev::lastRedirect";let s=+(localStorage.getItem(e)??0);localStorage.getItem(t);Number.isNaN(s)&&(s=0);let r=window.location.href;const n=function(){const i=new URLSearchParams(window.location.search);if(!i.has("proxyRedirect"))return console.debug("No proxyRedirect param. Cleaning up."),void localStorage.removeItem(e);r!==window.location.href?(r=window.location.href,setTimeout(n,s<3?3e3:5e3)):window.location.href=i.get("proxyRedirect"),localStorage.setItem(e,""+ ++s),localStorage.setItem(t,(new Date).toISOString())};setTimeout(n,3e3)};t+=`<script>(${e.toString()})()<\/script>`}const r=t.slice(0,100);Ze.test(e.pathname)&&(r.includes("<html")||r.includes("<body")||r.includes("<head")||r.includes("html>"))&&!De(s.headers.host)&&(t+=`<script>(${be.toString()})(${n=d,JSON.stringify(n).replace(/</g,"\\u003c")})<\/script>`)}catch{}const r=s.headers.host??"";return Ie(Ye,"/login",Ee(d,r,t))}var n});return m(e,t,s)},error(e,t,s){!function(e,t,s,r){const n=`Proxy error: "${e.message}" when trying to "${t.method} ${t.url}"`;if(r(`${n}\n\n${e.stack??""}`),"function"!=typeof s.writeHead)return void s.destroy();const i=s;i.writableEnded||i.destroyed||(i.headersSent?i.destroy():(i.writeHead(502,{"Content-Type":"text/plain; charset=utf-8"}),i.end(n)))}(e,t,s,e=>h.error(e))}}})}const ct=/\.(?:[a-z0-9]+)$/i,lt=6e5,dt=104857600,ut=1e3,pt=10485760;const ht=new class{items=new Map;totalSize=0;maxSize;maxItems;constructor(e,t){this.maxSize=e,this.maxItems=t}get(e){const t=this.items.get(e);return t?t.expiresAt<=Date.now()?(this.del(e),null):t.value:null}put(e,t,s=lt){return this.del(e),this.items.set(e,{value:t,expiresAt:Date.now()+s}),this.totalSize+=t.size,this.cleanup(),t}del(e){const t=this.items.get(e);return!!t&&(this.totalSize-=t.value.size,this.items.delete(e))}clear(){this.items.clear(),this.totalSize=0}keys(){return this.purgeExpired(),[...this.items.keys()]}getTotalSize(){return this.totalSize}getItemCount(){return this.keys().length}purgeExpired(){const e=Date.now();for(const[t,s]of this.items)s.expiresAt<=e&&this.del(t)}cleanup(){for(this.purgeExpired();this.items.size>0&&(this.items.size>this.maxItems||this.totalSize>this.maxSize);)this.del(this.items.keys().next().value)}}(dt,ut),gt=new Set,ft=new Map;function mt(e){ht.clear(),ft.clear(),gt.forEach(e=>e()),n.createLogger().info(n.colors.blue(`Proxy cache cleared: ${e}`))}const yt=new WeakSet;function wt(e,t){return t?e.startsWith(`@${t}@`):!e.startsWith("@")}function vt(e,t){if(e){for(const t of ht.keys())wt(t,e)&&ht.del(t);ft.delete(e),n.createLogger().info(n.colors.blue(`Proxy cache cleared for ${e}: ${t}`))}else mt(t)}function bt(e,t,s){const r=function(e){return et.get(e)}(e);if(void 0!==r){const e=ft.get(s),t=void 0!==e&&r!==e;return ft.set(s,r),t?"personal access token changed":void 0}const n=we(t.getHeader("set-cookie"),fe);return void 0!==n&&n!==ye(e.headers.cookie,fe)?"MI session changed":void 0}function kt(e){if(0===e.length)return Buffer.alloc(0);if(1===e.length)return e[0];const t=e.reduce((e,t)=>Buffer.byteLength(t)+e,0);return Buffer.concat(e,t)}function $t(e){const{devServer:t,ttl:s=lt,maxSize:r=dt,maxItems:i=ut,users:a=Ue}=e,o=n.createLogger();return r===dt&&i===ut||(ht.maxSize=r,ht.maxItems=i),t&&(t.cache=ht),yt.has(a)||(yt.add(a),a.onRemove(e=>vt(e.name,"user removed")),a.onSessionChange(e=>vt(e.name,"MI session changed or ended"))),(e,t,r)=>{const i=a.resolve(e);if(!i)return r();t.once("finish",()=>{const s=t.hasHeader(Xe)?bt(e,t,i.key):void 0;s&&vt(i.key,`${s} (${e.method} ${Le(e.url??"")})`)});const c=i.user?.session,l=e.originalUrl||e.url||"",d="GET"===e.method?function(e,t,s){const r=e.split("?")[0];return ct.test(r)?r.includes("/auth/info.js")?"":t?`@${t}@${s}:${e}`:`${s}:${e}`:""}(l,i.key,e.headers.host??""):"";if(!d||!function(e,t){const{user:s}=t;return"session"!==s?.kind||!!s.session&&(De(e.headers.host)!==s.name||ye(e.headers.cookie,fe)===s.session)}(e,i))return r();const u=ht.get(d);if(u)return o.info(`${n.colors.blue("Proxies request:")} ${n.colors.green(e.method)} ${l} -> ${n.colors.blue("Cache")} ${d}`),function(e,t){try{for(const[s,r]of Object.entries(t))null!=r&&e.setHeader(s,r)}catch(e){n.createLogger().warn(`Failed to set some response headers: ${e instanceof Error?e.message:String(e)}`)}}(t,u.headers),t.setHeader("X-PP-Cache","hit"),t.write(u.content),void t.end();const p=t.end,h=t.write,g=[];let f=0,m="undecided";const y=(e,t)=>null==e?null:"string"==typeof e?Buffer.from(e,t||"utf8"):e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf8"),w=()=>{m="pass";for(const e of g.splice(0))h.call(t,e)},v=()=>{"undecided"===m&&(t.hasHeader(Xe)?!function(e){if(200!==e.statusCode)return!1;if(/^text\/event-stream/i.test(String(e.getHeader("content-type")??"")))return!1;if("no"===String(e.getHeader("x-accel-buffering")??"").toLowerCase())return!1;const t=Number(e.getHeader("content-length"));return!(Number.isFinite(t)&&t>=pt)}(t)?w():m="buffer":m="pass")};t.write=function(e,t,s){if(v(),"pass"===m)return h.call(this,e,t,s);const r="function"==typeof t?t:s,n=y(e,"string"==typeof t?t:void 0);return n&&(g.push(n),f+=n.length),f>pt&&w(),r&&process.nextTick(r),!0},t.end=function(e,r,l){if(v(),"pass"===m)return p.call(this,e,r,l);"function"==typeof e?(l=e,e=void 0):"function"==typeof r&&(l=r,r=void 0);const u=y(e,"string"==typeof r?r:void 0);let h;u&&g.push(u);try{h=kt(g);const e=Buffer.byteLength(h);if(200===t.statusCode&&e>0&&e<pt&&function(e,t,s){return!e.user||s.get(e.key)===e.user&&e.user.session===t}(i,c,a)){const{"set-cookie":r,...i}=t.getHeaders(),a={headers:i,content:h,timestamp:Date.now(),size:e};ht.put(d,a,s),o.info(`${n.colors.blue("[Cached]")} ${d} (${(e/1024).toFixed(1)}KB)`)}}catch(e){o.error(`Failed to cache response for ${d}: ${e}`),h=kt(g)}return p.call(this,h,l)},r()}}const xt=new WeakMap;let St=0;function At(e){let t=xt.get(e);return t||(t=new Map,xt.set(e,t)),t}function Tt(e,t){const s=At(e),r=s.get(t);return r?r.epoch!==St||Date.now()-r.timestamp>18e4?(s.delete(t),null):r.data:null}function Et(e,t,s){At(e).set(t,{timestamp:Date.now(),epoch:St,data:s})}var It;It=()=>{St+=1},gt.add(It);let Pt=!1;function Lt(e){Pt||(Pt=!0,e.info(n.colors.blue("Clearing proxy cache after successful login")),ht.clear())}function jt(){Pt=!1,n.authProvider.reset()}const Nt="/home?proxyRedirect=",Rt=`${Nt}${encodeURIComponent("/")}`;function Ct(e){const t=e.headers??{},s=Boolean(De(e.headers?.host));if(!s&&!Ue.resolve(e)?.user)return t;const{cookie:r,authorization:n,token:i,...a}=t;return s||void 0===r?a:{...a,cookie:r}}function Ot(e,t,s){const{templateLess:r=!1,miHudLess:i=!1,appId:a,base:o,appBase:c}=s,l=n.createLogger();if(r&&i&&void 0===a)throw new Error("Custom App ID is required when both templateLess and miHudLess are true");return async(s,d,u)=>{try{const p=!(r&&i),h=Le(s.url??""),g=e.test(h),f=!g&&!h.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)}(h,c)&&function(e){const t=e.headers["sec-fetch-dest"];if("string"==typeof t)return"document"===t;const s=e.headers.accept;return"string"==typeof s&&s.includes("text/html")}(s),m=n.authProvider.getState();if(!m.isAuthenticated&&!m.isRedirected&&s.url?.startsWith("/home")&&!s.url?.startsWith(Nt)){let e;l.info(n.colors.blue("Trying to authenticate and redirect to base"));const c=t=>{e=t};try{if(p?await Bt(t,{templateLess:r,miHudLess:i,appId:a,redirectUrl:Rt},s,d,c,l):await Mt(t,{templateLess:r,miHudLess:i,appId:a,redirectUrl:Rt},s,d,c,l),d.headersSent||d.writableEnded)return;return e?u(e):(n.authProvider.setRedirected(!0),l.info(n.colors.blue("Successfully authenticated. Redirecting to base")),Pe(d,o??"/",302))}catch(e){if(d.headersSent||d.writableEnded)return;return u()}}if(!g&&!f)return u();if(!p){return await Mt(t,{templateLess:r,miHudLess:i,appId:a,redirectUrl:Rt},s,d,u,l)}return await Bt(t,{templateLess:r,miHudLess:i,appId:a,redirectUrl:Rt},s,d,u,l)}catch(e){return l.error(n.colors.red(`Unexpected error in load-pp-data middleware: ${e instanceof Error?e.message:String(e)}`)),jt(),u(e)}}}async function Mt(e,t,s,r,i,a){const{appId:o,redirectOnAuthFailure:c,redirectUrl:l}=t;if(void 0===o){const e=new Error("Custom App ID is required for page info only mode");return a.error(n.colors.red(e.message)),i(e)}const d=Ct(s);a.info(n.colors.green("Start loading page info"));try{const t=`pageInfo:${o}`;return Tt(e,t)?(a.info(n.colors.green("Page info loaded from cache")),i()):(await e.getPageInfo(o,d),Lt(a),Et(e,t,{success:!0}),n.authProvider.updateState({isAuthenticated:!0}),a.info(n.colors.green("Page info loaded successfully")),i())}catch(e){return jt(),Ft(e,c??!0,l||Rt,r,i,a,"Page info")}}async function Bt(e,t,s,r,i,a){const{templateLess:o,appId:c,redirectOnAuthFailure:l,redirectUrl:d}=t,u=Ct(s);a.info(n.colors.green("Start loading page data"));try{const t=`pageData:${o}:${c}`;if(Tt(e,t))return a.info(n.colors.green("Page data loaded from cache")),i();const s=o||void 0===c?e.getPageTemplate(u):e.getPageVariables(c,u);return await s,Lt(a),Et(e,t,{success:!0}),a.info(n.colors.green("Page data loaded successfully")),i()}catch(e){return jt(),Ft(e,l??!0,d||Rt,r,i,a,"Page data")}}function Ft(e,t,s,r,i,a,o){if(function(e){return null!==e&&"object"==typeof e&&xe(e)}(e)&&(a.info(n.colors.red(`${o} loading failed. Not authorized`)),t)){const e=`${s}`;return a.info(n.colors.yellow(`Redirecting to: ${e}`)),Pe(r,e,302)}const c=e instanceof Error?e.message:String(e);return a.info(n.colors.red(`${o} loading failed. Error: ${c}`)),i(e)}function Dt(e){return"string"==typeof e?e:void 0}function _t(e,t){return"string"==typeof e?Buffer.from(e,t):e instanceof Uint8Array?Buffer.from(e):null}function Ut(e,t,s={}){return async(r,i,a)=>{if(await e(r.url??"",r,i)){const e=n.createLogger();"GET"!==r.method&&"HEAD"!==r.method||!(r.headers.accept??"").includes("text/html")||delete r.headers["if-none-match"];const o=i.end;if("HEAD"===r.method)return i.end=function(e,t,r){const n=[e,t,r].find(e=>"function"==typeof e),a=i.getHeader("content-type"),c=!s.contentType||s.contentType(void 0===a?"":String(a));return!i.headersSent&&c&&i.removeHeader("content-length"),o.call(this,n),this},void a();e.info(`Rewrite response for ${r.url}`);const l=[],d=i.write,u=i.writeHead,p=i.flushHeaders;let h=null,g=!1;const f=()=>{g=!0,h&&!i.headersSent&&u.apply(i,h),h=null;for(const e of l.splice(0))d.call(i,e)},m=(e=!1)=>{if(g)return!0;if(!s.contentType)return!1;const t=i.getHeader("content-type");return!(void 0===t&&!e)&&(!s.contentType(void 0===t?"":String(t))&&(f(),!0))};i.flushHeaders=function(){m()&&p.call(this)},i.writeHead=function(e,...t){if(g)return u.call(this,e,...t);const s="string"==typeof t[0]?t[0]:void 0;return function(e,t){if(Array.isArray(t)){const s=new Map;for(let e=0;e+1<t.length;e+=2){const r=String(t[e]),n=s.get(r.toLowerCase())??{name:r,values:[]};n.values.push(String(t[e+1])),s.set(r.toLowerCase(),n)}for(const{name:t,values:r}of s.values())e.setHeader(t,1===r.length?r[0]:r);return}if(t&&"object"==typeof t)for(const[s,r]of Object.entries(t))void 0!==r&&e.setHeader(s,r)}(this,void 0===s?t[0]:t[1]),this.statusCode=e,h=void 0===s?[e]:[e,s],m(),this},i.write=function(e,t,s){if(m())return d.call(this,e,t,s);const r=_t(e,Dt(t));r&&l.push(r);const n="function"==typeof t?t:s;return"function"==typeof n&&process.nextTick(n),!0},i.end=function(s,n,a){if(m(!0))return o.call(this,s,n,a);"function"==typeof s&&(a=s,s=void 0);const d=_t(s,Dt(n));d&&l.push(d);const p="function"==typeof n?n:a,g=i.getHeader("content-encoding"),f=z(Buffer.concat(l),g),y=function(e,t){switch(t){case"gzip":return c.gzipSync(e);case"br":return c.brotliCompressSync(e);case"deflate":return c.deflateSync(e);default:return e}}(t(f,r,i),g);return void 0!==i.getHeader("content-length")&&(i.headersSent?e.warn(`Rewrite response for ${r.url}: headers already sent, Content-Length left as is`):i.setHeader("content-length",y.length)),i.headersSent||i.removeHeader("etag"),i.writeHead=u,h&&!i.headersSent&&u.apply(this,h),o.call(this,y,p),this}}a()}}const Ht="<redacted>",Vt=new RegExp(`(^|;\\s*)(${fe}=)[^;]*`,"gi"),qt=new RegExp(`^(\\s*${fe}=)[^;]*`,"i");function zt(e){const t={...e};if("string"==typeof t.authorization){const[e,s]=t.authorization.split(/\s+/,2);t.authorization=void 0===s?Ht:`${e} ${Ht}`}return void 0!==t.token&&(t.token=Ht),"string"==typeof t.cookie&&(t.cookie=t.cookie.replace(Vt,`$1$2${Ht}`)),t}function Wt(e){const t={...e},s=t["set-cookie"],r=e=>e.replace(qt,`$1${Ht}`);return Array.isArray(s)?t["set-cookie"]=s.map(r):"string"==typeof s&&(t["set-cookie"]=r(s)),t}const Jt=/^\/(?:login|auth)(?:[/?#]|$)/i,Gt=/pass(?:word|wd|code)?|pwd|secret|token|otp|mfa|2fa/i;function Kt(e,t){return Array.isArray(e)?e.map(e=>Kt(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,s])=>Gt.test(e)?(t.any=!0,[e,Ht]):[e,Kt(s,t)])):e}function Xt(e,t,s){if(!s)return s;if(Jt.test(e))return Buffer.from(Ht);const r=(t??"").split(";",1)[0].trim().toLowerCase();try{if("application/x-www-form-urlencoded"===r){const e=new URLSearchParams(s.toString("utf8")),t=[...new Set(e.keys())].filter(e=>Gt.test(e));return t.forEach(t=>e.set(t,Ht)),t.length?Buffer.from(e.toString()):s}if("application/json"===r||r.endsWith("+json")){const e={any:!1},t=Kt(JSON.parse(s.toString("utf8")),e);return e.any?Buffer.from(JSON.stringify(t)):s}}catch{}return s}const Zt=["/@","/_next/","/__nextjs_"],Yt=new Set(["/favicon.ico","/installHook.js.map"]);function Qt(e){return(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0)+512}function es(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 ts{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-=Qt(t),this.entries.delete(e)),this.head>=1024&&2*this.head>=this.insertOrder.length&&(this.insertOrder=this.insertOrder.slice(this.head),this.head=0)}allocateId(){return u.randomUUID()}add(e){let t=e,s=(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0);s>this.maxMemory&&(t={...e,requestBody:null,responseBody:null,requestBodyTruncated:e.requestBodyTruncated||null!==e.requestBody,responseBodyTruncated:e.responseBodyTruncated||null!==e.responseBody},s=0);const r=Qt(t);for(;(this.totalSize+r>this.maxMemory||this.entries.size>=this.maxEntries)&&this.head<this.insertOrder.length;)this.evictOldest();this.entries.set(t.id,t),this.insertOrder.push(t.id),this.totalSize+=r}get(e){return this.entries.get(e)}list(e){const t=e?.method?.toUpperCase(),s=e?.search?.toLowerCase(),r=e=>(!t||e.method===t)&&(!s||e.url.toLowerCase().includes(s)),n=Number.isFinite(e?.limit)?e.limit:1/0,i=[];if(n<=0)return i;if(void 0===e?.offset){for(let e=this.insertOrder.length-1;e>=this.head&&i.length<n;e-=1){const t=this.entries.get(this.insertOrder[e]);t&&r(t)&&i.push(es(t))}return i.reverse()}let a=Number.isFinite(e.offset)?Math.max(0,e.offset):0;for(let e=this.head;e<this.insertOrder.length&&i.length<n;e+=1){const t=this.entries.get(this.insertOrder[e]);t&&r(t)&&(a>0?a-=1:i.push(es(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 ss(e){const t=new C,s=async r=>{const n=await l.promises.readdir(r,{withFileTypes:!0});for(const i of n){const n=L.join(r,i.name);if(i.isDirectory())await s(n);else if(i.isFile()){const s=L.relative(e,n).replace(/\\/g,"/");t.file(s,await l.promises.readFile(n))}}};return await s(e),await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"})}async function rs(e,t){const s=await C.loadAsync(await l.promises.readFile(e),{createFolders:!1}),r=L.resolve(t),n=Object.values(s.files).filter(e=>!e.name.startsWith("__MACOSX/"));for(const e of n){const t=e.unsafeOriginalName??e.name,s=L.resolve(r,t);if(s!==r&&!s.startsWith(r+L.sep))throw new Error(`Zip entry "${t}" resolves outside the extraction directory`);if("number"==typeof e.unixPermissions&&40960==(61440&e.unixPermissions))throw new Error(`Zip archive contains a symlink ("${t}"), which is not allowed`)}await l.promises.mkdir(r,{recursive:!0});for(const e of n){const t=L.resolve(r,e.unsafeOriginalName??e.name);e.dir?await l.promises.mkdir(t,{recursive:!0}):(await l.promises.mkdir(L.dirname(t),{recursive:!0}),await l.promises.writeFile(t,await e.async("nodebuffer")))}}function ns(e){return`${e}.${process.pid}.${u.randomBytes(4).toString("hex")}.tmp`}const is=new Map;async function as(e,t,s){const r=ns(e);try{await B.writeFile(r,t,s),await B.rename(r,e)}catch(e){throw await B.rm(r,{force:!0}),e}}function os(e,t){const s=t?.distDir;if("export"!==t?.output||!s||".next"===s)return null;const r=L.resolve(e,s,"dev","types");return P.existsSync(r)?(P.rmSync(r,{recursive:!0,force:!0}),r):null}const cs=6e5;function ls(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&&F.spawn("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore"}).on("error",()=>{})}function ds(e,t,s,{cwd:r,env:n,timeoutMs:i,signal:a,killGraceMs:o=5e3}){return new Promise((c,l)=>{if(a?.aborted)return void l(new Error(`${e} was stopped`));const d="win32"!==process.platform&&(void 0!==a||void 0!==i),u=F.spawn(t,s,{cwd:r,env:n,stdio:"inherit",detached:d});let p,h;const g=(e,t)=>{p?t||void 0===h||(clearTimeout(h),h=void 0,ls(u,"SIGKILL",d)):(p=e,t?(ls(u,"SIGTERM",d),h=setTimeout(()=>{h=void 0,ls(u,"SIGKILL",d)},o)):ls(u,"SIGKILL",d))},f=()=>g(`${e} was stopped`,!1),m=void 0===i?void 0:setTimeout(()=>g(`${e} timed out after ${Math.round(i/1e3)} s`,!0),i);a?.addEventListener("abort",f,{once:!0});const y=e=>{clearTimeout(m),clearTimeout(h),a?.removeEventListener("abort",f),d&&ls(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 us=".next";async function ps(e,t={}){let s;try{const t=v.createRequire(L.join(e,"package.json")).resolve("next/package.json");s=L.resolve(L.dirname(t),"dist/bin/next")}catch{throw new Error(`Unable to resolve the "next" binary from ${e}. Is Next.js installed?`)}const{distDir:r,...i}=t,a=Object.assign({},process.env,{NODE_ENV:"production",[n.PP_DEV_NEXT_BUILD_ENV_VAR]:"1"});r?a[n.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR]=r:delete a[n.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR],await ds("next build",process.execPath,[s,"build"],{...i,cwd:e,env:a})}const hs="pageName",gs="date",fs=L.dirname("undefined"!=typeof __filename&&__filename||i.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:x&&"SCRIPT"===x.tagName.toUpperCase()&&x.src||new URL("internal.middleware-BlM7gqkq.js",document.baseURI).href)),ms=L.resolve(fs,"..",".."),ys=Buffer.from([80,75,3,4]),ws=20,vs=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const bs="sync-service.meta.json",ks="BUILD-MANIFEST.json",$s="__template_variables.json";const xs=["text","select","multiselect","file","list","color","boolean"];function Ss(e){return xs.includes(e)}const As=["true","false","Y","N","1","0"],Ts=/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function Es(e,t){return e.id===t||e.text===t}function Is(e){if("string"==typeof e||"number"==typeof e)return{id:String(e),text:String(e)};if("object"!=typeof e||null===e)return{text:""};const{id:t,text:s}=e,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{id:r,text:"string"==typeof s?s:r??""}}function Ps(e,t,s,r){const n="select"===s.type||"multi-select"===s.type;if("string"!=typeof r&&(!n||"number"!=typeof r))return[{name:e,severity:"warning",message:`${t}: field "${s.name}" should be a string, got ${typeof r}.`}];const i=String(r);if(!i)return[];switch(s.type){case"color":return Ts.test(i)?[]:[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${i}" is not a recognized color (expected e.g. "#075b7e").`}];case"select":{if(!Array.isArray(s.options)||!s.options.length)return[];const r=s.options.map(Is);return r.some(e=>Es(e,i))?[]:[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${i}" is not one of the declared options (${r.map(e=>e.text).join(", ")}).`}]}case"multi-select":{if(!Array.isArray(s.options)||!s.options.length)return[];const r=s.options.map(Is),n=i.split(",").map(e=>e.trim()).filter(e=>!r.some(t=>Es(t,e)));return n.length?[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${n.join(", ")}" is not among the declared options (${r.map(e=>e.text).join(", ")}).`}]:[]}default:return[]}}function Ls(e,t){const s=function(e){if(!Array.isArray(e)||0===e.length)return null;const t=e.map(e=>"string"==typeof e?{name:e,type:"textarea"}:e&&"object"==typeof e&&"string"==typeof e.name?e:null).filter(e=>null!==e);return t.length?t:null}(e.additional_options);if(!s)return[];const r=new Set(s.map(e=>e.name)),n=[];return t.forEach((t,i)=>{const a=`"${e.name}" item #${i+1}`;if("object"!=typeof t||null===t||Array.isArray(t))return void n.push({name:e.name,severity:"warning",message:`${a} should be an object with field(s): ${s.map(e=>e.name).join(", ")}.`});const o=t;for(const t of s)t.name in o?n.push(...Ps(e.name,a,t,o[t.name])):n.push({name:e.name,severity:"warning",message:`${a} is missing field "${t.name}".`});const c=Object.keys(o).filter(e=>!r.has(e));c.length&&n.push({name:e.name,severity:"warning",message:`${a} has unexpected field(s) not declared in additional_options: ${c.join(", ")}.`})}),n}function js(e,t){const s=[];switch(e.tag_type){case"boolean":As.includes(t)||s.push({name:e.name,severity:"warning",message:`Value "${t}" is not a recognized boolean encoding (expected one of ${As.join(", ")}).`});break;case"list":try{const r=JSON.parse(t);Array.isArray(r)?s.push(...Ls(e,r)):s.push({name:e.name,severity:"warning",message:`Value for list variable "${e.name}" is valid JSON but not an array.`})}catch{s.push({name:e.name,severity:"warning",message:`Value for list variable "${e.name}" is not valid JSON.`})}break;case"select":case"multiselect":if(Array.isArray(e.additional_options)){const r=e.additional_options.map(Is),n=("multiselect"===e.tag_type?t.split(",").map(e=>e.trim()):[t]).filter(e=>!r.some(t=>Es(t,e)));n.length&&s.push({name:e.name,severity:"warning",message:`Value "${n.join(", ")}" does not match any declared option for "${e.name}".`})}}return s}function Ns(e,t){switch(e.tag_type){case"boolean":return As.includes(t)?null:`Not a recognized boolean value ("${t}").`;case"color":return""===t||Ts.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 Rs="/@pp-dev/variables-editor",Cs=/^[A-Za-z0-9_\s-]+$/,Os="Dist service or MiAPI is not defined",Ms=new WeakMap;async function Bs(e){const t=await e.readPublicTemplateVariablesFile();if(!t)return null;const s=t.toString("utf-8");let r;try{r=JSON.parse(s)}catch(e){return{raw:s,schema:null,parseError:e instanceof Error?e.message:"Invalid JSON"}}return"object"!=typeof r||null===r||Array.isArray(r)||!Array.isArray(r.tags)?{raw:s,schema:null,parseError:'The root value must be a JSON object with a "tags" array.'}:{raw:s,schema:r}}async function Fs(e){const t=e?(await Bs(e))?.schema??null:null;return t&&{...t,tags:t.tags.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.name&&""!==e.name)}}function Ds(e,t,s){const r=Ms.get(e);if(r)return void(r.deps=t);const n={deps:t};Ms.set(e,n),e.get("/@api/variables/schema",async(e,t)=>{const{distService:s}=n.deps;if(!s)return void t.status(503).json({error:Os});const r=await Bs(s);t.json(r?{exists:!0,...r}:{exists:!1,schema:null,raw:null})}),e.put("/@api/variables/schema",async(e,t)=>{const{distService:s}=n.deps;if(!s)return void t.status(503).json({error:Os});const r=e.body?.raw;if("string"!=typeof r)return void t.status(400).json({error:"Request body must be { raw: string }."});let i;try{i=JSON.parse(r)}catch{return void t.status(400).json({error:"Not valid JSON."})}if("object"!=typeof i||null===i||Array.isArray(i))return void t.status(400).json({error:"The root value must be a JSON object."});const a=i.tags;if(!Array.isArray(a))return void t.status(400).json({error:'"tags" must be an array.'});const o=a.findIndex(e=>"object"!=typeof e||null===e||"string"!=typeof e.name||!e.name);if(-1!==o)return void t.status(400).json({error:`tags[${o}] is missing a non-empty "name".`});const c=[],l=new Set;for(const e of a)l.has(e.name)&&c.push(`Duplicate variable name "${e.name}".`),l.add(e.name),e.tag_type&&!Ss(e.tag_type)&&c.push(`"${e.name}" has an unrecognized tag_type "${e.tag_type}".`),Cs.test(e.name)||c.push(`"${e.name}" contains a character MI's own editor doesn't allow (only letters, digits, underscore, hyphen, and whitespace).`);try{await s.saveTemplateVariablesFile(Buffer.from(r,"utf-8"))}catch(e){return void t.status(500).json({error:`Failed to write ${$s}.`,details:e instanceof Error?e.message:String(e)})}t.json({ok:!0,warnings:c})}),e.get("/@api/variables/values",async(e,t)=>{const{distService:s,miAPI:r}=n.deps;try{const e=await Fs(s),n=await r.getLivePageVariables(),i=function(e,t){const s=(e?.tags??[]).filter(e=>"string"==typeof e?.name&&""!==e.name),r=new Map(s.map(e=>[e.name,e])),n=new Map(t.map(e=>[e.name,e.value])),i=new Set([...r.keys(),...n.keys()]);return Array.from(i).map(e=>({name:e,value:n.get(e)??r.get(e)?.default_value??""}))}(e,n);t.json({schema:e,live:n,combined:i,local:r.localPageVariables??null})}catch(e){t.status(502).json({error:"Failed to fetch live page variables.",details:e instanceof Error?e.message:String(e)})}}),e.put("/@api/variables/values",async(e,t)=>{const{distService:s,miAPI:r}=n.deps,i=function(e){const t="object"==typeof e&&null!==e?e.tags:void 0;if(!Array.isArray(t))return null;const s=[];for(const e of t){if("object"!=typeof e||null===e)return null;const{name:t,value:r}=e;if("string"!=typeof t||!t||"string"!=typeof r)return null;s.push({name:t,value:r})}return s}(e.body);if(!i)return void t.status(400).json({error:"Request body must be { tags: {name, value}[] }."});const a=i.map(e=>e.name).find((e,t,s)=>s.indexOf(e)!==t);if(void 0===a)try{const e=await Fs(s),n=new Map((e?.tags??[]).map(e=>[e.name,e])),a=[];for(const e of i){const t=n.get(e.name);t&&a.push(...js(t,e.value))}let o;await r.applyPageVariables(i);try{await r.reloadPageVariables()}catch(e){o=e instanceof Error?e.message:String(e)}t.json({ok:!0,warnings:a,local:r.localPageVariables??null,...o?{localError:o}:{}})}catch(e){t.status(502).json({error:"Failed to save live page variables.",details:e instanceof Error?e.message:String(e)})}else t.status(400).json({error:`Variable "${a}" is listed more than once.`})}),e.post("/@api/variables/values/local",async(e,t)=>{const{miAPI:s}=n.deps;try{await s.reloadPageVariables(),t.json({local:s.localPageVariables??null})}catch(e){t.status(502).json({error:"Failed to update the local values.",details:e instanceof Error?e.message:String(e)})}}),e.get("/@api/variables/pages",async(e,t)=>{const{miAPI:s}=n.deps;try{const e=await s.listPages(),r=e=>void 0!==s.pageId?e.id===s.pageId:e.internal_name===s.internalPageName,n=e.find(r)??null,i=e.filter(e=>!r(e)).map(e=>({id:e.id,name:e.name,internal_name:e.internal_name,sameTemplate:!!n&&(null!=n.template_id?e.template_id===n.template_id:!!n.template&&e.template===n.template)}));t.json({pages:i,currentPageName:n?.name??null})}catch(e){t.status(502).json({error:"Failed to fetch the page list.",details:e instanceof Error?e.message:String(e)})}}),e.get("/@api/variables/import-plan/:pageId",async(e,t)=>{const{distService:s,miAPI:r}=n.deps,i=Number(e.params.pageId);if(!Number.isInteger(i)||i<=0)t.status(400).json({error:"pageId must be a positive integer."});else try{const e=await Fs(s),n=await r.getPageVariablesFor(i);t.json(function(e,t){const s=new Map((e?.tags??[]).map(e=>[e.name,e])),r=[],n=[];for(const e of t){const t=s.get(e.name);if(!t){n.push({name:e.name,sourceValue:e.value,reason:"Not in the current page's schema."});continue}const i=Ns(t,e.value);i?n.push({name:e.name,sourceValue:e.value,reason:i}):r.push({name:e.name,sourceValue:e.value,tagType:t.tag_type||"text"})}return{importable:r,skipped:n}}(e,n))}catch(e){t.status(502).json({error:"Failed to fetch values from the selected page.",details:e instanceof Error?e.message:String(e)})}}),q(e,{path:Rs,name:"variables-editor",clientDir:s,values:()=>({templateLess:String(Boolean(n.deps.miAPI.isTemplateLess))})})}const _s=12e4;class Us{server;opts;eventMap;logger;syncInFlight=null;syncActionResolvers=new Map;constructor(e,t){this.server=e,this.opts=t||{},this.eventMap=new Map,this.eventMap.set("info-data:request",this.onInfoDataRequest.bind(this)),this.eventMap.set("template:sync",this.onTemplateSync.bind(this)),this.eventMap.set("template:sync:action-response",this.onTemplateSyncActionResponse.bind(this)),this.eventMap.set("page-variables:reload",this.onPageVariablesReload.bind(this)),this.logger=n.createLogger(),this.init()}init(){const{ws:e}=this.server;for(const[t,s]of this.eventMap)e.on(t,s);e.on("error",()=>{this.clearAllPendingSyncActions("disconnected")})}dispose(){this.clearAllPendingSyncActions("shutdown"),this.opts.distService?.stopBuilds()}resolveSyncAction(e,t){const s=this.syncActionResolvers.get(e);s&&(clearTimeout(s.timeoutId),s.cleanup(),this.syncActionResolvers.delete(e),s.resolve(t))}clearAllPendingSyncActions(e){for(const t of[...this.syncActionResolvers.keys()])this.resolveSyncAction(t,{approved:!1,reason:e})}describeSyncCancel(e){switch(e){case"cancelled":return"Sync cancelled by user.";case"timeout":return`Sync cancelled: its dialog was not answered within ${Math.round((this.opts.syncActionTimeoutMs??_s)/1e3)} s.`;case"disconnected":return"Sync cancelled: the tab that started it lost its connection to the dev server.";case"shutdown":return"Sync cancelled: the dev server is shutting down."}}cancelSync(e,t){const s=this.describeSyncCancel(t);this.sendSyncResponse(e,{cancelled:!0,message:`${s} Backup was saved.`}),this.logger.info(n.colors.yellow(s))}sendSyncResponse(e,t){e.send("template:sync:response",t)}onInfoDataRequest(e,t){t.send("info-data:response",{})}onTemplateSyncActionResponse(e){e&&"string"==typeof e.requestId&&"boolean"==typeof e.approved&&this.resolveSyncAction(e.requestId,e.approved?{approved:!0}:{approved:!1,reason:"cancelled"})}async requestSyncAction(e,t){const s=p.randomUUID(),r=this.opts.syncActionTimeoutMs??_s;return await new Promise(n=>{const i=e=>this.resolveSyncAction(s,{approved:!1,reason:e}),a=setTimeout(()=>i("timeout"),r),{socket:o}=t,c=()=>i("disconnected");o?.once("close",c),this.syncActionResolvers.set(s,{resolve:n,timeoutId:a,cleanup:()=>o?.off("close",c)}),o&&o.readyState!==o.OPEN?i("disconnected"):t.send("template:sync:action-required",{...e,requestId:s})})}async onTemplateSync(e,t){if(this.syncInFlight)return this.logger.warn(n.colors.yellow("Template sync requested while another one is running; ignored")),void this.sendSyncResponse(t,{error:"A template sync is already running. Wait for it to finish, or answer its dialog in the tab that started it.",code:"SYNC_IN_PROGRESS"});const s=this.runTemplateSync(e,t);this.syncInFlight=s;try{await s}finally{this.syncInFlight=null}}async runTemplateSync(e,t){if(!this.opts.distService||!this.opts.miAPI)return this.sendSyncResponse(t,{error:"Dist service or MiAPI is not defined"}),void this.logger.error(n.colors.red("Dist service or MiAPI is not defined"));{const{distService:e,miAPI:s}=this.opts;try{if(this.server.config.clientInjectionPlugin?.v7Features){if(!s?.isV710OrHigher)return void this.sendSyncResponse(t,{error:"This feature is available only for MI v7.1.0 or higher",config:{canSync:!1}});t.send("client:config:update",{config:{canSync:!0}})}const r=await s.getAssets().catch(async e=>{if(await this.reportMiFailure(t,e))return e;throw e});if(r instanceof Error)return;let i;if(r){const s=await(e?.analyzeBackup(r).catch(e=>e));if(s instanceof Error)i=s;else if(s){await(e?.saveBackup(r,s));const n=0===s.unknownFiles.length&&1===s.versionManifestHashMismatches.length&&L.basename(s.versionManifestHashMismatches[0].relativePath)===$s,a=s.versionManifestHashMismatches,o=a.filter(e=>L.basename(e.relativePath)===$s),c=a.filter(e=>L.basename(e.relativePath)!==$s),l=!n&&o.length>0&&c.length>0,d=n?[]:c.map(e=>e.relativePath),u=async()=>{if(!s.templateVariables||!e)return!0;const{templateVariables:r}=s;if(await e.getPublicTemplateVariablesHash()!==r.actualHash){const s=await this.requestSyncAction({title:"Template variables (server backup)",content:"The server backup includes __template_variables.json. It differs from your local public/__template_variables.json (or that file is missing). Replace your project copy with the server backup?",confirmText:"Replace from server",cancelText:"Keep local"},t);if(s.approved)await e.saveTemplateVariablesFile(r.content);else if("cancelled"!==s.reason)return this.cancelSync(t,s.reason),!1}return!0};if(s.unknownFiles.length>0){const e=await this.requestSyncAction({title:"Unknown files found in backup",content:`Backup contains files not listed in VERSION: ${s.unknownFiles.join(", ")}. Continue sync or cancel?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!e.approved)return void this.cancelSync(t,e.reason)}if(l&&!await u())return;if(!n&&d.length>0){const e=40,s=d,r=s.slice(0,e),n=s.length-r.length,i=r.map(e=>`• ${e}`).join("\n"),a=n>0?`\n... and ${n} more file${1===n?"":"s"}`:"",o=await this.requestSyncAction({title:"VERSION manifest out of date",content:`These files no longer match the hashes recorded in the VERSION manifest:\n\n${i}${a}\n\nCancel sync, or override and continue using the files on disk?`,confirmText:"Override and continue",cancelText:"Cancel sync"},t);if(!o.approved)return void this.cancelSync(t,o.reason)}if(!n&&s.buildManifestMismatch&&0===s.versionManifestHashMismatches.length){const{expected:e,actual:r}=s.buildManifestMismatch,n=await this.requestSyncAction({title:"Build manifest fingerprint mismatch",content:`The recomputed backup fingerprint does not match BUILD-MANIFEST.json.\nManifest: ${e.slice(0,12)}...\nComputed: ${r.slice(0,12)}...\nContinue sync anyway?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!n.approved)return void this.cancelSync(t,n.reason)}if(!l&&!await u())return;i=await(e?.buildNewAssets())}}else i=await(e?.buildNewAssets());if(!(i&&i instanceof Buffer))return i instanceof Error?(this.sendSyncResponse(t,{error:i.message}),void this.logger.error(n.colors.red(i.message))):(this.sendSyncResponse(t,{error:"Failed to build new assets"}),void this.logger.error(n.colors.red("Failed to build new assets")));{if(e.stopped)return this.sendSyncResponse(t,{error:"Sync stopped: the dev server is shutting down."}),void this.logger.warn(n.colors.yellow("Sync stopped before the upload: the dev server is shutting down"));let r;try{r=await s.updateAssets(i)}catch(e){if(await this.reportMiFailure(t,e))return;throw e}if("OK"===r?.status){const s=e?.getBackupMeta();this.sendSyncResponse(t,{syncedAt:(new Date).toISOString(),backupFilename:s?.lastBackupName??""}),this.logger.info(n.colors.green("Template synced"))}else{const e=`Failed to update assets: MI answered ${function(e){if("string"==typeof e){const t=e.replace(/\s+/g," ").trim();return`with a non-JSON body: "${t.slice(0,120)}${t.length>120?"…":""}"`}return e&&"object"==typeof e?`with ${JSON.stringify(e).slice(0,200)}`:`with ${String(e)}`}(r)}`;this.sendSyncResponse(t,{error:e}),this.logger.error(n.colors.red(e))}}}catch(e){const s=e instanceof Error?e.message:"Template sync failed";return this.logger.error(n.colors.red(`Template sync failed: ${s}`)),void this.sendSyncResponse(t,{error:s,code:"SYNC_FAILED"})}}}async reportMiFailure(t,s){if(e.isAxiosError(s)){if("SESSION_EXPIRED"===$e(s).code){this.logger.info(n.colors.yellow("Session expired - attempting to validate credentials"));try{const e=await(this.opts.miAPI?.validateCredentials());e&&!e.isValid?(this.logger.error(n.colors.red(`Authentication error: ${e.error}`)),this.sendSyncResponse(t,{error:e.error??"Authentication failed",code:e.code,refresh:!0})):(this.logger.info(n.colors.yellow("Session expired")),this.sendSyncResponse(t,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0}))}catch{this.logger.info(n.colors.yellow("Session expired")),this.sendSyncResponse(t,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0})}return!0}if(s.cause instanceof Error&&("ECONNRESET"===s.cause.code||"ENOTFOUND"===s.cause.code))return this.logger.info(n.colors.yellow("Server in maintenance mode, VPN connection is needed or no internet connection")),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0;const e=s.response?.status;if(502===e||503===e||504===e)return this.logger.info(n.colors.yellow(`Server in maintenance mode or unreachable (HTTP ${e}); VPN may be required`)),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0}return!!le(s)&&(this.logger.info(n.colors.yellow("Server in maintenance mode or non-JSON page / page-template API response (unavailable HTML body)")),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0)}async onPageVariablesReload(e,t){const{miAPI:s}=this.opts;if(!s)return t.send("page-variables:reload:response",{error:"MiAPI is not defined"}),void this.logger.error(n.colors.red("MiAPI is not defined"));try{const e=await s.reloadPageVariables();t.send("page-variables:reload:response",{ok:!0,count:e?e.length:0,skipped:null===e}),this.logger.info(n.colors.green("Page variables reloaded"))}catch(e){const s=e instanceof Error?e.message:"Reload variables failed";this.logger.error(n.colors.red(`Reload variables failed: ${s}`)),t.send("page-variables:reload:response",{error:s})}}}const Hs="/@api/users",Vs=new WeakMap;function qs(e,t){const s=_e(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 zs(e,t,s,r){e.status(t).json({error:r,code:s})}function Ws(e){let t;try{t=JSON.parse(M.readFileSync(e,"utf-8"))}catch(t){return"ENOENT"!==t.code&&n.createLogger().warn(n.colors.yellow(`Could not read the saved users from ${e}: ${String(t)}`)),[]}const s=t&&"object"==typeof t&&!Array.isArray(t)?t.users:void 0;return(Array.isArray(s)?s:[]).filter(e=>"string"==typeof e?.name&&"string"==typeof e.token&&Boolean(e.token))}function Js(e,t,s){const r={version:1,...s,users:t};M.mkdirSync(_.dirname(e),{recursive:!0,mode:448}),function(e,t,s){const r=ns(e);try{O.writeFileSync(r,t,s),O.renameSync(r,e)}catch(e){throw O.rmSync(r,{force:!0}),e}}(e,`${JSON.stringify(r,null,2)}\n`,{mode:384}),M.chmodSync(e,384)}const Gs=new WeakMap,Ks=new WeakMap;function Xs(e){Gs.delete(e),Ks.get(e)?.(),Ks.delete(e)}async function Zs(e,t){const s=function(e,t,s=D.homedir()){const r=u.createHash("sha256").update(`${_.resolve(e)}\n${t.replace(/\/+$/,"")}`).digest("hex").slice(0,16);return _.join(s,".pp-dev","users",`${r}.json`)}(t.projectRoot,t.miUrl,t.homeDir),r={project:_.resolve(t.projectRoot),miUrl:t.miUrl},i=n.createLogger();if(Gs.get(e)===s)return;Xs(e),Gs.set(e,s);const a=Ws(s);let o=!0,c=!1,l=e.list().some(e=>"token"===e.kind&&e.token);const d=new Set,p=new Set,h=()=>{const t=e.list(),a=t.filter(e=>"token"===e.kind&&e.token).map(e=>({name:e.name,token:e.token})),o=new Set(t.map(e=>e.name)),c=Ws(s).filter(e=>!o.has(e.name)&&!p.has(e.name));try{Js(s,[...a,...c],r)}catch(e){i.warn(n.colors.yellow(`Could not save the users to ${s}: ${String(e)}`))}},g=e.onRemove(t=>{Gs.get(e)===s&&(p.add(t.name),o&&d.add(t.name))}),f=e.onChange(()=>{Gs.get(e)===s&&(o?l||=!c:h())});Ks.set(e,()=>{g(),f()});try{const r=await Promise.all(a.map(e=>t.checkToken(e.token)));if(Gs.get(e)!==s)return;a.forEach((t,s)=>{if(Fe(t.name)||e.get(t.name)||d.has(t.name))return;const a=r[s];c=!0;try{e.add({name:t.name,kind:"token",token:t.token,...a.ok?{miUser:a.miUser}:{},...!a.ok&&a.rejected?{state:"expired"}:{}})}finally{c=!1}a.ok||i.warn(n.colors.yellow(`Restored user ${t.name}: ${a.message}`))})}finally{o=!1}l&&Gs.get(e)===s&&h(),a.length&&i.info(`${n.colors.blue("Restored")} ${a.length} ${n.colors.blue("saved user(s) from")} ${s}`)}function Ys(e){const t=`${_.resolve(e.projectRoot)}\n${e.miUrl.replace(/\/+$/,"")}`;Ue.context!==t&&(Xs(Ue),Ue.useContext(t)),e.persist?e.miAPI.personalAccessToken?Zs(Ue,{projectRoot:e.projectRoot,miUrl:e.miUrl,checkToken:t=>Ge(e.miAPI,t)}).catch(e=>{n.createLogger().warn(n.colors.yellow(`Could not restore the saved users: ${String(e)}`))}):n.createLogger().warn(n.colors.yellow("users.persist is on, but users need your own API token (mi.token or MI_ACCESS_TOKEN).")):Xs(Ue)}function Qs(e,t,s,r,n){const i={error:s};r&&(i.details=r),n&&(i.code=n),e.status(t).json(i).end()}function er(e){return["/@vite","/@metricinsights","/@",(e.endsWith("/")?e.slice(0,-1):e)||"/"]}function tr(e,t){const s=t instanceof Error?t.message:String(t);n.createLogger().error(n.colors.red(`Request failed: ${s}`)),e.writableEnded||e.destroyed||(e.headersSent?e.destroy():(e.statusCode=500,e.setHeader("content-type","text/plain; charset=utf-8"),e.end(s)))}const sr="10mb",rr=(e,t,s,r)=>{const n="number"==typeof e?.status?e.status:void 0;if(!n||n<400||n>=500||"string"!=typeof e.type||s.headersSent)return void r(e);const i="entity.too.large"===e.type?`The request body is larger than the dev server accepts (${sr}).`:`The request body could not be read: ${e.message}`;s.status(n).json({error:i})};exports.DistService=class{root;backupFolder;backupNameTemplate;dateFormat;pageName;currentMeta=null;versionFileTemplate;buildInputFolder;nextBuild;maxBackups;buildTimeoutMs;metaDir;builds=new AbortController;metaLoaded;logger;constructor(e,t){this.pageName=e;const{root:s=N.cwd(),backupFolder:r="backups",backupNameTemplate:i=`{${hs}}-{${gs}}.zip`,versionFileTemplate:a="VERSION-v{packageversion}-{currentDate}.json",buildInputFolder:o,dateFormat:c=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,""),nextBuild:l,maxBackups:d=ws,buildTimeoutMs:u=cs,metaDir:p}=t||{};this.root=s,this.backupFolder=L.resolve(s,r),this.backupNameTemplate=i,this.dateFormat=c,this.versionFileTemplate=n.normalizeRelativeOutputPath(a,"VERSION file name template"),this.buildInputFolder=o,this.nextBuild=l,this.maxBackups="number"==typeof d&&Number.isInteger(d)&&d>0?d:1/0,this.buildTimeoutMs=u,this.metaDir=void 0===p?L.join(this.backupFolder,".pp-dev-meta"):L.resolve(s,p),this.logger=n.createLogger(),this.metaLoaded=this.loadMeta()}stopBuilds(){this.builds.abort()}async checkMeta(){await l.promises.mkdir(this.metaDir,{recursive:!0}),await l.promises.mkdir(this.backupFolder,{recursive:!0})}async loadMeta(){try{const e=JSON.parse(await this.readMetaFile());this.currentMeta=e&&"object"==typeof e?e:{}}catch(e){this.logger.warn(n.colors.yellow(`[DistService] Could not read the sync meta (${e instanceof Error?e.message:String(e)}); starting a new one`)),this.currentMeta={}}}async meta(){return await this.metaLoaded,this.currentMeta||(this.currentMeta={}),this.currentMeta}async readMetaFile(){return await this.checkMeta(),await l.promises.readFile(L.join(this.metaDir,bs),{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await l.promises.writeFile(L.join(this.metaDir,bs),JSON.stringify(e,null,2),{encoding:"utf-8"})}async syncMeta(){await this.writeMetaFile(await this.meta())}async getLatestSavedBackup(){const{lastBackupName:e}=await this.meta();if(!e)return null;const t=L.resolve(this.backupFolder,e);try{return await l.promises.stat(t),t}catch{return null}}backupName(e,t=new Date){return this.backupNameTemplate.replace(`{${hs}}`,e).replace(`{${gs}}`,this.dateFormat(t))}getBackupMeta(){return this.currentMeta}async pruneBackups(e){if(Number.isFinite(this.maxBackups))try{const t=function(e,t,s){const r=s.split(/(\d+)/).map((e,t)=>t%2==1?"\\d+":vs(e)).join(""),n=[{token:`{${hs}}`,pattern:vs(t)},{token:`{${gs}}`,pattern:r}].map(t=>({...t,at:e.indexOf(t.token)})).filter(e=>-1!==e.at).sort((e,t)=>e.at-t.at);let i="^",a=0;for(const{token:t,pattern:s,at:r}of n)i+=vs(e.slice(a,r))+s,a=r+t.length;return new RegExp(`${i}${vs(e.slice(a))}$`)}(this.backupNameTemplate,this.pageName,this.dateFormat(new Date)),s=new Set([e]),r=await l.promises.readdir(this.backupFolder,{withFileTypes:!0}),i=(await Promise.all(r.filter(e=>e.isFile()&&t.test(e.name)).map(async e=>({name:e.name,mtimeMs:(await l.promises.stat(L.resolve(this.backupFolder,e.name))).mtimeMs})))).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.name.localeCompare(e.name)),a=i.filter(e=>s.has(e.name)).length,o=i.filter(e=>!s.has(e.name)).slice(Math.max(0,this.maxBackups-a));for(const e of o)await l.promises.unlink(L.resolve(this.backupFolder,e.name));o.length>0&&this.logger.info(n.colors.gray(`[DistService] Deleted ${o.length} old backup(s), keeping the latest ${this.maxBackups}`))}catch(e){this.logger.warn(n.colors.yellow(`[DistService] Could not delete old backups: ${e instanceof Error?e.message:String(e)}`))}}pathToPosix(e){return e.replace(/\\/g,"/")}normalizeBackupManifestPath(e){try{return n.normalizeRelativeOutputPath(e,"VERSION manifest file path")}catch{throw new Error(`VERSION manifest file path "${e}" resolves outside the backup root`)}}async normalizeExtractedRootDir(e){let t=e;for(;;){const e=await l.promises.readdir(t,{withFileTypes:!0});if(1!==e.length||!e[0]?.isDirectory())return t;t=L.join(t,e[0].name)}}async listFilesRecursive(e){const t=await l.promises.readdir(e,{withFileTypes:!0}),s=[];for(const r of t){const t=L.join(e,r.name);r.isDirectory()?s.push(...await this.listFilesRecursive(t)):r.isFile()&&s.push(t)}return s}buildManifestChecksum(e){const t=Object.keys(e).sort().map(t=>e[t]).join("");return j.createHash("sha256").update(t).digest("hex")}buildBackupFingerprint(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("\n");return j.createHash("sha256").update(t,"utf-8").digest("hex")}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}versionFileTemplateMatcher(){const e=/\{[^}]+\}/g,t=[];let s=0,r=null;for(;r=e.exec(this.versionFileTemplate),r;){const[e]=r,n=this.versionFileTemplate.slice(s,r.index);t.push(this.escapeRegExp(n)),t.push("[^/]+"),s=r.index+e.length}const n=this.versionFileTemplate.slice(s);return t.push(this.escapeRegExp(n)),new RegExp(`^${t.join("")}$`,"i")}isTemplateVariablesBasename(e){return e===$s}async pickTemplateVariablesFromBackupZip(e,t){const s=e.find(e=>L.basename(e)===$s);if(!s)return null;const r=L.join(t,s),n=await l.promises.readFile(r);return{relativePath:s,content:n,actualHash:j.createHash("sha256").update(n).digest("hex"),manifestHash:null}}async resolveBackupAnalysisFromZip(e){const t=await l.promises.mkdtemp(L.join(R.tmpdir(),"pp-dev-backup-")),s=L.join(t,"backup.zip"),r=L.join(t,"extracted");try{await l.promises.mkdir(r,{recursive:!0}),await l.promises.writeFile(s,e),await rs(s,r);const t=await this.normalizeExtractedRootDir(r),i=(await this.listFilesRecursive(t)).map(e=>this.pathToPosix(L.relative(t,e))),a=i.filter(e=>L.basename(e)===ks);if(a.length>1)throw new Error(`Expected at most one ${ks} in backup ZIP, found ${a.length}`);const o=1===a.length?a[0]:null;let c=null;if(o){const e=L.join(t,o);if(c=JSON.parse(await l.promises.readFile(e,"utf-8")),!(c&&"pp-dev-build-manifest"===c.manifestType&&"string"==typeof c.versionFile&&c.versionFile.trim()&&"string"==typeof c.versionFileTemplate&&c.versionFileTemplate.trim()&&"string"==typeof c.buildFingerprint&&c.buildFingerprint.trim()))throw new Error("Build manifest is missing required fields")}let d=null;if(c){const e=this.pathToPosix(c.versionFile.trim()),t=i.filter(t=>t===e),s=i.filter(t=>L.basename(t)===L.basename(e)),r=t.length>0?t:s;if(r.length>1)throw new Error(`Build manifest version file "${c.versionFile}" must resolve to exactly one file in backup ZIP, found ${r.length}`);if(1===r.length&&(d=r[0]),!0===c.compat?.versionFileRequired&&null===d)throw new Error(`Build manifest requires version file "${c.versionFile}", but it is missing in backup ZIP`)}else{const e=this.versionFileTemplateMatcher(),t=i.filter(t=>e.test(L.basename(t)));if(t.length>1)throw new Error(`Expected exactly one version file matching template "${this.versionFileTemplate}" in backup ZIP, found ${t.length}`);1===t.length&&(d=t[0])}const u={};let p=null,h=null,g=[];if(d){const e=L.join(t,d),s=JSON.parse(await l.promises.readFile(e,"utf-8"));if(!s?.files||"object"!=typeof s.files)throw new Error("VERSION manifest files map is missing or invalid");if("string"!=typeof s.checksum||!s.checksum)throw new Error("VERSION manifest checksum is missing or invalid");h=s.checksum;for(const[e,t]of Object.entries(s.files)){if("string"!=typeof t||!t.trim())throw new Error(`VERSION manifest contains invalid hash for file: ${e}`);const s=this.normalizeBackupManifestPath(e);if(Object.prototype.hasOwnProperty.call(u,s))throw new Error(`VERSION manifest contains duplicate normalized file path: ${s}`);u[s]=t}if(this.buildManifestChecksum(u)!==s.checksum)throw new Error("VERSION manifest checksum does not match its files map");for(const[e,s]of Object.entries(u)){const r=L.join(t,e),n=await l.promises.readFile(r).catch(()=>null);if(!n)throw new Error(`VERSION manifest references missing file: ${e}`);const i=j.createHash("sha256").update(n).digest("hex");i!==s&&g.push({relativePath:e,expected:s,actual:i}),this.isTemplateVariablesBasename(L.basename(e))&&(p={relativePath:e,content:n,actualHash:i,manifestHash:s})}g.length>0&&this.logger.warn(n.colors.yellow(`[DistService] VERSION manifest hash mismatch for ${g.length} file(s) (confirm in UI): ${g.map(e=>e.relativePath).join(", ")}`))}const f={},m=[];for(const e of i){if(e===o)continue;if(d&&e===d)continue;const s=L.join(t,e),r=await l.promises.readFile(s);f[e]=j.createHash("sha256").update(r).digest("hex"),d&&!Object.prototype.hasOwnProperty.call(u,e)&&m.push(e)}p||(p=await this.pickTemplateVariablesFromBackupZip(i,t));const y=this.buildBackupFingerprint(f);let w=null;return c&&d&&y!==c.buildFingerprint&&(w={expected:c.buildFingerprint,actual:y},this.logger.warn(n.colors.yellow(`[DistService] Build manifest fingerprint mismatch (confirm in UI): expected ${c.buildFingerprint}, got ${y}`))),{backupFingerprint:y,unknownFiles:m,templateVariables:p,mainHash:h,buildManifestMismatch:w,versionManifestHashMismatches:g}}finally{await l.promises.rm(t,{recursive:!0,force:!0})}}async analyzeBackup(e){if(!ys.equals(e.subarray(0,ys.length)))throw new Error("Backup file is not a ZIP file");return await this.resolveBackupAnalysisFromZip(e)}async getPublicTemplateVariablesHash(){const e=L.resolve(this.root,"public",$s),t=await l.promises.readFile(e).catch(()=>null);return t?j.createHash("sha256").update(t).digest("hex"):null}async readPublicTemplateVariablesFile(){const e=L.resolve(this.root,"public",$s);return await l.promises.readFile(e).catch(()=>null)}async saveTemplateVariablesFile(e){const t=L.resolve(this.root,"public",$s);return await l.promises.mkdir(L.dirname(t),{recursive:!0}),await function(e,t,s){const r=(is.get(e)??Promise.resolve()).then(()=>as(e,t,s),()=>as(e,t,s)),n=()=>{is.get(e)===r&&is.delete(e)};return is.set(e,r),r.then(n,n),r}(t,e),t}async saveBackup(e,t){const s=(t??await this.analyzeBackup(e)).backupFingerprint,r=await this.getLatestSavedBackup(),i=await this.meta();if(r&&i.lastBackupHash===s)return void this.logger.info(n.colors.yellow(`[DistService] Backup skipped: same backup fingerprint as last saved (${s.slice(0,12)}...)`));const a=new Date,o=this.backupName(this.pageName,a);i.lastBackupName=o,i.lastBackupHash=s,i.lastBackupDate=a.toISOString(),delete i.lastMainHash,await this.syncMeta(),await l.promises.writeFile(L.resolve(this.backupFolder,o),e),this.logger.info(`Backup saved to ${o}`),await this.pruneBackups(o)}async buildNewAssets(){if(this.nextBuild)return await this.buildNextAssets();this.logger.info(n.colors.cyan("[DistService] Build started"));const e=ds("pp-dev build",N.execPath,[L.resolve(ms,"./bin/pp-dev.js"),"build"],{cwd:this.root,env:Object.assign({},N.env,{NODE_ENV:"production"}),timeoutMs:this.buildTimeoutMs,signal:this.builds.signal});try{if(await this.logBuild("Build",e),!this.buildInputFolder)throw new Error("The sync has no build directory to zip (build.outDir or build.zip.inDir)");const t=L.resolve(this.root,this.buildInputFolder);if(!await this.isDirectory(t))throw new Error(`Build input directory ${t} not found`);const s=await ss(t);return this.throwIfStopped("pp-dev build"),s}catch(e){throw this.logger.error(e instanceof Error?e.stack??e.message:String(e)),e}}async saveBackupAndBuild(e){return await this.saveBackup(e),await this.buildNewAssets()}async buildNextAssets(){const{projectRoot:e,distDir:t,buildDistDir:s=t,output:i,configWrapped:a}=this.nextBuild,o=a||s===us?"out":s,c=L.resolve(e,o);if(a&&function(e,t){const s=L.relative(t,e);return""===s||!(".."===s||s.startsWith(`..${L.sep}`)||L.isAbsolute(s))}(L.resolve(e,t),c))throw new Error(`The app's distDir (${t}) is inside the sync's export directory (${o}), which next build empties: set another distDir in next.config.`);const d=os(e,{output:i,distDir:t});if(d&&this.logger.info(n.colors.dim(`[DistService] Removed stale dev route types: ${L.relative(e,d)}`)),a||o!==t||this.logger.warn(n.colors.yellow(`⚠️ next.config is not wrapped with withPPDev(): the sync's build exports into ${t} and removes the dev server's ${L.join(t,"dev")}; restart pp-dev next after the sync`)),a&&await l.promises.rm(c,{recursive:!0,force:!0}),this.logger.info(n.colors.cyan("[DistService] Next.js build started")),await this.logBuild("Next.js build",ps(e,{timeoutMs:this.buildTimeoutMs,signal:this.builds.signal,distDir:a?us:void 0})),!await this.isDirectory(c))throw new Error(`Next.js build output directory not found: ${c}. The sync needs "output: 'export'" in next.config (static export).`);this.throwIfStopped("next build"),await r.writeBuildVersionManifest({outDir:c,root:e,packageVersion:this.nextBuild.packageVersion,versionFileTemplate:this.versionFileTemplate,packageRepositoryUrl:this.nextBuild.packageRepositoryUrl,packageBranchName:this.nextBuild.packageBranchName}),this.throwIfStopped("next build");const u=await ss(c);return this.throwIfStopped("next build"),u}get stopped(){return this.builds.signal.aborted}throwIfStopped(e){if(this.stopped)throw new Error(`${e} was stopped`)}async logBuild(e,t){try{await t}catch(t){const s=this.builds.signal.aborted;throw this.logger.info(n.colors.yellow(`[DistService] ${e} ${s?"stopped":"failed"}`)),t}this.logger.info(n.colors.cyan(`[DistService] ${e} finished`))}async isDirectory(e){try{return(await l.promises.stat(e)).isDirectory()}catch{return!1}}},exports.INSPECTOR_PATH=W,exports.PP_DEV_HMR_WS_PATH="/@pp-dev-hmr",exports.configuredNextDistDir=function(e){return(e?.distDirRoot||e?.distDir||".next").replace(/\\/g,"/").replace(/\/+$/,"")},exports.createInternalServer=function({allowedHosts:e=[]}={}){const t=U();return t.use(n.createOriginGuard(e)),t.use(U.json({limit:sr})),t.use(U.urlencoded({extended:!0})),t.use(rr),t},exports.createMiddlewareChain=function(e){const{templateName:t,internalServer:s,backendBaseURL:r,inspector:i,proxy:a}=e,o=e.base.endsWith("/")?e.base:`${e.base}/`,c=[],l=[];if(r){const e=He();c.push(e),l.push(e)}if(i.enabled){const e=new ts(i.maxMemory);K(s,e,i.captureLimit),c.push(function(e,t=10485760,s=Ue){return(r,n,i)=>{const a=r.url||"/",o=a.split("?")[0];if(Zt.some(e=>a.startsWith(e))||Yt.has(o))return void i();const c=e.allocateId(),l=s.resolve(r)?.user?.name,d=Date.now(),u=[];let p=0,h=!1;const g=r.emit.bind(r);r.emit=(e,...s)=>{if("data"===e&&!h){const e=s[0],r=Buffer.isBuffer(e)?e:Buffer.from(String(e));p+=r.byteLength,p<=t?u.push(r):(h=!0,u.length=0)}return g(e,...s)};const f=[];let m=0,y=!1;const w=n.write.bind(n),v=n.end.bind(n);function b(e,s){if(!y&&null!=e)try{const r=Buffer.isBuffer(e)?e:"string"==typeof e?Buffer.from(e,s):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?Buffer.from(e):Buffer.from(String(e));m+=r.byteLength,m<=t?f.push(r):(y=!0,f.length=0)}catch{}}function k(e){return"string"==typeof e[0]?e[0]:void 0}function $(){const e=n.getHeaders();return e["x-pp-proxy"]?"hit"===e["x-pp-cache"]?"proxy-cache":"proxy":"local"}let x=!1;function S(t=!1){if(x)return;x=!0;const s=Xt(a,"string"==typeof r.headers["content-type"]?r.headers["content-type"]:void 0,!h&&u.length>0?Buffer.concat(u):null),i=!y&&f.length>0?Buffer.concat(f):null;e.add({id:c,timestamp:d,method:r.method||"GET",url:a,statusCode:n.statusCode??null,duration:Date.now()-d,source:$(),user:l,requestHeaders:zt(r.headers),requestBody:s,requestBodyTruncated:h,responseHeaders:Wt(n.getHeaders()),responseBody:i,responseBodyTruncated:y,...t?{aborted:t}:{}})}n.once("close",()=>S(!0)),n.write=(e,...t)=>(b(e,k(t)),w(e,...t)),n.end=(e,...t)=>("function"!=typeof e&&b(e,k(t)),S(),v(e,...t)),i()}}(e,i.captureLimit))}const d=Ce(o,t);if(c.push(d),l.push(d),e.devPanelAssets){const e=n.createDevPanelAssetMiddleware(o);c.push(e),l.push(e)}if(i.enabled||r){const e=(e,t,r)=>{const n=e.url??"";n.startsWith("/@api/")||n.startsWith(W)||n.startsWith(Rs)?s(e,t,e=>function(e,t){t?tr(e,t):e.headersSent||e.writableEnded||(e.statusCode=404,e.setHeader("content-type","application/json"),e.end(JSON.stringify({error:"Not found"})))}(t,e)):r()};c.push(e),l.push(e)}let u=null,p=null,h=null;if(r){"/"===o&&n.createLogger().warn(n.colors.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}}(r,e.mi);u=new Re(r,s),a.cache&&(p=function(e){const t=Number(e);return!t||Number.isNaN(t)||t<0?6e5:t}(a.cacheTtl),c.push($t({devServer:a.devServer,ttl:p}))),c.push(Ot(function(e){return new RegExp(`^((${t=e,t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`);var t}(o),u,{...e.mi,base:o,appBase:o})),c.push(ot({baseURL:r,proxyIgnore:[...er(o),...a.ignore??[]],disableSSLValidation:e.mi.disableSSLValidation,miAPI:u,templateName:t}));const i=e.rewrite(u,new URL(r).host);h=Ut((e,t)=>i.predicate(e,t),(e,t)=>i.transform(e,t),i.contentType?{contentType:i.contentType}:{})}return{main:c,essential:l,rewrite:h,mi:u,proxyCacheTtl:p}},exports.extractZipSafe=rs,exports.mountMiddlewareChain=function(e,t){for(const s of t.main)e.middlewares.use(s)},exports.removeStaleDevTypes=os,exports.runMiddlewareChain=function(e,t,s,r){let n=0;const i=a=>{if(a)return void tr(s,a);if(n>=e.length)return void r();const o=e[n];n+=1;try{o(t,s,i)}catch(e){tr(s,e)}};i()},exports.runNextBuildProcess=ps,exports.startSyncAndUsers=function(e){const{distService:t,miAPI:s,persistUsers:r,projectRoot:i,miUrl:a}=e,o=new Us(e.server,{distService:t,miAPI:s});return function(e,t){const{miAPI:s,persistUsers:r,projectRoot:i,miUrl:a}=t,o=n.createLogger(),c=(e,t,s)=>{o.error(`${s} token validation error: ${t instanceof Error?t.message:String(t)}`);const r=$e(t),n=t?.tokenErrorInfo;if(n)return Qs(e,n.status||500,n.userFriendlyMessage,n.message,n.code),null;let i,a,c;switch(r.code){case"SESSION_EXPIRED":i=412,a="personal"===s?"Personal access token expired":"Session expired",c="personal"===s?"PAT_EXPIRED":"SESSION_EXPIRED";break;case"UNAUTHORIZED":i=401,a="Unauthorized",c="UNAUTHORIZED";break;case"FORBIDDEN":i=403,a="Access forbidden",c="FORBIDDEN";break;default:i=500,a="Internal server error",c=r.code}return Qs(e,i,a,"personal"===s&&"PAT_EXPIRED"===c?"Your personal access token has expired. Please generate a new token from the portal.":"regular"===s&&"SESSION_EXPIRED"===c?"Your portal session has expired. Please refresh your token or re-authenticate.":r.userFriendlyMessage,c),null};e.post("/@api/login",async(e,t)=>{const{token:n,tokenType:l}=e.body??{};if(De(e.headers.host))Qs(t,409,"Token login is only available on the main host","This tab belongs to a saved pp-dev user. Log in with a token on the main host (localhost).","USER_HOST");else if("string"==typeof n&&n)if(o.info(`Attempting to validate ${String(l)} token...`),"personal"===l){if(!await s.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${n}`},!0).then(e=>"object"!=typeof e.data||null===e.data?(Qs(t,502,"MI is unavailable","The instance may be down or in maintenance mode. Please try again later.","MI_UNAVAILABLE"),null):"number"==typeof e.data?.user?.user_id?(s.personalAccessToken=n,o.info(`Personal access token validated successfully for user ${e.data.user.user_id}`),e):(Qs(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"personal")))return;mt("logged in with a personal access token"),Ys({persist:r,miAPI:s,projectRoot:i,miUrl:a}),Pe(t,"/",302)}else if("regular"===l){if(!await s.get("/api/user",{"Content-Type":"application/json",Accept:"application/json",Token:n},!0).then(r=>r.data?.users?.length?(s.personalAccessToken=void 0,o.info(`Regular token validated successfully for ${r.data.users.length} user(s)`),t.setHeader("set-cookie",ve(r.headers["set-cookie"],he(e))??""),r):(Qs(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"regular")))return;mt("logged in with a token"),Pe(t,"/",302)}else Qs(t,400,"Invalid tokenType",'tokenType must be "personal" or "regular".',"INVALID_TOKEN_TYPE");else Qs(t,400,"Token is required")})}(e.internalServer,{miAPI:s,persistUsers:r,projectRoot:i,miUrl:a}),Ds(e.internalServer,{distService:t,miAPI:s}),function(e,t){const s=Vs.get(e);if(s)return void(s.deps=t);const r={deps:t};Vs.set(e,r);const i=n.createLogger(),a=()=>r.deps.users??Ue;e.get(Hs,(e,t)=>{const s=a();t.json({available:Boolean(r.deps.miAPI.personalAccessToken),users:s.list().map(t=>qs(t,e)),defaultUser:s.defaultUser?.name??null})}),e.put(`${Hs}/default`,(e,t)=>{const s=a(),r=(e.body??{}).name;if(null===r||"string"==typeof r)if(null===r||s.get(r)){try{s.setDefaultUser(r??void 0)}catch(e){return void zs(t,409,"NOT_LOGGED_IN",e instanceof Error?e.message:String(e))}i.info(`${n.colors.blue("Default user:")} ${n.colors.yellow(r??"the original user")}`),t.json({defaultUser:r})}else zs(t,404,"NOT_FOUND",`There is no user named "${r}"`);else zs(t,400,"INVALID_NAME","name must be a user name or null")}),e.post(Hs,async(e,t)=>{const{miAPI:s}=r.deps,o=a(),c=e.body??{},l="string"==typeof c.name?c.name:"",d="string"==typeof c.token?c.token.trim():"",u=c.kind??"token";if("token"!==u&&"session"!==u)return void zs(t,400,"INVALID_KIND",'kind must be "token" or "session"');if(!s.personalAccessToken)return void zs(t,409,"ORIGINAL_TOKEN_REQUIRED","Adding users needs your own API token: set mi.token or MI_ACCESS_TOKEN.");const p=Fe(l);if(p)return void zs(t,400,"INVALID_NAME",p);if(o.get(l))return void zs(t,409,"NAME_TAKEN",`A user named "${l}" already exists`);if("session"===u){const s=o.add({name:l,kind:"session"});return i.info(`${n.colors.blue("Added user")} ${n.colors.yellow(s.name)}: log in at ${_e(e,s.name)}/login`),void t.status(201).json({user:qs(s,e)})}if(!d)return void zs(t,400,"TOKEN_REQUIRED","The API token is required");const h=o.context,g=await Ge(s,d);if(o.context!==h||r.deps.miAPI!==s||a()!==o)return void zs(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; add the user again");if(!g.ok)return void(g.rejected?zs(t,400,"INVALID_TOKEN",g.message):zs(t,502,"MI_UNAVAILABLE",g.message));const{miUser:f}=g;let m;try{m=o.add({name:l,kind:"token",token:d,miUser:f})}catch(e){return void zs(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}i.info(`${n.colors.blue("Added user")} ${n.colors.yellow(m.name)} (MI user ${f.id}${f.username?`, ${f.username}`:""}) at ${_e(e,m.name)}`),t.status(201).json({user:qs(m,e)})}),e.patch(`${Hs}/:name`,async(e,t)=>{const{miAPI:s}=r.deps,o=a(),c=String(e.params.name),l=o.get(c),d=e.body??{},u="string"==typeof d.name&&d.name?d.name:c,p="string"==typeof d.token?d.token.trim():"";if(!l)return void zs(t,404,"NOT_FOUND",`There is no user named "${c}"`);if("token"!==l.kind)return void zs(t,400,"NOT_EDITABLE","Only users added with an API token can be edited. Remove this user and add it again.");const h=Fe(u);if(h)return void zs(t,400,"INVALID_NAME",h);if(u!==c&&o.get(u))return void zs(t,409,"NAME_TAKEN",`A user named "${u}" already exists`);let g,f={...l,name:u};if(p&&(p!==l.token||"expired"===l.state)){const e=o.context,n=await Ge(s,p);if(o.context!==e||r.deps.miAPI!==s||a()!==o)return void zs(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; edit the user again");if(!n.ok)return void(n.rejected?zs(t,400,"INVALID_TOKEN",n.message):zs(t,502,"MI_UNAVAILABLE",n.message));const{state:i,...c}=f;f={...c,token:p,miUser:n.miUser}}if(o.get(c)===l)if(u!==c||f.token!==l.token||f.state!==l.state){try{g=o.replace(c,f)}catch(e){return void zs(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}i.info(`${n.colors.blue("Edited user")} ${n.colors.yellow(c)}${u!==c?` → ${n.colors.yellow(u)}`:""}${g.token!==l.token?" (new API token)":""}`),t.json({user:qs(g,e)})}else t.json({user:qs(l,e)});else zs(t,409,"USER_CHANGED",`The user "${c}" changed meanwhile; edit it again`)}),e.delete(`${Hs}/:name`,(e,t)=>{const s=String(e.params.name);a().remove(s)?(i.info(`${n.colors.blue("Removed user")} ${n.colors.yellow(s)}`),t.status(204).end()):zs(t,404,"NOT_FOUND",`There is no user named "${s}"`)})}(e.internalServer,{miAPI:s}),Ys({persist:r,miAPI:s,projectRoot:i,miUrl:a}),o},exports.urlReplacer=Ee,exports.zipDirectoryToBuffer=ss;
2
- //# sourceMappingURL=internal.middleware-BlM7gqkq.js.map