@metricinsights/pp-dev 1.5.0-beta.20 → 1.5.0-beta.22

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 (52) hide show
  1. package/README.md +15 -9
  2. package/dist/README.md +15 -9
  3. package/dist/cjs/auth.provider-CyXyBAm3.js +2 -0
  4. package/dist/cjs/auth.provider-CyXyBAm3.js.map +1 -0
  5. package/dist/cjs/cli.js +1 -1
  6. package/dist/cjs/{index-DFNyrsll.js → index-CeIQtamz.js} +2 -2
  7. package/dist/cjs/index-CeIQtamz.js.map +1 -0
  8. package/dist/cjs/index.js +1 -1
  9. package/dist/cjs/migrate-C1svbbPB.js +2 -0
  10. package/dist/cjs/{migrate-D_y8SIv9.js.map → migrate-C1svbbPB.js.map} +1 -1
  11. package/dist/cjs/package.json +1 -1
  12. package/dist/cjs/plugin.js +1 -1
  13. package/dist/cjs/request-capture.middleware-Jk6Vxx40.js +2 -0
  14. package/dist/cjs/request-capture.middleware-Jk6Vxx40.js.map +1 -0
  15. package/dist/cjs/{version-manifest-DsHoDq-U.js → version-manifest-C15hpGGV.js} +2 -2
  16. package/dist/cjs/{version-manifest-DsHoDq-U.js.map → version-manifest-C15hpGGV.js.map} +1 -1
  17. package/dist/cjs/version-plugin-DtPQBhEK.js +2 -0
  18. package/dist/cjs/{version-plugin-Cm56j0DZ.js.map → version-plugin-DtPQBhEK.js.map} +1 -1
  19. package/dist/esm/auth.provider-Cq0EuReh.js +2 -0
  20. package/dist/esm/auth.provider-Cq0EuReh.js.map +1 -0
  21. package/dist/esm/cli.js +1 -1
  22. package/dist/esm/index-DioJ4R68.js +2 -0
  23. package/dist/esm/index-DioJ4R68.js.map +1 -0
  24. package/dist/esm/index.js +1 -1
  25. package/dist/esm/migrate-FpJKfYgz.js +2 -0
  26. package/dist/esm/{migrate-BHq9PUZz.js.map → migrate-FpJKfYgz.js.map} +1 -1
  27. package/dist/esm/package.json +1 -1
  28. package/dist/esm/plugin.js +1 -1
  29. package/dist/esm/plugin.js.map +1 -1
  30. package/dist/esm/request-capture.middleware-B9t-px8Z.js +2 -0
  31. package/dist/esm/request-capture.middleware-B9t-px8Z.js.map +1 -0
  32. package/dist/esm/{version-manifest-CuZrGM-C.js → version-manifest-qxz5FXuG.js} +2 -2
  33. package/dist/esm/{version-manifest-CuZrGM-C.js.map → version-manifest-qxz5FXuG.js.map} +1 -1
  34. package/dist/esm/version-plugin-b2xMXK9M.js +2 -0
  35. package/dist/esm/{version-plugin-CbEJf2b3.js.map → version-plugin-b2xMXK9M.js.map} +1 -1
  36. package/dist/types/index.d.ts +3 -2
  37. package/package.json +1 -1
  38. package/dist/cjs/auth.provider-CnmH_J2r.js +0 -2
  39. package/dist/cjs/auth.provider-CnmH_J2r.js.map +0 -1
  40. package/dist/cjs/index-DFNyrsll.js.map +0 -1
  41. package/dist/cjs/migrate-D_y8SIv9.js +0 -2
  42. package/dist/cjs/request-capture.middleware-BUpxzWDS.js +0 -2
  43. package/dist/cjs/request-capture.middleware-BUpxzWDS.js.map +0 -1
  44. package/dist/cjs/version-plugin-Cm56j0DZ.js +0 -2
  45. package/dist/esm/auth.provider-B9ybFjL5.js +0 -2
  46. package/dist/esm/auth.provider-B9ybFjL5.js.map +0 -1
  47. package/dist/esm/index-ypcJ5r5C.js +0 -2
  48. package/dist/esm/index-ypcJ5r5C.js.map +0 -1
  49. package/dist/esm/migrate-BHq9PUZz.js +0 -2
  50. package/dist/esm/request-capture.middleware-VCmWYJoS.js +0 -2
  51. package/dist/esm/request-capture.middleware-VCmWYJoS.js.map +0 -1
  52. package/dist/esm/version-plugin-CbEJf2b3.js +0 -2
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("zlib"),t=require("./auth.provider-CnmH_J2r.js"),s=require("url"),r=require("axios"),n=require("node:http"),i=require("node:https"),a=require("./version-manifest-DsHoDq-U.js"),o=require("http-proxy-middleware"),c=require("node:string_decoder"),l=require("path"),d=require("fs"),u=require("crypto"),p=require("process"),h=require("os"),g=require("jszip"),m=require("child_process"),f=require("module"),y=require("node:crypto"),w=require("node:fs"),v=require("node:os"),b=require("node:path"),k=require("express"),$=require("node:net");var x="undefined"!=typeof document?document.currentScript:null;const S=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function A(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const s in e)t[s]=e[s];return t.default=e,Object.freeze(t)}const E=S(r),T=S(n),I=S(i),P=A(l),N=A(d),L=A(u),R=A(p),j=A(h),F=S(g),O=A(m),B=S(w),C=S(v),M=S(b),U=S(k),D=P.dirname(t.PP_DEV_CLIENT_ENTRY),_={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function H(e,t){const s=t.clientDir??D,r=new Set([`${t.name}.js`,`${t.name}.css`,`${t.name}.js.map`,`${t.name}.css.map`]);e.get(t.path,(e,r)=>{N.readFile(P.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)?N.readFile(P.join(s,i),(e,s)=>{e?n():(t.setHeader("Content-Type",_[P.extname(i)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(s))}):n()})}const V="/@pp-dev/inspector",q=new WeakMap;function z(e){const t=Array.isArray(e)?e[0]:e;return"string"==typeof t?t:void 0}function W(e){return Array.isArray(e)?e[0]??"":String(e??"")}function J(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`}function Z(e){return"string"==typeof e?e:void 0}function G(e,t){return"string"==typeof e?Buffer.from(e,t):e instanceof Uint8Array?Buffer.from(e):null}const K=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),X=new Map,Y=new Map;const Q=(e,t,s)=>{let r=X.get(e);if(!r){const t=/:\d+$/.test(e)?"":"(?::(?<port>\\d+))?";r=new RegExp(`(?<keep>!!)?(?<url>http(?<secure>s)?(?<slashes>:(?:\\\\)?/(?:\\\\)?/)${K(e)}${t})`,"gi"),X.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}`})},ee=(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},te=(e,t,s)=>{e.setHeader("location",t),e.statusCode=s,e.end()};function se(e){return e.split("?")[0]}class re{axios;constructor(e){this.axios=e}async checkAuth(e){return this.axios.get("/data/page/index/auth/info",{headers:Object.assign({},e,{accept:"text/html"}),maxRedirects:0}).then(()=>!0).catch(()=>!1)}}class ne extends re{getDownloadUrl(e){return`/admin/page/downloadassets/id/${e}`}getDownloadTemplateUrl(e){return`/admin/pagetemplate/downloadassets/id/${e}`}getUploadUrl(e){return`/admin/page/uploadassets/id/${e}`}getUploadTemplateUrl(e){return`/admin/pagetemplate/uploadassets/id/${e}`}async downloadPageAssets(e,t){return this.download(this.getDownloadUrl(e),t)}async uploadPageAssets(e,t,s){return this.upload(this.getUploadUrl(e),t,s)}async downloadTemplateAssets(e,t){return this.download(this.getDownloadTemplateUrl(e),t)}async uploadTemplateAssets(e,t,s){return this.upload(this.getUploadTemplateUrl(e),t,s)}async download(e,t){return this.axios.get(e,{withCredentials:!0,headers:Object.assign({},t,{accept:"*/*"}),responseType:"arraybuffer"}).then(e=>e.data)}async upload(e,t,s){const 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 ie extends ne{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 ae="Something went wrong when fetching page data",oe="Something went wrong when fetching page template data",ce="Something went wrong when fetching page variables",le=" The instance may be down or in maintenance mode. Please try again later.",de=[ae,oe,ce];function ue(){return new Error(`${ae}.${le}`)}function pe(){return new Error(`${oe}.${le}`)}function he(e){return e instanceof Error&&de.some(t=>e.message.includes(t))}class ge extends re{async getAll(e){const t=(await this.axios.get("/api/page",{withCredentials:!0,headers:Object.assign({},e,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"})})).data;if("object"!=typeof t||null===t||!Array.isArray(t.pages))throw ue();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 ue();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 ue();return s.page}}class me extends re{async getAll(e,t){const s=(await this.axios.get("/api/page_template",{withCredentials:!0,headers:Object.assign({},t,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"}),params:{internal_name:e}})).data;if("object"!=typeof s||null===s||!Array.isArray(s.page_templates))throw pe();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 pe();return s.page_template}}class fe extends re{async getById(e,t){const s=(await this.axios.get("/api/page_variable",{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"}),params:{page_id:e}})).data;if("object"!=typeof s||null===s)throw new Error(`${ce}.${le}`);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 ye(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 we(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 ve="metric_insights_session";function be(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 ke(e,t){return e?be(e.split(";"),t):void 0}function $e(e,t){if(void 0===e||"number"==typeof e)return;return be((Array.isArray(e)?e:[e]).map(e=>e.split(";",1)[0]),t)}function xe(e,t){return void 0===e?e:Array.isArray(e)?e.map(e=>we(e,t)):we(e,t)}const Se=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 Ae(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 Ee(e){const{status:t,message:s}=Ae(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 Te(e){const{status:t}=Ae(e);return 401===t||403===t||412===t}const Ie="[DEV PAGE. DO NOT DELETE]",Pe=new Map;const Ne=String.raw`[a-z](?:[a-z0-9\-]*[a-z0-9])?`,Le=new RegExp(`^(?:${Ne})$`),Re=".localhost";function je(e){return e?e.length>32?"The name must be at most 32 characters long":Le.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 Fe(e){if(!e)return;const t=e.toLowerCase().replace(/:\d+$/,"");if(!t.endsWith(Re))return;const s=t.slice(0,-10);return s&&!s.includes(".")?s:void 0}function Oe(e,t){const s=/:(\d+)$/.exec(e.headers.host??"")?.[1];return`${ye(e)?"https":"http"}://${t?`${t}.`:""}localhost${s?`:${s}`:""}`}const Be=new class{#e=new Map;#t=new Set;#s=new Set;#r=!1;#n=new Set;#i;#a=new Map;#o=new WeakMap;#c;useContext(e){void 0!==this.#c&&this.#c!==e&&this.clear(),this.#c=e}get context(){return this.#c}list(){return[...this.#e.values()]}get(e){return this.#e.get(e)}add(e){const t=je(e.name);if(t)throw new Error(t);if(this.#e.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.#a.delete(s.name),this.#e.set(s.name,s),this.#l(),s}replace(e,t){if(!this.#e.has(e))throw new Error(`There is no user named "${e}"`);const s=je(t.name);if(s)throw new Error(s);if(t.name!==e&&this.#e.has(t.name))throw new Error(`A user named "${t.name}" already exists`);const r=this.#i===e,n=[...this.#a].filter(([,t])=>t===e).map(([e])=>e);let i;this.#r=!0;try{this.remove(e),i=this.add(t)}catch(s){throw this.#r=!1,this.#l(),s}finally{this.#r=!1}for(const s of t.name===e?n:[...n,e])this.#a.set(s,i.name);return r&&(this.#i=i.name),this.#l(),i}#l(){this.#r||this.#s.forEach(e=>e())}renamedTo(e){return this.#a.get(e)}remove(e){const t=this.#e.get(e);if(!t)return!1;this.#i===e&&(this.#i=void 0);for(const[t,s]of this.#a)s===e&&this.#a.delete(t);return this.#e.delete(e),this.#t.forEach(e=>e(t)),this.#l(),!0}clear(){for(const e of[...this.#e.keys()])this.remove(e)}onRemove(e){return this.#t.add(e),()=>{this.#t.delete(e)}}onSessionChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}sessionChanged(e){this.#e.get(e.name)===e&&this.#n.forEach(t=>t(e))}onChange(e){return this.#s.add(e),()=>{this.#s.delete(e)}}get defaultUser(){return void 0===this.#i?void 0:this.#e.get(this.#i)}setDefaultUser(e){if(void 0===e)return void(this.#i=void 0);const t=this.#e.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.#i=e}resolve(e){if(this.#o.has(e))return this.#o.get(e);const t=Fe(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.#e.get(t)??this.#e.get(this.#a.get(t)??"");s=e?{key:e.name,user:e}:void 0}return this.#o.set(e,s),s}};const Ce=/(?:^|\/\/[^/]+)\/(?:login|auth\/saml\/login)(?:[/?#]|$)/i;function Me(e){return(e??"").split(";").map(e=>e.trim()).filter(e=>e&&e.split("=",1)[0].trim()!==ve)}function Ue({statusCode:e=200,headers:t}){return 401===e||412===e||e>=300&&e<400&&Ce.test(String(t.location??""))}class De{#e;#d;#u=t.createLogger();#p=new WeakMap;#h=new WeakMap;#g=new WeakMap;#m=new WeakMap;constructor(e,t){this.#e=e,this.#d=t}isLeftBehindRequest(e,t,s){const r=Fe(t.headers.host)===e.name?ke(t.headers.cookie,ve):s;return void 0!==r&&this.#f(e,r)}observe(e,t,s,r){if("session"!==e.kind||this.#e.get(e.name)!==e)return;const n=Fe(t.headers.host)===e.name,i=n?ke(t.headers.cookie,ve):r,a=$e(s.headers["set-cookie"],ve),o=this.#g.get(e);let c,l,d=n;return a&&a!==i?(c=a,l=i):n&&i!==e.session&&!Ue(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&&Ue(s)&&i===e.session&&this.#y(e,`MI turned away ${t.method} ${t.url}`),c&&c!==e.session&&c!==this.#p.get(e)&&c!==this.#h.get(e)&&!this.#f(e,c)?this.#w(e,c,l,d):void 0}async#w(e,s,r,n){let i;this.#p.set(e,s);try{i=await this.#d(s)}catch(i){return this.#p.get(e)===s&&(this.#p.delete(e),this.#g.set(e,{session:s,replaced:r,ownHost:n,retryAt:Date.now()+5e3})),void this.#u.warn(t.colors.yellow(`Could not check the MI session of user ${e.name}: ${String(i)}`))}if(this.#p.get(e)===s&&this.#e.get(e.name)===e)if(this.#p.delete(e),this.#g.get(e)?.session===s&&this.#g.delete(e),i){if(this.#f(e,s)||void 0!==r&&this.#f(e,r))return;const a="active"===e.state;n&&(this.#v(e),void 0!==r&&r!==s&&this.#v(e,r)),this.#g.delete(e),Object.assign(e,{state:"active",session:s,miUser:i}),this.#h.delete(e),this.#e.sessionChanged(e),a||this.#u.info(`${t.colors.blue("User")} ${t.colors.yellow(e.name)} ${t.colors.blue("logged in")} (MI user ${i.id}${i.username?`, ${i.username}`:""})`)}else this.#h.set(e,s),"active"===e.state&&r===e.session&&this.#y(e,"MI started a guest session")}#f(e,t){return"active"===e.state&&Boolean(this.#m.get(e)?.has(t))}#v(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)}#y(e,s){this.#v(e),e.state="expired",e.session=void 0,this.#p.delete(e),this.#g.delete(e),this.#e.sessionChanged(e),this.#e.defaultUser===e&&this.#e.setDefaultUser(void 0),this.#u.warn(`${t.colors.yellow(`The MI session of user ${e.name} ended`)} (${s}). Log in again on its host.`)}}async function _e(e,t){try{const s=await e.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",...t},!0,{quiet:!0}),r=s.data?.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(Te(e))return{miUser:void 0,refused:Ee(e).userFriendlyMessage};throw e}}async function He(e,t){try{const s=await _e(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: ${Ee(e).userFriendlyMessage}`}}}const Ve=/^(https?:\/\/)([^/]+)(\/.*)?$/i,qe="X-PP-Proxy";const ze=/^\/login(?:\/|$)/i,We="/auth/saml/login";const Je=/^\/auth\/(?:index\/)?logout(?:[/?#]|$)/i;const Ze=new WeakMap,Ge=new WeakMap;const Ke=[/^text\//,/^application\/(?:[\w.-]+\+)?(?:json|xml)$/,/^application\/(?:x-)?(?:java|ecma)script$/,/^[\w.-]+\/[\w.-]+\+(?:json|xml)$/];function Xe(e){const t=e.split(";",1)[0].trim().toLowerCase();return Ke.some(e=>e.test(t))}const Ye=/[\w.:/\\!-]/;function Qe(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&&Xe(s)}function et(e){return async(t,s,r)=>{const n=e&&Qe(t.headers);r.statusCode=t.statusCode??r.statusCode,t.statusMessage&&(r.statusMessage=t.statusMessage),r.setHeader(qe,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 c.StringDecoder("utf8");let a="",o=!1;const l=s=>{if(!s)return;r.write(e(Buffer.from(s,"utf8"),"utf8"))||o||(o=!0,t.pause(),r.once("drain",()=>{o=!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(!Ye.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()})}}const tt=/\.(?:[a-z0-9]+)$/i,st=6e5,rt=104857600,nt=1e3,it=10485760;const at=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=st){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)}}(rt,nt),ot=new Set,ct=new Map;function lt(e){at.clear(),ct.clear(),ot.forEach(e=>e()),t.createLogger().info(t.colors.blue(`Proxy cache cleared: ${e}`))}const dt=new WeakSet;function ut(e,t){return t?e.startsWith(`@${t}@`):!e.startsWith("@")}function pt(e,s){if(e){for(const t of at.keys())ut(t,e)&&at.del(t);ct.delete(e),t.createLogger().info(t.colors.blue(`Proxy cache cleared for ${e}: ${s}`))}else lt(s)}function ht(e,t,s){const r=function(e){return Ze.get(e)}(e);if(void 0!==r){const e=ct.get(s),t=void 0!==e&&r!==e;return ct.set(s,r),t?"personal access token changed":void 0}const n=$e(t.getHeader("set-cookie"),ve);return void 0!==n&&n!==ke(e.headers.cookie,ve)?"MI session changed":void 0}function gt(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)}const mt=new Map;function ft(e){const t=mt.get(e);return t?Date.now()-t.timestamp>18e4?(mt.delete(e),null):t.data:null}function yt(e,t){mt.set(e,{timestamp:Date.now(),data:t})}var wt;wt=()=>mt.clear(),ot.add(wt);let vt=!1;function bt(e){vt||(vt=!0,e.info(t.colors.blue("Clearing proxy cache after successful login")),at.clear())}function kt(){vt=!1,t.authProvider.reset()}const $t="/home?proxyRedirect=";function xt(e){const t=e.headers??{},s=Boolean(Fe(e.headers?.host));if(!s&&!Be.resolve(e)?.user)return t;const{cookie:r,authorization:n,token:i,...a}=t;return s||void 0===r?a:{...a,cookie:r}}async function St(e,s,r,n,i,a){const{appId:o,redirectOnAuthFailure:c,redirectUrl:l}=s;if(void 0===o){const e=new Error("Custom App ID is required for page info only mode");return a.error(t.colors.red(e.message)),i(e)}const d=xt(r);a.info(t.colors.green("Start loading page info"));try{const s=`pageInfo:${o}`;return ft(s)?(a.info(t.colors.green("Page info loaded from cache")),i()):(await e.getPageInfo(o,d),bt(a),yt(s,{success:!0}),t.authProvider.updateState({isAuthenticated:!0}),a.info(t.colors.green("Page info loaded successfully")),i())}catch(e){return kt(),Et(e,c??!0,l||`${$t}${encodeURIComponent("/")}`,n,i,a,"Page info")}}async function At(e,s,r,n,i,a){const{templateLess:o,appId:c,redirectOnAuthFailure:l,redirectUrl:d}=s,u=xt(r);a.info(t.colors.green("Start loading page data"));try{const s=`pageData:${o}:${c}`;if(ft(s))return a.info(t.colors.green("Page data loaded from cache")),i();const r=o||void 0===c?e.getPageTemplate(u):e.getPageVariables(c,u);return await r,bt(a),yt(s,{success:!0}),a.info(t.colors.green("Page data loaded successfully")),i()}catch(e){return kt(),Et(e,l??!0,d||`${$t}${encodeURIComponent("/")}`,n,i,a,"Page data")}}function Et(e,s,r,n,i,a,o){if(function(e){return null!==e&&"object"==typeof e&&Te(e)}(e)&&(a.info(t.colors.red(`${o} loading failed. Not authorized`)),s)){const e=`${r}`;return a.info(t.colors.yellow(`Redirecting to: ${e}`)),te(n,e,302)}const c=e instanceof Error?e.message:String(e);return a.info(t.colors.red(`${o} loading failed. Error: ${c}`)),i(e)}async function Tt(e){const t=new F,s=async r=>{const n=await d.promises.readdir(r,{withFileTypes:!0});for(const i of n){const n=P.join(r,i.name);if(i.isDirectory())await s(n);else if(i.isFile()){const s=P.relative(e,n).replace(/\\/g,"/");t.file(s,await d.promises.readFile(n))}}};return await s(e),await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"})}async function It(e,t){const s=await F.loadAsync(await d.promises.readFile(e),{createFolders:!1}),r=P.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=P.resolve(r,t);if(s!==r&&!s.startsWith(r+P.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 d.promises.mkdir(r,{recursive:!0});for(const e of n){const t=P.resolve(r,e.unsafeOriginalName??e.name);e.dir?await d.promises.mkdir(t,{recursive:!0}):(await d.promises.mkdir(P.dirname(t),{recursive:!0}),await d.promises.writeFile(t,await e.async("nodebuffer")))}}const Pt=6e5;function Nt(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&&O.spawnSync("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore"})}function Lt(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=O.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,Nt(u,"SIGKILL",d)):(p=e,t?(Nt(u,"SIGTERM",d),h=setTimeout(()=>{h=void 0,Nt(u,"SIGKILL",d)},o)):Nt(u,"SIGKILL",d))},m=()=>g(`${e} was stopped`,!1),f=void 0===i?void 0:setTimeout(()=>g(`${e} timed out after ${Math.round(i/1e3)} s`,!0),i);a?.addEventListener("abort",m,{once:!0});const y=e=>{clearTimeout(f),clearTimeout(h),a?.removeEventListener("abort",m),d&&Nt(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))})}async function Rt(e,s={}){let r;try{const t=f.createRequire(P.join(e,"package.json")).resolve("next/package.json");r=P.resolve(P.dirname(t),"dist/bin/next")}catch{throw new Error(`Unable to resolve the "next" binary from ${e}. Is Next.js installed?`)}await Lt("next build",process.execPath,[r,"build"],{...s,cwd:e,env:Object.assign({},process.env,{NODE_ENV:"production",[t.PP_DEV_NEXT_BUILD_ENV_VAR]:"1"})})}const jt="pageName",Ft="date",Ot=P.dirname("undefined"!=typeof __filename&&__filename||s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:x&&"SCRIPT"===x.tagName.toUpperCase()&&x.src||new URL("request-capture.middleware-BUpxzWDS.js",document.baseURI).href)),Bt=P.resolve(Ot,"..",".."),Ct=Buffer.from([80,75,3,4]),Mt=20,Ut=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const Dt="sync-service.meta.json",_t="BUILD-MANIFEST.json",Ht="__template_variables.json";class Vt{server;opts;eventMap;logger;syncInFlight=null;syncActionResolvers=new Map;constructor(e,s){this.server=e,this.opts=s||{},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=t.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(!1)})}dispose(){this.clearAllPendingSyncActions(!1),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,e)}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)}async requestSyncAction(e,t){const s=u.randomUUID(),r=this.opts.syncActionTimeoutMs??12e4;return await new Promise(n=>{const i=()=>this.resolveSyncAction(s,!1),a=setTimeout(i,r),{socket:o}=t;o?.once("close",i),this.syncActionResolvers.set(s,{resolve:n,timeoutId:a,cleanup:()=>o?.off("close",i)}),o&&o.readyState!==o.OPEN?i():t.send("template:sync:action-required",{...e,requestId:s})})}async onTemplateSync(e,s){if(this.syncInFlight)return this.logger.warn(t.colors.yellow("Template sync requested while another one is running; ignored")),void this.sendSyncResponse(s,{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 r=this.runTemplateSync(e,s);this.syncInFlight=r;try{await r}finally{this.syncInFlight=null}}async runTemplateSync(e,s){if(!this.opts.distService||!this.opts.miAPI)return this.sendSyncResponse(s,{error:"Dist service or MiAPI is not defined"}),void this.logger.error(t.colors.red("Dist service or MiAPI is not defined"));{const{distService:e,miAPI:n}=this.opts;try{if(this.server.config.clientInjectionPlugin?.v7Features){if(!n?.isV710OrHigher)return void this.sendSyncResponse(s,{error:"This feature is available only for MI v7.1.0 or higher",config:{canSync:!1}});s.send("client:config:update",{config:{canSync:!0}})}const i=await(n?.getAssets().catch(async e=>{if(r.isAxiosError(e)){if("SESSION_EXPIRED"===Ee(e).code){this.logger.info(t.colors.yellow("Session expired - attempting to validate credentials"));try{const e=await(n?.validateCredentials());e&&!e.isValid?(this.logger.error(t.colors.red(`Authentication error: ${e.error}`)),this.sendSyncResponse(s,{error:e.error??"Authentication failed",code:e.code,refresh:!0})):(this.logger.info(t.colors.yellow("Session expired")),this.sendSyncResponse(s,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0}))}catch(e){this.logger.info(t.colors.yellow("Session expired")),this.sendSyncResponse(s,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0})}return e}if(e.cause instanceof Error&&("ECONNRESET"===e.cause.code||"ENOTFOUND"===e.cause.code))return this.logger.info(t.colors.yellow("Server in maintenance mode, VPN connection is needed or no internet connection")),this.sendSyncResponse(s,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e;const r=e.response?.status;if(502===r||503===r||504===r)return this.logger.info(t.colors.yellow(`Server in maintenance mode or unreachable (HTTP ${r}); VPN may be required`)),this.sendSyncResponse(s,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e}if(he(e))return this.logger.info(t.colors.yellow("Server in maintenance mode or non-JSON page / page-template API response (unavailable HTML body)")),this.sendSyncResponse(s,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e;throw e}));if(i instanceof Error)return;let a;if(i){const r=await(e?.analyzeBackup(i).catch(e=>"Backup file is not a ZIP file"===e.message?(this.logger.error(t.colors.red("Backup file is not a ZIP file")),e):e));if(r instanceof Error)a=r;else if(r){await(e?.saveBackup(i,r));const n=0===r.unknownFiles.length&&1===r.versionManifestHashMismatches.length&&P.basename(r.versionManifestHashMismatches[0].relativePath)===Ht,o=r.versionManifestHashMismatches,c=o.filter(e=>P.basename(e.relativePath)===Ht),l=o.filter(e=>P.basename(e.relativePath)!==Ht),d=!n&&c.length>0&&l.length>0,u=n?[]:l.map(e=>e.relativePath),p=async()=>{if(!r.templateVariables||!e)return;const{templateVariables:t}=r;if(await e.getPublicTemplateVariablesHash()!==t.actualHash){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"},s)&&await e.saveTemplateVariablesFile(t.content)}};if(r.unknownFiles.length>0){if(!await this.requestSyncAction({title:"Unknown files found in backup",content:`Backup contains files not listed in VERSION: ${r.unknownFiles.join(", ")}. Continue sync or cancel?`,confirmText:"Continue sync",cancelText:"Cancel sync"},s))return this.sendSyncResponse(s,{cancelled:!0,message:"Sync cancelled by user. Backup was saved."}),void this.logger.info(t.colors.yellow("Sync cancelled by user"))}if(d&&await p(),!n&&u.length>0){const e=40,r=u,n=r.slice(0,e),i=r.length-n.length,a=n.map(e=>`• ${e}`).join("\n"),o=i>0?`\n... and ${i} more file${1===i?"":"s"}`:"";if(!await this.requestSyncAction({title:"VERSION manifest out of date",content:`These files no longer match the hashes recorded in the VERSION manifest:\n\n${a}${o}\n\nCancel sync, or override and continue using the files on disk?`,confirmText:"Override and continue",cancelText:"Cancel sync"},s))return this.sendSyncResponse(s,{cancelled:!0,message:"Sync cancelled by user. Backup was saved."}),void this.logger.info(t.colors.yellow("Sync cancelled by user"))}if(!n&&r.buildManifestMismatch&&0===r.versionManifestHashMismatches.length){const{expected:e,actual:n}=r.buildManifestMismatch;if(!await this.requestSyncAction({title:"Build manifest fingerprint mismatch",content:`The recomputed backup fingerprint does not match BUILD-MANIFEST.json.\nManifest: ${e.slice(0,12)}...\nComputed: ${n.slice(0,12)}...\nContinue sync anyway?`,confirmText:"Continue sync",cancelText:"Cancel sync"},s))return this.sendSyncResponse(s,{cancelled:!0,message:"Sync cancelled by user. Backup was saved."}),void this.logger.info(t.colors.yellow("Sync cancelled by user"))}d||await p(),a=await(e?.buildNewAssets())}}else a=await(e?.buildNewAssets());if(!(a&&a instanceof Buffer))return a instanceof Error?(this.sendSyncResponse(s,{error:a.message}),void this.logger.error(t.colors.red(a.message))):(this.sendSyncResponse(s,{error:"Failed to build new assets"}),void this.logger.error(t.colors.red("Failed to build new assets")));{if(e.stopped)return this.sendSyncResponse(s,{error:"Sync stopped: the dev server is shutting down."}),void this.logger.warn(t.colors.yellow("Sync stopped before the upload: the dev server is shutting down"));const r=await(n?.updateAssets(a));if("OK"===r?.status){const r=e?.getBackupMeta(),n=r?.lastBackupDate?new Date(r.lastBackupDate):new Date;this.sendSyncResponse(s,{syncedAt:(Number.isNaN(n.getTime())?new Date:n).toISOString(),currentHash:r?.lastBackupHash??"",backupFilename:r?.lastBackupName??""}),this.logger.info(t.colors.green("Template synced"))}else this.sendSyncResponse(s,{error:"Failed to update assets"}),this.logger.error(t.colors.red("Failed to update assets"))}}catch(e){const r=e instanceof Error?e.message:"Template sync failed";return this.logger.error(t.colors.red(`Template sync failed: ${r}`)),void this.sendSyncResponse(s,{error:r,code:"SYNC_FAILED"})}}}async onPageVariablesReload(e,s){const{miAPI:r}=this.opts;if(!r)return s.send("page-variables:reload:response",{error:"MiAPI is not defined"}),void this.logger.error(t.colors.red("MiAPI is not defined"));try{const e=await r.reloadPageVariables();s.send("page-variables:reload:response",{ok:!0,count:e?e.length:0,skipped:null===e}),this.logger.info(t.colors.green("Page variables reloaded"))}catch(e){const r=e instanceof Error?e.message:"Reload variables failed";this.logger.error(t.colors.red(`Reload variables failed: ${r}`)),s.send("page-variables:reload:response",{error:r})}}}const qt=["text","select","multiselect","file","list","color","boolean"];function zt(e){return qt.includes(e)}const Wt=["true","false","Y","N","1","0"],Jt=/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function Zt(e,t){return e.id===t||e.text===t}function Gt(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 Kt(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 Jt.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(!s.options?.length)return[];const r=s.options.map(Gt);return r.some(e=>Zt(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(!s.options?.length)return[];const r=s.options.map(Gt),n=i.split(",").map(e=>e.trim()).filter(e=>!r.some(t=>Zt(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 Xt(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(...Kt(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 Yt(e,t){const s=[];switch(e.tag_type){case"boolean":Wt.includes(t)||s.push({name:e.name,severity:"warning",message:`Value "${t}" is not a recognized boolean encoding (expected one of ${Wt.join(", ")}).`});break;case"list":try{const r=JSON.parse(t);Array.isArray(r)?s.push(...Xt(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(Gt),n=("multiselect"===e.tag_type?t.split(",").map(e=>e.trim()):[t]).filter(e=>!r.some(t=>Zt(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 Qt(e,t){switch(e.tag_type){case"boolean":return Wt.includes(t)?null:`Not a recognized boolean value ("${t}").`;case"color":return""===t||Jt.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 es="/@pp-dev/variables-editor",ts=/^[A-Za-z0-9_\s-]+$/,ss="Dist service or MiAPI is not defined",rs=new WeakMap;async function ns(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 is(e){return e?(await ns(e))?.schema??null:null}function as(e,t,s){const r=rs.get(e);if(r)return void(r.deps=t);const n={deps:t};rs.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:ss});const r=await ns(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:ss});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&&!zt(e.tag_type)&&c.push(`"${e.name}" has an unrecognized tag_type "${e.tag_type}".`),ts.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 ${Ht}.`,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 is(s),n=await r.getLivePageVariables(),i=function(e,t){const s=new Map((e?.tags??[]).map(e=>[e.name,e])),r=new Map(t.map(e=>[e.name,e.value])),n=new Set([...s.keys(),...r.keys()]);return Array.from(n).map(e=>({name:e,value:r.get(e)??s.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)try{const e=await is(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(...Yt(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:"Request body must be { tags: {name, value}[] }."})}),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.find(e=>e.internal_name===s.internalPageName)??null,n=e.filter(e=>e.internal_name!==s.internalPageName).map(e=>({id:e.id,name:e.name,internal_name:e.internal_name,sameTemplate:!!r&&(null!=r.template_id?e.template_id===r.template_id:!!r.template&&e.template===r.template)}));t.json({pages:n,currentPageName:r?.name??null})}catch(e){t.status(502).json({error:"Failed to fetch the page list.",details:e instanceof Error?e.message:String(e)})}}),e.get("/@api/variables/import-plan/:pageId",async(e,t)=>{const{distService:s,miAPI: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 is(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=Qt(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)})}}),H(e,{path:es,name:"variables-editor",clientDir:s,values:()=>({templateLess:String(Boolean(n.deps.miAPI.isTemplateLess))})})}const os="/@api/users",cs=new WeakMap;function ls(e,t){const s=Oe(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 ds(e,t,s,r){e.status(t).json({error:r,code:s})}function us(e){let s;try{s=JSON.parse(B.readFileSync(e,"utf-8"))}catch(s){return"ENOENT"!==s.code&&t.createLogger().warn(t.colors.yellow(`Could not read the saved users from ${e}: ${String(s)}`)),[]}const r=s&&"object"==typeof s&&!Array.isArray(s)?s.users:void 0;return(Array.isArray(r)?r:[]).filter(e=>"string"==typeof e?.name&&"string"==typeof e.token&&Boolean(e.token))}const ps=new WeakMap,hs=new WeakMap;function gs(e){ps.delete(e),hs.get(e)?.(),hs.delete(e)}async function ms(e,s){const r=function(e,t,s=C.homedir()){const r=y.createHash("sha256").update(`${M.resolve(e)}\n${t.replace(/\/+$/,"")}`).digest("hex").slice(0,16);return M.join(s,".pp-dev","users",`${r}.json`)}(s.projectRoot,s.miUrl,s.homeDir),n={project:M.resolve(s.projectRoot),miUrl:s.miUrl},i=t.createLogger();if(ps.get(e)===r)return;gs(e),ps.set(e,r);const a=us(r);let o=!0,c=!1,l=e.list().some(e=>"token"===e.kind&&e.token);const d=new Set,u=new Set,p=()=>{const s=e.list(),a=s.filter(e=>"token"===e.kind&&e.token).map(e=>({name:e.name,token:e.token})),o=new Set(s.map(e=>e.name)),c=us(r).filter(e=>!o.has(e.name)&&!u.has(e.name));try{!function(e,t,s){const r={version:1,...s,users:t},n=`${e}.${process.pid}.tmp`;B.mkdirSync(M.dirname(e),{recursive:!0,mode:448}),B.writeFileSync(n,`${JSON.stringify(r,null,2)}\n`,{mode:384}),B.renameSync(n,e),B.chmodSync(e,384)}(r,[...a,...c],n)}catch(e){i.warn(t.colors.yellow(`Could not save the users to ${r}: ${String(e)}`))}},h=e.onRemove(t=>{ps.get(e)===r&&(u.add(t.name),o&&d.add(t.name))}),g=e.onChange(()=>{ps.get(e)===r&&(o?l||=!c:p())});hs.set(e,()=>{h(),g()});try{const n=await Promise.all(a.map(e=>s.checkToken(e.token)));if(ps.get(e)!==r)return;a.forEach((s,r)=>{if(je(s.name)||e.get(s.name)||d.has(s.name))return;const a=n[r];c=!0;try{e.add({name:s.name,kind:"token",token:s.token,...a.ok?{miUser:a.miUser}:{},...!a.ok&&a.rejected?{state:"expired"}:{}})}finally{c=!1}a.ok||i.warn(t.colors.yellow(`Restored user ${s.name}: ${a.message}`))})}finally{o=!1}l&&ps.get(e)===r&&p(),a.length&&i.info(`${t.colors.blue("Restored")} ${a.length} ${t.colors.blue("saved user(s) from")} ${r}`)}function fs(e){const s=`${M.resolve(e.projectRoot)}\n${e.miUrl.replace(/\/+$/,"")}`;Be.context!==s&&(gs(Be),Be.useContext(s)),e.persist?e.miAPI.personalAccessToken?ms(Be,{projectRoot:e.projectRoot,miUrl:e.miUrl,checkToken:t=>He(e.miAPI,t)}).catch(e=>{t.createLogger().warn(t.colors.yellow(`Could not restore the saved users: ${String(e)}`))}):t.createLogger().warn(t.colors.yellow("users.persist is on, but users need your own API token (mi.token or MI_ACCESS_TOKEN).")):gs(Be)}const ys=new Set(["GET","HEAD","OPTIONS"]);function ws(e,t=[]){const s=e.headers.origin,r=e.headers.host;if("string"==typeof s){if("null"===s)return'Origin "null" (a sandboxed or file:// page)';let e;try{e=new URL(s)}catch{return`unreadable Origin "${s}"`}if("localhost"===(n=e.hostname)||n.endsWith(".localhost")||"[::1]"===n||/^127(?:\.\d{1,3}){3}$/.test(n)||!0!==t&&t.includes(e.hostname))return null;const i=r?function(e,t){try{return new URL(`${e}//${t}`).host}catch{return}}(e.protocol,r):void 0;return i&&e.host===i?null:`Origin ${e.origin} is neither this dev server (${r??"no Host"}) nor this machine`}var n;const i=e.headers["sec-fetch-site"];return ys.has((e.method??"GET").toUpperCase())||"cross-site"!==i?null:"sent from a cross-site page"}const vs="10mb",bs=(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 (${vs}).`:`The request body could not be read: ${e.message}`;s.status(n).json({error:i})};function ks(e){return(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0)+512}function $s(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}}const xs="<redacted>",Ss=new RegExp(`(^|;\\s*)(${ve}=)[^;]*`,"gi"),As=new RegExp(`^(\\s*${ve}=)[^;]*`,"i");function Es(e){const t={...e};if("string"==typeof t.authorization){const[e,s]=t.authorization.split(/\s+/,2);t.authorization=void 0===s?xs:`${e} ${xs}`}return void 0!==t.token&&(t.token=xs),"string"==typeof t.cookie&&(t.cookie=t.cookie.replace(Ss,`$1$2${xs}`)),t}function Ts(e){const t={...e},s=t["set-cookie"],r=e=>e.replace(As,`$1${xs}`);return Array.isArray(s)?t["set-cookie"]=s.map(r):"string"==typeof s&&(t["set-cookie"]=r(s)),t}const Is=/^\/(?:login|auth)(?:[/?#]|$)/i,Ps=/pass(?:word|wd|code)?|pwd|secret|token|otp|mfa|2fa/i;function Ns(e,t){return Array.isArray(e)?e.map(e=>Ns(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,s])=>Ps.test(e)?(t.any=!0,[e,xs]):[e,Ns(s,t)])):e}function Ls(e,t,s){if(!s)return s;if(Is.test(e))return Buffer.from(xs);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=>Ps.test(e));return t.forEach(t=>e.set(t,xs)),t.length?Buffer.from(e.toString()):s}if("application/json"===r||r.endsWith("+json")){const e={any:!1},t=Ns(JSON.parse(s.toString("utf8")),e);return e.any?Buffer.from(JSON.stringify(t)):s}}catch{}return s}const Rs=["/@","/_next/","/__nextjs_"],js=new Set(["/favicon.ico","/installHook.js.map"]);exports.DistService=class{root;backupFolder;backupNameTemplate;dateFormat;pageName;currentMeta=null;distZipFolder;distZipFilename;versionFileTemplate;buildInputFolder;nextBuild;maxBackups;buildTimeoutMs;metaDir;builds=new AbortController;metaLoaded;logger;constructor(e,s){this.pageName=e;const{root:r=R.cwd(),backupFolder:n="backups",distZipFolder:i=P.resolve(r,"dist-zip"),distZipFilename:a=t.createDefaultZipFileName(this.pageName),backupNameTemplate:o=`{${jt}}-{${Ft}}.zip`,versionFileTemplate:c="VERSION-v{packageversion}-{currentDate}.json",buildInputFolder:l,dateFormat:d=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,""),nextBuild:u,maxBackups:p=Mt,buildTimeoutMs:h=Pt,metaDir:g}=s||{};this.root=r,this.backupFolder=P.resolve(r,n),this.backupNameTemplate=o,this.dateFormat=d,this.distZipFolder=i,this.distZipFilename=t.normalizeRelativeOutputPath(a,"ZIP output file name"),this.versionFileTemplate=t.normalizeRelativeOutputPath(c,"VERSION file name template"),this.buildInputFolder=l,this.nextBuild=u,this.maxBackups="number"==typeof p&&Number.isInteger(p)&&p>0?p:1/0,this.buildTimeoutMs=h,this.metaDir=void 0===g?P.join(this.backupFolder,".pp-dev-meta"):P.resolve(r,g),this.logger=t.createLogger(),this.metaLoaded=this.loadMeta()}stopBuilds(){this.builds.abort()}async checkMeta(){await d.promises.mkdir(this.metaDir,{recursive:!0}),await d.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(t.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 d.promises.readFile(P.join(this.metaDir,Dt),{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await d.promises.writeFile(P.join(this.metaDir,Dt),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=P.resolve(this.backupFolder,e);try{return await d.promises.stat(t),t}catch{return null}}backupName(e,t=new Date){return this.backupNameTemplate.replace(`{${jt}}`,e).replace(`{${Ft}}`,this.dateFormat(t))}getBackupMeta(){return this.currentMeta}async pruneBackups(e){if(Number.isFinite(this.maxBackups))try{const s=function(e,t,s){const r=s.split(/(\d+)/).map((e,t)=>t%2==1?"\\d+":Ut(e)).join(""),n=[{token:`{${jt}}`,pattern:Ut(t)},{token:`{${Ft}}`,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+=Ut(e.slice(a,r))+s,a=r+t.length;return new RegExp(`${i}${Ut(e.slice(a))}$`)}(this.backupNameTemplate,this.pageName,this.dateFormat(new Date)),r=new Set([e]),n=await d.promises.readdir(this.backupFolder,{withFileTypes:!0}),i=(await Promise.all(n.filter(e=>e.isFile()&&s.test(e.name)).map(async e=>({name:e.name,mtimeMs:(await d.promises.stat(P.resolve(this.backupFolder,e.name))).mtimeMs})))).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.name.localeCompare(e.name)),a=i.filter(e=>r.has(e.name)).length,o=i.filter(e=>!r.has(e.name)).slice(Math.max(0,this.maxBackups-a));for(const e of o)await d.promises.unlink(P.resolve(this.backupFolder,e.name));o.length>0&&this.logger.info(t.colors.gray(`[DistService] Deleted ${o.length} old backup(s), keeping the latest ${this.maxBackups}`))}catch(e){this.logger.warn(t.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 t.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 d.promises.readdir(t,{withFileTypes:!0});if(1!==e.length||!e[0]?.isDirectory())return t;t=P.join(t,e[0].name)}}async listFilesRecursive(e){const t=await d.promises.readdir(e,{withFileTypes:!0}),s=[];for(const r of t){const t=P.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 L.createHash("sha256").update(t).digest("hex")}buildBackupFingerprint(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("\n");return L.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===Ht}async pickTemplateVariablesFromBackupZip(e,t){const s=e.find(e=>P.basename(e)===Ht);if(!s)return null;const r=P.join(t,s),n=await d.promises.readFile(r);return{relativePath:s,content:n,actualHash:L.createHash("sha256").update(n).digest("hex"),manifestHash:null}}async resolveBackupAnalysisFromZip(e){const s=await d.promises.mkdtemp(P.join(j.tmpdir(),"pp-dev-backup-")),r=P.join(s,"backup.zip"),n=P.join(s,"extracted");try{await d.promises.mkdir(n,{recursive:!0}),await d.promises.writeFile(r,e),await It(r,n);const s=await this.normalizeExtractedRootDir(n),i=(await this.listFilesRecursive(s)).map(e=>this.pathToPosix(P.relative(s,e))),a=i.filter(e=>P.basename(e)===_t);if(a.length>1)throw new Error(`Expected at most one ${_t} in backup ZIP, found ${a.length}`);const o=1===a.length?a[0]:null;let c=null;if(o){const e=P.join(s,o);if(c=JSON.parse(await d.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 l=null;if(c){const e=this.pathToPosix(c.versionFile.trim()),t=i.filter(t=>t===e),s=i.filter(t=>P.basename(t)===P.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&&(l=r[0]),!0===c.compat?.versionFileRequired&&null===l)throw new Error(`Build manifest requires version file "${c.versionFile}", but it is missing in backup ZIP`)}else{const e=this.versionFileTemplateMatcher(),t=i.filter(t=>e.test(P.basename(t)));if(t.length>1)throw new Error(`Expected exactly one version file matching template "${this.versionFileTemplate}" in backup ZIP, found ${t.length}`);1===t.length&&(l=t[0])}const u={};let p=null,h=null;const g={};let m=[];if(l){const e=P.join(s,l),r=JSON.parse(await d.promises.readFile(e,"utf-8"));if(!r?.files||"object"!=typeof r.files)throw new Error("VERSION manifest files map is missing or invalid");if("string"!=typeof r.checksum||!r.checksum)throw new Error("VERSION manifest checksum is missing or invalid");h=r.checksum;for(const[e,t]of Object.entries(r.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)!==r.checksum)throw new Error("VERSION manifest checksum does not match its files map");for(const[e,t]of Object.entries(u)){const r=P.join(s,e),n=await d.promises.readFile(r).catch(()=>null);if(!n)throw new Error(`VERSION manifest references missing file: ${e}`);const i=L.createHash("sha256").update(n).digest("hex");g[e]=i,i!==t&&m.push({relativePath:e,expected:t,actual:i}),this.isTemplateVariablesBasename(P.basename(e))&&(p={relativePath:e,content:n,actualHash:i,manifestHash:t})}m.length>0&&this.logger.warn(t.colors.yellow(`[DistService] VERSION manifest hash mismatch for ${m.length} file(s) (confirm in UI): ${m.map(e=>e.relativePath).join(", ")}`))}const f=new Set(m.map(e=>e.relativePath)),y={},w=[];for(const e of i){if(e===o)continue;if(l&&e===l)continue;if(l&&Object.prototype.hasOwnProperty.call(y,e))continue;const t=P.join(s,e),r=await d.promises.readFile(t),n=L.createHash("sha256").update(r).digest("hex");l&&Object.prototype.hasOwnProperty.call(u,e)?y[e]=f.has(e)?g[e]:u[e]:l?(y[e]="__NOT_IN_VERSION_FILE__",w.push(e)):y[e]=n}p||(p=await this.pickTemplateVariablesFromBackupZip(i,s));const v=this.buildBackupFingerprint(y);let b=null;return c&&l&&v!==c.buildFingerprint&&(b={expected:c.buildFingerprint,actual:v},this.logger.warn(t.colors.yellow(`[DistService] Build manifest fingerprint mismatch (confirm in UI): expected ${c.buildFingerprint}, got ${v}`))),{backupFingerprint:v,unknownFiles:w,templateVariables:p,mainHash:h,allFilesInMeta:Boolean(l&&0===w.length),buildManifestMismatch:b,versionManifestHashMismatches:m}}finally{await d.promises.rm(s,{recursive:!0,force:!0})}}async analyzeBackup(e){if(!Ct.equals(e.subarray(0,Ct.length)))throw new Error("Backup file is not a ZIP file");return await this.resolveBackupAnalysisFromZip(e)}async getPublicTemplateVariablesHash(){const e=P.resolve(this.root,"public",Ht),t=await d.promises.readFile(e).catch(()=>null);return t?L.createHash("sha256").update(t).digest("hex"):null}async readPublicTemplateVariablesFile(){const e=P.resolve(this.root,"public",Ht);return await d.promises.readFile(e).catch(()=>null)}async saveTemplateVariablesFile(e){const t=P.resolve(this.root,"public",Ht);return await d.promises.mkdir(P.dirname(t),{recursive:!0}),await d.promises.writeFile(t,e),t}async saveBackup(e,s){const r=s??await this.analyzeBackup(e),n=r.backupFingerprint,i=await this.getLatestSavedBackup(),a=await this.meta();if(i){const{lastBackupHash:e,lastMainHash:s}=a;if(e===n)return void this.logger.info(t.colors.yellow(`[DistService] Backup skipped: same backup fingerprint as last saved (${n.slice(0,12)}...)`));if(r.allFilesInMeta&&r.mainHash&&s===r.mainHash)return void this.logger.info(t.colors.yellow("[DistService] Backup skipped: same VERSION manifest checksum (main hash) and all files listed in VERSION"))}const o=new Date,c=this.backupName(this.pageName,o);a.lastBackupName=c,a.lastBackupHash=n,a.lastBackupDate=o.toISOString(),r.mainHash?a.lastMainHash=r.mainHash:delete a.lastMainHash,await this.syncMeta(),await d.promises.writeFile(P.resolve(this.backupFolder,c),e),this.logger.info(`Backup saved to ${c}`),await this.pruneBackups(c)}async buildNewAssets(){if(this.nextBuild)return await this.buildNextAssets();this.logger.info(t.colors.cyan("[DistService] Build started"));const e=Lt("pp-dev build","node",[P.resolve(Bt,"./bin/pp-dev.js"),"build"],{cwd:this.root,env:Object.assign({},R.env,{NODE_ENV:"production"}),timeoutMs:this.buildTimeoutMs,signal:this.builds.signal});try{if(await this.logBuild("Build",e),this.buildInputFolder){const e=P.resolve(this.root,this.buildInputFolder);if(!await this.isDirectory(e))throw new Error(`Build input directory ${e} not found`);const t=await Tt(e);return this.throwIfStopped("pp-dev build"),t}const t=P.resolve(this.root,this.distZipFolder,this.distZipFilename);let s;try{s=await d.promises.readFile(t)}catch(e){if("ENOENT"===e.code)throw new Error(`File ${t} not found`);throw e}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:s}=this.nextBuild;this.logger.info(t.colors.cyan("[DistService] Next.js build started")),await this.logBuild("Next.js build",Rt(e,{timeoutMs:this.buildTimeoutMs,signal:this.builds.signal}));const r=P.resolve(e,s);if(!await this.isDirectory(r))throw new Error(`Next.js build output directory not found: ${r}`);this.throwIfStopped("next build"),await a.writeBuildVersionManifest({outDir:r,packageVersion:this.nextBuild.packageVersion,versionFileTemplate:this.versionFileTemplate,packageRepositoryUrl:this.nextBuild.packageRepositoryUrl,packageBranchName:this.nextBuild.packageBranchName}),this.throwIfStopped("next build");const n=await Tt(r);return this.throwIfStopped("next build"),n}get stopped(){return this.builds.signal.aborted}throwIfStopped(e){if(this.stopped)throw new Error(`${e} was stopped`)}async logBuild(e,s){try{await s}catch(s){const r=this.builds.signal.aborted;throw this.logger.info(t.colors.yellow(`[DistService] ${e} ${r?"stopped":"failed"}`)),s}this.logger.info(t.colors.cyan(`[DistService] ${e} finished`))}async isDirectory(e){try{return(await d.promises.stat(e)).isDirectory()}catch{return!1}}},exports.INSPECTOR_PATH=V,exports.MiAPI=class{#b;#k;#$=null;#x;#S;#A=!1;#E=null;#T=null;#I;#P;#N;#L;#R;internalPageName;appId;templateLess;assetsApi;pageApi;pageTemplateApi;pageVariableApi;logger;constructor(e,s){const{headers:r={},appId:n,templateLess:i=!0,disableSSLValidation:a=!1,v7Features:o=!1,personalAccessToken:c}=s||{};this.#b=r,this.#S=[],this.#x="",this.#I=o,this.#P=c,this.#N=!1,this.#L=Promise.resolve(!1);const l=`${e}:${a}`;if(Pe.has(l))this.#k=Pe.get(l);else{const t=new I.Agent({keepAlive:!1,...a?{rejectUnauthorized:!1}:{}});this.#k=E.create({baseURL:e,headers:r,timeout:3e4,maxRedirects:5,httpAgent:new T.Agent({keepAlive:!1}),httpsAgent:t}),Pe.set(l,this.#k)}this.appId=n,this.templateLess=i,this.assetsApi=new(o?ie:ne)(this.#k),this.pageApi=new ge(this.#k),this.pageTemplateApi=new me(this.#k),this.pageVariableApi=new fe(this.#k),this.logger=t.createLogger()}async isTemplateLoaded(){return this.#L}get isV710OrHigher(){return this.#N}get v7Features(){return this.#I}#j(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.#b=t,!t.authorization&&this.#P&&(t.authorization=`Bearer ${this.#P}`),t}#F(e){return e.replace(/[.*+?^${}()|[\]\\\/]/g,"\\$&")}get personalAccessToken(){return this.#P}set personalAccessToken(e){this.#P=e}updateHeaders(e){this.#j(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.#L||this.#$||(this.#L=new Promise(e=>{this.#R=e})),this.#$)return Promise.resolve(this.#$);if(void 0===this.templateLess&&(this.templateLess=!1),this.#I){const s=await this.pageApi.get(this.appId,this.#j(e)).then(e=>(this.logger.info(t.colors.green("Page fetched")),e)).catch(async s=>{if(this.#R(!1),he(s))throw s;throw await this.pageApi.checkAuth(this.#j(e))?(this.logger.error(t.colors.red(`Error fetching page data: ${s.message}\n${s.stack}`)),new Error("The current user does not have access to this page. Check your configuration to ensure app.id is correct.")):s});return void 0!==s.template_id&&(this.#N=!0),this.internalPageName=s.internal_name,this.#$=this.localTemplateHTML,this.#$=this.#$.replace(/%%PAGE TITLE%%/g,s.name||"Local template"),this.logger.info(t.colors.green("Local page template fetched")),this.#R(!0),this.#$}let s=(await this.pageApi.getAll(this.#j(e)).then(e=>(this.logger.info(t.colors.green("Page list fetched")),e)).catch(async s=>{throw this.#R(!1),await this.pageApi.checkAuth(this.#j(e))?(this.logger.error(t.colors.red(`Error fetching page list: ${s.message}\n${s.stack}`)),new Error("Current user does not have access to page list")):s})).find(e=>e.name===Ie);return s||(this.logger.warn(t.colors.yellow("Creating dev page template...")),s=await this.pageApi.create({enabled:"Y",name:Ie,internal_name:"dev-page-template",visible_in_homepage:"Y"},this.#j(e)).then(e=>(this.logger.info(t.colors.green("Dev page created")),e)).catch(e=>{throw this.logger.error(t.colors.red(`Error creating dev page: ${e.message}`)),this.#R(!1),new Error(`Error when creating dev page.\n That can be caused by missing permissions or page with name "${Ie}" already exists`)})),await this.pageApi.getPageContent(s.internal_name,this.#j(e)).then(e=>(this.#$=e,e)).then(e=>(this.#R(!0),this.logger.info(t.colors.green("Page template fetched")),e)).catch(e=>{throw this.#R(!1),this.logger.error(t.colors.red(`Error fetching page template: ${e.message}`)),new Error("Error fetching page template")})}async getPageVariables(e,s){return void 0===this.appId&&(this.appId=e,this.templateLess=!1),this.#$=await this.getPageTemplate(s),await this.pageApi.get(e,this.#j(s)).then(e=>{const{tags:t="[]",name:s,template:r}=e;if(r&&t){const e=JSON.parse(t);return this.#S=e,this.#A=!0,this.#x=s,e}return this.#S=[],this.#A=!0,this.#x=s,[]}).catch(s=>{if(this.logger.error(t.colors.red(`Error fetching page variables: ${s.message}`)),404===s.response?.status)throw new Error(`Portal Page with id "${e}" not found on instance ${this.#k.getUri()}`);if(401===s.response?.status)throw this.logger.warn(`Unauthorized error: ${s}`),new Error(`Current user does not have access to page with id "${e}" on instance ${this.#k.getUri()}`);throw s})}async getLivePageVariables(e=this.#b){if(void 0===this.appId)throw new Error("Cannot fetch live page variables before the page ID is known");const s=this.appId,r=Date.now();this.logger.info(t.colors.cyan(`[page-variables] Fetching live variables for page ID ${s} (page_id lookup)`));const n=await this.pageVariableApi.getById(s,this.#j(e));return this.logger.info(t.colors.green(`[page-variables] Fetched ${n.length} live variable(s) for page ID ${s} in ${Date.now()-r}ms`)),n}async applyPageVariables(e,s=this.#b){if(void 0===this.appId)throw new Error("Cannot apply page variables before the page ID is known");const r=this.appId,n=Date.now();this.logger.info(t.colors.cyan(`[page-variables] Applying ${e.length} variable(s) to page ID ${r} (page_id lookup)`)),await this.pageVariableApi.updateById(r,e,this.#j(s)),this.logger.info(t.colors.green(`[page-variables] Applied variables to page ID ${r} in ${Date.now()-n}ms`))}async listPages(e=this.#b){return this.pageApi.getAll(this.#j(e))}async getPageVariablesFor(e,t=this.#b){return this.pageVariableApi.getById(e,this.#j(t))}get localPageVariables(){return this.templateLess||!this.#A?null:this.#S.map(({name:e,value:t})=>({name:e,value:t}))}get isTemplateLess(){return!!this.templateLess}async reloadPageVariables(e=this.#b){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.#j(t),r=this.appId;try{return this.#I?await this.#O(r,s):await this.#B(r,s)}catch(e){this.#C(e,r)}}async#O(e,s){const r=await this.pageApi.get(e,s);return this.logger.info(t.colors.green("Page fetched")),void 0!==r.template_id&&(this.#N=!0),this.internalPageName=r.internal_name,r}async#B(e,t){return await this.pageApi.get(e,t)}#C(e,s){if(he(e))throw e;if(this.#I&&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 "${s}" not found on instance ${this.#k.getUri()}`);throw 401===e.response?.status&&this.logger.error(t.colors.red(`Current user does not have access to page with id "${s}" on instance ${this.#k.getUri()}`)),e}buildPage(e,t=!1){let s="string"==typeof e?e:e.toString("utf-8");for(const{regExp:e,value:t}of this.#M())s=s.replace(e,()=>t);if(t){return new(a.getJSDOM())(s).serialize()}const{before:r,after:n}=this.#U();return r+s+n}#M(){return this.#E?.vars!==this.#S&&(this.#E={vars:this.#S,replacements:this.#S.map(({name:e,value:t})=>({regExp:new RegExp(`\\[${this.#F(e)}\\]`,"g"),value:t}))}),this.#E.replacements}#U(){const e=this.#$,t=this.#x;if(this.#T?.template===e&&this.#T.title===t)return this.#T;const s=new(a.getJSDOM())(e),{document:r}=s.window,n="%%PLACEHOLDER%%",i=r.createElement("div");i.innerHTML=n;const o=r.querySelector(".main-side");if(o){const e=o.querySelectorAll("script");e.length?o.insertBefore(i,e.item(e.length-1)):o.append(i)}else{const e=r.createElement("div");e.append(i),r.body.append(e)}const c=r.querySelector("head"),l=c.querySelector("title");if(l)l.text=t;else{const e=r.createElement("title");e.textContent=t,c.appendChild(e)}const d=s.serialize(),u=new RegExp(`<div>\\s*${n}\\s*<\\/div>`,"i").exec(d);return this.#T={template:e,title:t,before:d.slice(0,u.index),after:d.slice(u.index+u[0].length)},this.#T}async getAssets(){if(this.appId){if(this.templateLess)return await this.assetsApi.downloadPageAssets(this.appId,this.#b);{const e=await this.pageApi.get(this.appId,this.#b);if(this.#N){const t=await this.pageTemplateApi.get(e.template_id,this.#b);return await this.assetsApi.downloadTemplateAssets(t.id,this.#b)}if(e.template)return await this.assetsApi.downloadTemplateAssets(e.template,this.#b)}}}async updateAssets(e){if(this.appId){if(this.templateLess)return await this.assetsApi.uploadPageAssets(this.appId,e,this.#b);{const t=await this.pageApi.get(this.appId,this.#b);if(this.#N){const s=await this.pageTemplateApi.get(t.template_id,this.#b);return await this.assetsApi.uploadTemplateAssets(s.id,e,this.#b)}if(t.template)return await this.assetsApi.uploadTemplateAssets(t.template,e,this.#b)}}}async validateCredentials(e){try{const t=e||this.#b;return await this.get("/api/user",t,!0),{isValid:!0}}catch(e){const t=Ee(e);return{isValid:!1,error:t.userFriendlyMessage,code:t.code}}}async get(e,s,r=!1,n={}){const i=r?s:Object.assign({},this.#j(this.#b),s);try{return await this.#k.get(e,{headers:i})}catch(e){if("UNKNOWN_ERROR"!==Ee(e).code){const s=Ee(e);throw n.quiet||(this.logger.error(t.colors.red(`API request failed: ${s.userFriendlyMessage}`)),function(e,s,r){const n=Ee(s),i=`[${r}] `;e.error(t.colors.red(`${i}${n.userFriendlyMessage}`)),e.error(t.colors.red(`Status: ${n.status} (${n.code})`)),e.error(t.colors.red(`Details: ${n.message}`)),n.suggestions.length>0&&(e.info(t.colors.yellow("Suggestions:")),n.suggestions.forEach((s,r)=>{e.info(t.colors.yellow(` ${r+1}. ${s}`))}))}(this.logger,e,"API Request")),e.tokenErrorInfo=s,e}throw e}}},exports.PP_DEV_HMR_WS_PATH="/@pp-dev-hmr",exports.RequestStore=class{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-=ks(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 y.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=ks(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($s(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($s(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}},exports.USERS_API_PATH=os,exports.VARIABLES_EDITOR_PATH=es,exports.createInternalServer=function({allowedHosts:e=[]}={}){const t=U();return t.use(function(e=[]){return(t,s,r)=>{const n=ws(t,e);n?s.status(403).json({error:`Blocked by pp-dev: ${n}.`}):r()}}(e)),t.use(U.json({limit:vs})),t.use(U.urlencoded({extended:!0})),t.use(bs),t},exports.createRequestCaptureMiddleware=function(e,t=10485760,s=Be){return(r,n,i)=>{const a=r.url||"/",o=a.split("?")[0];if(Rs.some(e=>a.startsWith(e))||js.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 m=[];let f=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));f+=r.byteLength,f<=t?m.push(r):(y=!0,m.length=0)}catch{}}function k(e){return"string"==typeof e[0]?e[0]:void 0}function $(){const e=n.getHeaders();return e["x-pp-proxy"]?"hit"===e["x-pp-cache"]?"proxy-cache":"proxy":"local"}let x=!1;n.write=function(e,...t){return b(e,k(t)),w(e,...t)},n.end=function(t,...s){return"function"!=typeof t&&b(t,k(s)),function(){if(x)return;x=!0;const t=Ls(a,"string"==typeof r.headers["content-type"]?r.headers["content-type"]:void 0,!h&&u.length>0?Buffer.concat(u):null),s=!y&&m.length>0?Buffer.concat(m):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:Es(r.headers),requestBody:t,requestBodyTruncated:h,responseHeaders:Ts(n.getHeaders()),responseBody:s,responseBodyTruncated:y})}(),v(t,...s)},i()}},exports.createUserHostGuard=function(e=Be){return(t,s,r)=>{const n=e.resolve(t),i=Fe(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",`${Oe(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.`))}},exports.crossOriginReason=ws,exports.extractZipSafe=It,exports.getIndexPageRegExp=function(e){return new RegExp(`^((${t=e,t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`);var t},exports.getMiAPIOptions=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}},exports.getProxyIgnore=function(e){return["/@vite","/@metricinsights","/@",e.endsWith("/")?e.slice(0,-1):e]},exports.getTokenErrorInfo=Ee,exports.getUserNameFromHost=Fe,exports.hostNotAllowedMessage=function(e){const t=JSON.stringify((e??"").replace(/:\d*$/,""));return`Blocked by pp-dev: this host (${t}) is not allowed. To allow it, add ${t} to server.allowedHosts in the pp-dev config.`},exports.initLoadPPData=function(e,s,r){const{templateLess:n=!1,miHudLess:i=!1,appId:a,base:o,appBase:c,v7Features:l}=r,d=t.createLogger();if(n&&i&&void 0===a)throw new Error("Custom App ID is required when both templateLess and miHudLess are true");return async(r,u,p)=>{try{const h=!(n&&i),g=se(r.url??""),m=e.test(g),f=!m&&!g.startsWith("/home")&&function(e,t){if(!t||"/"===t)return!0;const s=t.endsWith("/")?t:`${t}/`;return e===s||e===s.slice(0,-1)||e.startsWith(s)}(g,c)&&function(e){const t=e.headers["sec-fetch-dest"];if("string"==typeof t)return"document"===t;const s=e.headers.accept;return"string"==typeof s&&s.includes("text/html")}(r),y=t.authProvider.getState();if(!y.isAuthenticated&&!y.isRedirected&&r.url?.startsWith("/home")&&!r.url?.startsWith($t)){let e;d.info(t.colors.blue("Trying to authenticate and redirect to base"));const c=t=>{e=t};try{if(h?await At(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${$t}${encodeURIComponent("/")}`},r,u,c,d):await St(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${$t}${encodeURIComponent("/")}`},r,u,c,d),u.headersSent||u.writableEnded)return;return e?p(e):(t.authProvider.setRedirected(!0),d.info(t.colors.blue("Successfully authenticated. Redirecting to base")),te(u,o??"/",302))}catch(e){if(u.headersSent||u.writableEnded)return;return p()}}if(!m&&!f)return p();if(!h){return await St(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${$t}${encodeURIComponent("/")}`},r,u,p,d)}return await At(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${$t}${encodeURIComponent("/")}`},r,u,p,d)}catch(e){return d.error(t.colors.red(`Unexpected error in load-pp-data middleware: ${e instanceof Error?e.message:String(e)}`)),kt(),p(e)}}},exports.initPPRedirect=function(e,r){const n=(e=(e=e.startsWith("/")?e:`/${e}`).endsWith("/")?e:`${e}/`).endsWith("/")?e.slice(0,-1):e,i=t.createLogger();return(a,o,c)=>{const l=new s.URL(a.url??"","http://localhost"),{pathname:d,search:u}=l,p=["/",n];if(r&&(p.push(`${t.PATH_TEMPLATE_PREFIX}/${r}`),p.push(`${t.PATH_TEMPLATE_LOCAL_PREFIX}/${r}`)),p.includes(d)){const s=`${e}${u}`;return i.info(t.colors.yellow(`Redirecting to: ${s}`)),te(o,s,302)}c()}},exports.initProxy=function(e){const{rewritePath:r=/^\/(?!p[tl]).*/i,baseURL:n="",disableSSLValidation:i=!1,miAPI:a,templateName:c,users:l=Be}=e;if(!n)throw new Error("Base url is required");const d=function(e){try{return new URL(e).host}catch{return e.replace(Ve,"$2")}}(n),u=n.replace(Ve,"$1$2"),p=import("file-type"),h=t.createLogger(),g=e.sessionUsers??new De(l,function(e){return async t=>(await _e(e,{Cookie:`${ve}=${t}`})).miUser}(a));return o.createProxyMiddleware({selfHandleResponse:!0,pathFilter:(t,s)=>!(e.proxyIgnore||[]).some(e=>"string"==typeof e?t.startsWith(e):"function"!=typeof e.test||e.test(t))&&("string"==typeof r?t.startsWith(r):Array.isArray(r)?r.some(e=>t.startsWith(e)):"function"==typeof r.test&&r.test(t)),target:n,changeOrigin:!0,logger:{info:()=>{},warn:()=>{},error:()=>{}},secure:!i,headers:{host:d,origin:u},on:{proxyReq(e,r,i){const o=r.headers.host,d=e.getHeader("referer");o&&d&&"string"==typeof d&&e.setHeader("referer",d.replace(function(e){let t=Y.get(e);return t||(t=new RegExp(`^https?://${K(e)}(?=[/?#]|$)`,"i"),Y.set(e,t)),t}(o),n));const u=l.resolve(r);let p;u?.user?p=u.user.token:u&&(p=a.personalAccessToken),p?(e.setHeader("Authorization",`Bearer ${p}`),Ze.set(r,p)):"session"===u?.user?.kind&&e.removeHeader("Authorization"),u?.user&&e.removeHeader("Token");const g="session"===u?.user?.kind?u.user:void 0;let m;if(g&&Fe(r.headers.host)!==g.name){m=g.session;const t=m?(f=r.headers.cookie,y=m,[...Me(f),`${ve}=${y}`].join("; ")):function(e){const t=Me(e);return t.length?t.join("; "):void 0}(r.headers.cookie);t?e.setHeader("cookie",t):e.removeHeader("cookie")}var f,y;Ge.set(r,{user:u?.user,sentSession:m}),e.removeHeader("if-none-match"),e.removeHeader("if-modified-since");const w=r.url??"/",v=function(e,t,r,n){if(!t||!r||!n||r===n)return e;try{const t=new s.URL(e,"http://localhost"),i=t.pathname.match(/^\/data\/page\/([^/]+)(\/.*)?$/);if(!i)return e;let a;try{a=decodeURIComponent(i[1])}catch{a=i[1]}if(a!==r)return e;return`/data/page/${n}${i[2]??""}`+t.search+t.hash}catch{return e}}(w,a.v7Features,c,a.internalPageName);v!==w&&(r.url=v,e.path=v,console.info(`${t.colors.cyan("Rewrites data page to correct internal page name")}: ${t.colors.yellow(w)} ${t.colors.blue("→")} ${t.colors.green(v)}`)),h.info(`${t.colors.blue("Proxies request:")} ${t.colors.green(r.method)} ${r.url} -> ${t.colors.green(e.method)} ${e.protocol}//${e.host}${e.path}${u?.user?` ${t.colors.blue("as")} ${t.colors.yellow(u.user.name)}`:""}`);const{socket:b}=r,k=()=>{setTimeout(()=>{e.destroyed||e.destroy()},200)};return b.once("close",k),e.once("close",()=>b.off("close",k)),e},proxyRes:(e,s,r)=>{e.headers["set-cookie"]&&(e.headers["set-cookie"]=xe(e.headers["set-cookie"],ye(s))),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,`${ye(s)?"https":"http"}://${r}`):e}(e.headers.location,d,s));const n=function(e,t){if(!Je.test(e.url??""))return;const s=Fe(e.headers.host);return void 0===s?void 0:t.get(s)}(s,l),i=Ge.get(s);if(n){e.resume();const a={"cache-control":"no-store"};i?.user===n&&(l.remove(n.name),h.info(`${t.colors.blue("Logged out user")} ${t.colors.yellow(n.name)}, back to the main host`),e.headers["set-cookie"]&&(a["set-cookie"]=e.headers["set-cookie"]));const o=s.headers["sec-fetch-mode"];return o&&"navigate"!==o?r.writeHead(204,a):r.writeHead(302,{...a,location:`${Oe(s)}/`}),void r.end()}const a=i?.user;let c=!0;if(a&&l.get(a.name)!==a)c=!1;else if(a){let t=!1;"session"===a.kind&&(t=g.isLeftBehindRequest(a,s,i?.sentSession),g.observe(a,s,e,i?.sentSession)),c=Fe(s.headers.host)===a.name&&!t}if(!c){const t=function(e){const t=(e??[]).filter(e=>void 0===$e(e,ve));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,t)=>Buffer.from(ee(We,"/login",Q(d,s.headers.host??"",e.toString(t))),t);if(e.headers["content-type"]?.includes("text/event-stream")||e.headers["transfer-encoding"]?.includes("chunked")&&"no"===e.headers["x-accel-buffering"])return h.info(`${t.colors.blue("Start streaming for request:")} ${t.colors.green(s.method)} ${s.url}`),et(u)(e,s,r);const m=function(e){const t=e["content-type"];if("string"==typeof t&&t.trim()&&!Xe(t))return"pipe";const s=Number(e["content-length"]);return Number.isFinite(s)&&s>=10485760&&Qe(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"===m&&(e.headers["x-accel-buffering"]="no"),"buffer"!==m)return et("stream"===m?u:void 0)(e,s,r);const f=o.responseInterceptor(async(e,t,s,r)=>{r.setHeader(qe,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>"))&&!Fe(s.headers.host)&&(t+=`<script>(${Se.toString()})(${n=d,JSON.stringify(n).replace(/</g,"\\u003c")})<\/script>`)}catch{}const r=s.headers.host??"";return ee(We,"/login",Q(d,r,t))}var n});return f(e,s,r)},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))}}})},exports.initProxyCache=function(e){const{devServer:s,ttl:r=st,maxSize:n=rt,maxItems:i=nt,users:a=Be}=e,o=t.createLogger();return n===rt&&i===nt||(at.maxSize=n,at.maxItems=i),s.cache=at,dt.has(a)||(dt.add(a),a.onRemove(e=>pt(e.name,"user removed")),a.onSessionChange(e=>pt(e.name,"MI session changed or ended"))),(e,s,n)=>{const i=a.resolve(e);if(!i)return n();s.once("finish",()=>{const t=s.hasHeader(qe)?ht(e,s,i.key):void 0;t&&pt(i.key,`${t} (${e.method} ${se(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 tt.test(r)?r.includes("/auth/info.js")?"":t?`@${t}@${s}:${e}`:e:""}(l,i.key,e.headers.host??""):"";if(!d||!function(e,t){const{user:s}=t;return"session"!==s?.kind||!!s.session&&(Fe(e.headers.host)!==s.name||ke(e.headers.cookie,ve)===s.session)}(e,i))return n();const u=at.get(d);if(u)return o.info(`${t.colors.blue("Proxies request:")} ${t.colors.green(e.method)} ${l} -> ${t.colors.blue("Cache")} ${d}`),function(e,s){try{for(const[t,r]of Object.entries(s))null!=r&&e.setHeader(t,r)}catch(e){t.createLogger().warn(`Failed to set some response headers: ${e instanceof Error?e.message:String(e)}`)}}(s,u.headers),s.setHeader("X-PP-Cache","hit"),s.write(u.content),void s.end();const p=s.end,h=s.write,g=[];let m=0,f="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=()=>{f="pass";for(const e of g.splice(0))h.call(s,e)},v=()=>{"undecided"===f&&(s.hasHeader(qe)?!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>=it)}(s)?w():f="buffer":f="pass")};s.write=function(e,t,s){if(v(),"pass"===f)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),m+=n.length),m>it&&w(),r&&process.nextTick(r),!0},s.end=function(e,n,l){if(v(),"pass"===f)return p.call(this,e,n,l);"function"==typeof e?(l=e,e=void 0):"function"==typeof n&&(l=n,n=void 0);const u=y(e,"string"==typeof n?n:void 0);let h;u&&g.push(u);try{h=gt(g);const e=Buffer.byteLength(h);if(200===s.statusCode&&e>0&&e<it&&function(e,t,s){return!e.user||s.get(e.key)===e.user&&e.user.session===t}(i,c,a)){const{"set-cookie":n,...i}=s.getHeaders(),a={headers:i,content:h,timestamp:Date.now(),size:e};at.put(d,a,r),o.info(`${t.colors.blue("[Cached]")} ${d} (${(e/1024).toFixed(1)}KB)`)}}catch(e){o.error(`Failed to cache response for ${d}: ${e}`),h=gt(g)}return p.call(this,h,l)},n()}},exports.initRewriteResponse=function(s,r){return async(n,i,a)=>{if(await s(n.url??"",n,i)){const s=t.createLogger(),o=i.end;if("HEAD"===n.method)return i.end=function(e,t,s){const r=[e,t,s].find(e=>"function"==typeof e);return i.headersSent||i.removeHeader("content-length"),o.call(this,r),this},void a();s.info(`Rewrite response for ${n.url}`);const c=[];i.write=function(e,t,s){const r=G(e,Z(t));r&&c.push(r);const n="function"==typeof t?t:s;return"function"==typeof n&&process.nextTick(n),!0},i.end=function(t,a,l){"function"==typeof t&&(l=t,t=void 0);const d=G(t,Z(a));d&&c.push(d);const u="function"==typeof a?a:l,p=i.getHeader("content-encoding"),h=function(t,s){switch(s){case"gzip":return e.unzipSync(t);case"br":return e.brotliDecompressSync(t);case"deflate":return e.inflateSync(t);default:return t}}(Buffer.concat(c),p),g=function(t,s){switch(s){case"gzip":return e.gzipSync(t);case"br":return e.brotliCompressSync(t);case"deflate":return e.deflateSync(t);default:return t}}(r(h,n,i),p);return void 0!==i.getHeader("content-length")&&(i.headersSent?s.warn(`Rewrite response for ${n.url}: headers already sent, Content-Length left as is`):i.setHeader("content-length",g.length)),o.call(this,g,u),this}}a()}},exports.invalidateProxyCache=lt,exports.isHostAllowed=function(e,t){if(void 0===e||!0===t)return!0;const s=function(e){const t=e.trim().toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");return e>0&&6===$.isIP(t.slice(1,e))?{ip:!0}:void 0}const s=t.replace(/:\d*$/,"");if(s&&!s.includes(":"))return 4===$.isIP(s)?{ip:!0}:{hostname:s}}(e);if(void 0===s)return!1;if("ip"in s)return!0;const{hostname:r}=s;return"localhost"===r||r.endsWith(".localhost")||function(e,t){return t.some(t=>t===e||t.startsWith(".")&&(t.slice(1)===e||e.endsWith(t)))}(r,t)},exports.isSecureRequest=ye,exports.redirect=te,exports.registerInspectorRoutes=function(e,t,s=10485760,r=D){const n=q.get(e);if(n)return n.store=t,void(n.captureLimit=s);const i={store:t,captureLimit:s};q.set(e,i),e.get("/@api/requests",(e,t)=>{const{store:s}=i,r=z(e.query.limit),n=z(e.query.offset),a=z(e.query.method),o=z(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:J(s.memoryUsage),maxMemoryFormatted:J(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=W(s.requestHeaders["content-type"]),n=W(s.responseHeaders["content-type"]);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:s.responseBody?s.responseBody.toString("base64"):null,responseBodySize:s.responseBody?.byteLength??0,responseBodyTruncated:s.responseBodyTruncated,responseContentType:n})}),e.delete("/@api/requests",(e,t)=>{i.store.clear(),t.json({ok:!0})}),H(e,{path:V,name:"request-inspector",clientDir:r,values:()=>({captureLimit:String(i.captureLimit)})})},exports.removeStaleDevTypes=function(e,t){const s=t?.distDir;if("export"!==t?.output||!s||".next"===s)return null;const r=P.resolve(e,s,"dev","types");return N.existsSync(r)?(N.rmSync(r,{recursive:!0,force:!0}),r):null},exports.resolveProxyCacheTtl=function(e){const t=Number(e);return!t||Number.isNaN(t)||t<0?6e5:t},exports.rewriteSetCookieHeader=xe,exports.runNextBuildProcess=Rt,exports.startKeepingUsers=fs,exports.startSyncAndUsers=function(e){const{distService:s,miAPI:r}=e,n=new Vt(e.server,{distService:s,miAPI:r});return as(e.internalServer,{distService:s,miAPI:r}),function(e,s){const r=cs.get(e);if(r)return void(r.deps=s);const n={deps:s};cs.set(e,n);const i=t.createLogger(),a=()=>n.deps.users??Be;e.get(os,(e,t)=>{const s=a();t.json({available:Boolean(n.deps.miAPI.personalAccessToken),users:s.list().map(t=>ls(t,e)),defaultUser:s.defaultUser?.name??null})}),e.put(`${os}/default`,(e,s)=>{const r=a(),n=(e.body??{}).name;if(null===n||"string"==typeof n)if(null===n||r.get(n)){try{r.setDefaultUser(n??void 0)}catch(e){return void ds(s,409,"NOT_LOGGED_IN",e instanceof Error?e.message:String(e))}i.info(`${t.colors.blue("Default user:")} ${t.colors.yellow(n??"the original user")}`),s.json({defaultUser:n})}else ds(s,404,"NOT_FOUND",`There is no user named "${n}"`);else ds(s,400,"INVALID_NAME","name must be a user name or null")}),e.post(os,async(e,s)=>{const{miAPI:r}=n.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 ds(s,400,"INVALID_KIND",'kind must be "token" or "session"');if(!r.personalAccessToken)return void ds(s,409,"ORIGINAL_TOKEN_REQUIRED","Adding users needs your own API token: set mi.token or MI_ACCESS_TOKEN.");const p=je(l);if(p)return void ds(s,400,"INVALID_NAME",p);if(o.get(l))return void ds(s,409,"NAME_TAKEN",`A user named "${l}" already exists`);if("session"===u){const r=o.add({name:l,kind:"session"});return i.info(`${t.colors.blue("Added user")} ${t.colors.yellow(r.name)}: log in at ${Oe(e,r.name)}/login`),void s.status(201).json({user:ls(r,e)})}if(!d)return void ds(s,400,"TOKEN_REQUIRED","The API token is required");const h=o.context,g=await He(r,d);if(o.context!==h||n.deps.miAPI!==r||a()!==o)return void ds(s,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; add the user again");if(!g.ok)return void(g.rejected?ds(s,400,"INVALID_TOKEN",g.message):ds(s,502,"MI_UNAVAILABLE",g.message));const{miUser:m}=g;let f;try{f=o.add({name:l,kind:"token",token:d,miUser:m})}catch(e){return void ds(s,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}i.info(`${t.colors.blue("Added user")} ${t.colors.yellow(f.name)} (MI user ${m.id}${m.username?`, ${m.username}`:""}) at ${Oe(e,f.name)}`),s.status(201).json({user:ls(f,e)})}),e.patch(`${os}/:name`,async(e,s)=>{const{miAPI:r}=n.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 ds(s,404,"NOT_FOUND",`There is no user named "${c}"`);if("token"!==l.kind)return void ds(s,400,"NOT_EDITABLE","Only users added with an API token can be edited. Remove this user and add it again.");const h=je(u);if(h)return void ds(s,400,"INVALID_NAME",h);if(u!==c&&o.get(u))return void ds(s,409,"NAME_TAKEN",`A user named "${u}" already exists`);let g,m={...l,name:u};if(p&&p!==l.token){const e=o.context,t=await He(r,p);if(o.context!==e||n.deps.miAPI!==r||a()!==o)return void ds(s,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; edit the user again");if(!t.ok)return void(t.rejected?ds(s,400,"INVALID_TOKEN",t.message):ds(s,502,"MI_UNAVAILABLE",t.message));const{state:i,...c}=m;m={...c,token:p,miUser:t.miUser}}if(o.get(c)===l)if(u!==c||m.token!==l.token){try{g=o.replace(c,m)}catch(e){return void ds(s,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}i.info(`${t.colors.blue("Edited user")} ${t.colors.yellow(c)}${u!==c?` → ${t.colors.yellow(u)}`:""}${g.token!==l.token?" (new API token)":""}`),s.json({user:ls(g,e)})}else s.json({user:ls(l,e)});else ds(s,409,"USER_CHANGED",`The user "${c}" changed meanwhile; edit it again`)}),e.delete(`${os}/:name`,(e,s)=>{const r=String(e.params.name);a().remove(r)?(i.info(`${t.colors.blue("Removed user")} ${t.colors.yellow(r)}`),s.status(204).end()):ds(s,404,"NOT_FOUND",`There is no user named "${r}"`)})}(e.internalServer,{miAPI:r}),fs({persist:e.persistUsers,miAPI:r,projectRoot:e.projectRoot,miUrl:e.miUrl}),n},exports.urlReplacer=Q,exports.zipDirectoryToBuffer=Tt;
2
- //# sourceMappingURL=request-capture.middleware-BUpxzWDS.js.map