@metricinsights/pp-dev 1.5.0-beta.2 → 1.5.0-beta.21

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 (68) hide show
  1. package/README.md +54 -11
  2. package/dist/README.md +54 -11
  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/cli.js.map +1 -1
  7. package/dist/cjs/index-CeIQtamz.js +2 -0
  8. package/dist/cjs/index-CeIQtamz.js.map +1 -0
  9. package/dist/cjs/index.js +1 -1
  10. package/dist/cjs/migrate-C1svbbPB.js +2 -0
  11. package/dist/cjs/migrate-C1svbbPB.js.map +1 -0
  12. package/dist/cjs/package.json +8 -12
  13. package/dist/cjs/plugin.js +1 -1
  14. package/dist/cjs/plugin.js.map +1 -1
  15. package/dist/cjs/request-capture.middleware-Chm27VXb.js +2 -0
  16. package/dist/cjs/request-capture.middleware-Chm27VXb.js.map +1 -0
  17. package/dist/cjs/version-manifest-C15hpGGV.js +2 -0
  18. package/dist/cjs/version-manifest-C15hpGGV.js.map +1 -0
  19. package/dist/cjs/version-plugin-DtPQBhEK.js +2 -0
  20. package/dist/cjs/version-plugin-DtPQBhEK.js.map +1 -0
  21. package/dist/client/client.js +269 -125
  22. package/dist/client/client.js.map +1 -1
  23. package/dist/client/request-inspector.css +3 -0
  24. package/dist/client/request-inspector.css.map +1 -0
  25. package/dist/client/request-inspector.html +87 -0
  26. package/dist/client/request-inspector.js +527 -0
  27. package/dist/client/request-inspector.js.map +1 -0
  28. package/dist/client/variables-editor.css +3 -0
  29. package/dist/client/variables-editor.css.map +1 -0
  30. package/dist/client/variables-editor.html +44 -0
  31. package/dist/client/variables-editor.js +3419 -0
  32. package/dist/client/variables-editor.js.map +1 -0
  33. package/dist/esm/auth.provider-Cq0EuReh.js +2 -0
  34. package/dist/esm/auth.provider-Cq0EuReh.js.map +1 -0
  35. package/dist/esm/cli.js +1 -1
  36. package/dist/esm/cli.js.map +1 -1
  37. package/dist/esm/index-DioJ4R68.js +2 -0
  38. package/dist/esm/index-DioJ4R68.js.map +1 -0
  39. package/dist/esm/index.js +1 -1
  40. package/dist/esm/migrate-FpJKfYgz.js +2 -0
  41. package/dist/esm/{migrate-CCFtF5bt.js.map → migrate-FpJKfYgz.js.map} +1 -1
  42. package/dist/esm/package.json +8 -12
  43. package/dist/esm/plugin.js +1 -1
  44. package/dist/esm/plugin.js.map +1 -1
  45. package/dist/esm/request-capture.middleware-BNCdPdkF.js +2 -0
  46. package/dist/esm/request-capture.middleware-BNCdPdkF.js.map +1 -0
  47. package/dist/esm/version-manifest-qxz5FXuG.js +2 -0
  48. package/dist/esm/version-manifest-qxz5FXuG.js.map +1 -0
  49. package/dist/esm/version-plugin-b2xMXK9M.js +2 -0
  50. package/dist/esm/version-plugin-b2xMXK9M.js.map +1 -0
  51. package/dist/types/index.d.ts +46 -9
  52. package/docs/features.md +4 -1
  53. package/package.json +21 -28
  54. package/dist/cjs/index-CNJgcIGX.js +0 -2
  55. package/dist/cjs/index-CNJgcIGX.js.map +0 -1
  56. package/dist/cjs/migrate-DkUysGJq.js +0 -2
  57. package/dist/cjs/migrate-DkUysGJq.js.map +0 -1
  58. package/dist/cjs/plugin-BZ6G8J6V.js +0 -2
  59. package/dist/cjs/plugin-BZ6G8J6V.js.map +0 -1
  60. package/dist/cjs/version-plugin-433yyuTq.js +0 -2
  61. package/dist/cjs/version-plugin-433yyuTq.js.map +0 -1
  62. package/dist/esm/index-BeF76QPw.js +0 -2
  63. package/dist/esm/index-BeF76QPw.js.map +0 -1
  64. package/dist/esm/migrate-CCFtF5bt.js +0 -2
  65. package/dist/esm/plugin-l4fgvJz0.js +0 -2
  66. package/dist/esm/plugin-l4fgvJz0.js.map +0 -1
  67. package/dist/esm/version-plugin-Bqy1V1SQ.js +0 -2
  68. package/dist/esm/version-plugin-Bqy1V1SQ.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("zlib"),t=require("./auth.provider-CyXyBAm3.js"),s=require("url"),r=require("axios"),n=require("node:http"),i=require("node:https"),a=require("./version-manifest-C15hpGGV.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");var $="undefined"!=typeof document?document.currentScript:null;const x=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function S(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 A=x(r),E=x(n),T=x(i),I=S(l),P=S(d),N=S(u),L=S(p),R=S(h),j=x(g),F=S(m),B=x(w),C=x(v),O=x(b),M=x(k),U=I.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 D(e,t){const s=t.clientDir??U,r=new Set([`${t.name}.js`,`${t.name}.css`,`${t.name}.js.map`,`${t.name}.css.map`]);e.get(t.path,(e,r)=>{P.readFile(I.join(s,`${t.name}.html`),"utf-8",(e,s)=>{if(e)return void r.status(500).type("text/plain").end(`${t.name} page not built (${e.message})`);const n=t.values?.()??{};r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-cache"),r.end(s.replace(/\{\{(\w+)\}\}/g,(e,t)=>n[t]??e))})}),e.get(`${t.path}/:file`,(e,t,n)=>{const i=e.params.file;r.has(i)?P.readFile(I.join(s,i),(e,s)=>{e?n():(t.setHeader("Content-Type",_[I.extname(i)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(s))}):n()})}const H="/@pp-dev/inspector",V=new WeakMap;function q(e){const t=Array.isArray(e)?e[0]:e;return"string"==typeof t?t:void 0}function z(e){return Array.isArray(e)?e[0]??"":String(e??"")}function W(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 J(e){return"string"==typeof e?e:void 0}function Z(e,t){return"string"==typeof e?Buffer.from(e,t):e instanceof Uint8Array?Buffer.from(e):null}const K=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),G=new Map,X=new Map;const Y=(e,t,s)=>{let r=G.get(e);if(!r){const t=/:\d+$/.test(e)?"":"(?::(?<port>\\d+))?";r=new RegExp(`(?<keep>!!)?(?<url>http(?<secure>s)?(?<slashes>:(?:\\\\)?/(?:\\\\)?/)${K(e)}${t})`,"gi"),G.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}`})},Q=(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},ee=(e,t,s)=>{e.setHeader("location",t),e.statusCode=s,e.end()};function te(e){return e.split("?")[0]}class se{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 re extends se{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 ne extends re{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 ie="Something went wrong when fetching page data",ae="Something went wrong when fetching page template data",oe="Something went wrong when fetching page variables",ce=" The instance may be down or in maintenance mode. Please try again later.",le=[ie,ae,oe];function de(){return new Error(`${ie}.${ce}`)}function ue(){return new Error(`${ae}.${ce}`)}function pe(e){return e instanceof Error&&le.some(t=>e.message.includes(t))}class he extends se{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 de();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 de();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 de();return s.page}}class ge extends se{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 ue();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 ue();return s.page_template}}class me extends se{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(`${oe}.${ce}`);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 fe(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 ye(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 we="metric_insights_session";function ve(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 be(e,t){return e?ve(e.split(";"),t):void 0}function ke(e,t){if(void 0===e||"number"==typeof e)return;return ve((Array.isArray(e)?e:[e]).map(e=>e.split(";",1)[0]),t)}function $e(e,t){return void 0===e?e:Array.isArray(e)?e.map(e=>ye(e,t)):ye(e,t)}const xe=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 Se(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 Ae(e){const{status:t,message:s}=Se(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 Ee(e){const{status:t}=Se(e);return 401===t||403===t||412===t}const Te="[DEV PAGE. DO NOT DELETE]",Ie=new Map;const Pe=String.raw`[a-z](?:[a-z0-9\-]*[a-z0-9])?`,Ne=new RegExp(`^(?:${Pe})$`),Le=".localhost";function Re(e){return e?e.length>32?"The name must be at most 32 characters long":Ne.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 je(e){if(!e)return;const t=e.toLowerCase().replace(/:\d+$/,"");if(!t.endsWith(Le))return;const s=t.slice(0,-10);return s&&!s.includes(".")?s:void 0}function Fe(e,t){const s=/:(\d+)$/.exec(e.headers.host??"")?.[1];return`${fe(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=Re(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=Re(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=je(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 Oe(e){return(e??"").split(";").map(e=>e.trim()).filter(e=>e&&e.split("=",1)[0].trim()!==we)}function Me({statusCode:e=200,headers:t}){return 401===e||412===e||e>=300&&e<400&&Ce.test(String(t.location??""))}class Ue{#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=je(t.headers.host)===e.name?be(t.headers.cookie,we):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=je(t.headers.host)===e.name,i=n?be(t.headers.cookie,we):r,a=ke(s.headers["set-cookie"],we),o=this.#g.get(e);let c,l,d=n;return a&&a!==i?(c=a,l=i):n&&i!==e.session&&!Me(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&&Me(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(Ee(e))return{miUser:void 0,refused:Ae(e).userFriendlyMessage};throw e}}async function De(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: ${Ae(e).userFriendlyMessage}`}}}const He=/^(https?:\/\/)([^/]+)(\/.*)?$/i,Ve="X-PP-Proxy";const qe=/^\/login(?:\/|$)/i,ze="/auth/saml/login";const We=/^\/auth\/(?:index\/)?logout(?:[/?#]|$)/i;const Je=new WeakMap,Ze=new WeakMap;const Ke=[/^text\//,/^application\/(?:[\w.-]+\+)?(?:json|xml)$/,/^application\/(?:x-)?(?:java|ecma)script$/,/^[\w.-]+\/[\w.-]+\+(?:json|xml)$/];function Ge(e){const t=e.split(";",1)[0].trim().toLowerCase();return Ke.some(e=>e.test(t))}const Xe=/[\w.:/\\!-]/;function Ye(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&&Ge(s)}function Qe(e){return async(t,s,r)=>{const n=e&&Ye(t.headers);r.statusCode=t.statusCode??r.statusCode,t.statusMessage&&(r.statusMessage=t.statusMessage),r.setHeader(Ve,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(!Xe.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 et=/\.(?:[a-z0-9]+)$/i,tt=6e5,st=104857600,rt=1e3,nt=10485760;const it=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=tt){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)}}(st,rt),at=new Set,ot=new Map;function ct(e){it.clear(),ot.clear(),at.forEach(e=>e()),t.createLogger().info(t.colors.blue(`Proxy cache cleared: ${e}`))}const lt=new WeakSet;function dt(e,t){return t?e.startsWith(`@${t}@`):!e.startsWith("@")}function ut(e,s){if(e){for(const t of it.keys())dt(t,e)&&it.del(t);ot.delete(e),t.createLogger().info(t.colors.blue(`Proxy cache cleared for ${e}: ${s}`))}else ct(s)}function pt(e,t,s){const r=function(e){return Je.get(e)}(e);if(void 0!==r){const e=ot.get(s),t=void 0!==e&&r!==e;return ot.set(s,r),t?"personal access token changed":void 0}const n=ke(t.getHeader("set-cookie"),we);return void 0!==n&&n!==be(e.headers.cookie,we)?"MI session changed":void 0}function ht(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 gt=new Map;function mt(e){const t=gt.get(e);return t?Date.now()-t.timestamp>18e4?(gt.delete(e),null):t.data:null}function ft(e,t){gt.set(e,{timestamp:Date.now(),data:t})}var yt;yt=()=>gt.clear(),at.add(yt);let wt=!1;function vt(e){wt||(wt=!0,e.info(t.colors.blue("Clearing proxy cache after successful login")),it.clear())}function bt(){wt=!1,t.authProvider.reset()}const kt="/home?proxyRedirect=";function $t(e){const t=e.headers??{},s=Boolean(je(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 xt(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=$t(r);a.info(t.colors.green("Start loading page info"));try{const s=`pageInfo:${o}`;return mt(s)?(a.info(t.colors.green("Page info loaded from cache")),i()):(await e.getPageInfo(o,d),vt(a),ft(s,{success:!0}),t.authProvider.updateState({isAuthenticated:!0}),a.info(t.colors.green("Page info loaded successfully")),i())}catch(e){return bt(),At(e,c??!0,l||`${kt}${encodeURIComponent("/")}`,n,i,a,"Page info")}}async function St(e,s,r,n,i,a){const{templateLess:o,appId:c,redirectOnAuthFailure:l,redirectUrl:d}=s,u=$t(r);a.info(t.colors.green("Start loading page data"));try{const s=`pageData:${o}:${c}`;if(mt(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,vt(a),ft(s,{success:!0}),a.info(t.colors.green("Page data loaded successfully")),i()}catch(e){return bt(),At(e,l??!0,d||`${kt}${encodeURIComponent("/")}`,n,i,a,"Page data")}}function At(e,s,r,n,i,a,o){if(function(e){return null!==e&&"object"==typeof e&&Ee(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}`)),ee(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 Et(e){const t=new j,s=async r=>{const n=await d.promises.readdir(r,{withFileTypes:!0});for(const i of n){const n=I.join(r,i.name);if(i.isDirectory())await s(n);else if(i.isFile()){const s=I.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 Tt(e,t){const s=await j.loadAsync(await d.promises.readFile(e),{createFolders:!1}),r=I.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=I.resolve(r,t);if(s!==r&&!s.startsWith(r+I.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=I.resolve(r,e.unsafeOriginalName??e.name);e.dir?await d.promises.mkdir(t,{recursive:!0}):(await d.promises.mkdir(I.dirname(t),{recursive:!0}),await d.promises.writeFile(t,await e.async("nodebuffer")))}}const It=6e5;function Pt(e,t,s){if(e.pid)if("win32"!==process.platform)try{s?process.kill(-e.pid,t):e.kill(t)}catch{}else null===e.exitCode&&null===e.signalCode&&F.spawnSync("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore"})}function Nt(e,t,s,{cwd:r,env:n,timeoutMs:i,signal:a,killGraceMs:o=5e3}){return new Promise((c,l)=>{if(a?.aborted)return void l(new Error(`${e} was stopped`));const d="win32"!==process.platform&&(void 0!==a||void 0!==i),u=F.spawn(t,s,{cwd:r,env:n,stdio:"inherit",detached:d});let p,h;const g=(e,t)=>{p?t||void 0===h||(clearTimeout(h),h=void 0,Pt(u,"SIGKILL",d)):(p=e,t?(Pt(u,"SIGTERM",d),h=setTimeout(()=>{h=void 0,Pt(u,"SIGKILL",d)},o)):Pt(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&&Pt(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 Lt(e,s={}){let r;try{const t=f.createRequire(I.join(e,"package.json")).resolve("next/package.json");r=I.resolve(I.dirname(t),"dist/bin/next")}catch{throw new Error(`Unable to resolve the "next" binary from ${e}. Is Next.js installed?`)}await Nt("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 Rt="pageName",jt="date",Ft=I.dirname("undefined"!=typeof __filename&&__filename||s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:$&&"SCRIPT"===$.tagName.toUpperCase()&&$.src||new URL("request-capture.middleware-Chm27VXb.js",document.baseURI).href)),Bt=I.resolve(Ft,"..",".."),Ct=Buffer.from([80,75,3,4]),Ot=20,Mt=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const Ut="sync-service.meta.json",_t="BUILD-MANIFEST.json",Dt="__template_variables.json";class Ht{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"===Ae(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(pe(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&&I.basename(r.versionManifestHashMismatches[0].relativePath)===Dt,o=r.versionManifestHashMismatches,c=o.filter(e=>I.basename(e.relativePath)===Dt),l=o.filter(e=>I.basename(e.relativePath)!==Dt),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 Vt=["text","select","multiselect","file","list","color","boolean"];function qt(e){return Vt.includes(e)}const zt=["true","false","Y","N","1","0"],Wt=/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function Jt(e,t){return e.id===t||e.text===t}function Zt(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 Wt.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(Zt);return r.some(e=>Jt(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(Zt),n=i.split(",").map(e=>e.trim()).filter(e=>!r.some(t=>Jt(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 Gt(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 Xt(e,t){const s=[];switch(e.tag_type){case"boolean":zt.includes(t)||s.push({name:e.name,severity:"warning",message:`Value "${t}" is not a recognized boolean encoding (expected one of ${zt.join(", ")}).`});break;case"list":try{const r=JSON.parse(t);Array.isArray(r)?s.push(...Gt(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(Zt),n=("multiselect"===e.tag_type?t.split(",").map(e=>e.trim()):[t]).filter(e=>!r.some(t=>Jt(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 Yt(e,t){switch(e.tag_type){case"boolean":return zt.includes(t)?null:`Not a recognized boolean value ("${t}").`;case"color":return""===t||Wt.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 Qt="/@pp-dev/variables-editor",es=/^[A-Za-z0-9_\s-]+$/,ts="Dist service or MiAPI is not defined",ss=new WeakMap;async function rs(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 ns(e){return e?(await rs(e))?.schema??null:null}function is(e,t,s){const r=ss.get(e);if(r)return void(r.deps=t);const n={deps:t};ss.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:ts});const r=await rs(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:ts});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&&!qt(e.tag_type)&&c.push(`"${e.name}" has an unrecognized tag_type "${e.tag_type}".`),es.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 ${Dt}.`,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 ns(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 ns(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(...Xt(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 ns(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=Yt(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)})}}),D(e,{path:Qt,name:"variables-editor",clientDir:s,values:()=>({templateLess:String(Boolean(n.deps.miAPI.isTemplateLess))})})}const as="/@api/users",os=new WeakMap;function cs(e,t){const s=Fe(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 ls(e,t,s,r){e.status(t).json({error:r,code:s})}function ds(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 us=new WeakMap,ps=new WeakMap;function hs(e){us.delete(e),ps.get(e)?.(),ps.delete(e)}async function gs(e,s){const r=function(e,t,s=C.homedir()){const r=y.createHash("sha256").update(`${O.resolve(e)}\n${t.replace(/\/+$/,"")}`).digest("hex").slice(0,16);return O.join(s,".pp-dev","users",`${r}.json`)}(s.projectRoot,s.miUrl,s.homeDir),n={project:O.resolve(s.projectRoot),miUrl:s.miUrl},i=t.createLogger();if(us.get(e)===r)return;hs(e),us.set(e,r);const a=ds(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=ds(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(O.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=>{us.get(e)===r&&(u.add(t.name),o&&d.add(t.name))}),g=e.onChange(()=>{us.get(e)===r&&(o?l||=!c:p())});ps.set(e,()=>{h(),g()});try{const n=await Promise.all(a.map(e=>s.checkToken(e.token)));if(us.get(e)!==r)return;a.forEach((s,r)=>{if(Re(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&&us.get(e)===r&&p(),a.length&&i.info(`${t.colors.blue("Restored")} ${a.length} ${t.colors.blue("saved user(s) from")} ${r}`)}function ms(e){const s=`${O.resolve(e.projectRoot)}\n${e.miUrl.replace(/\/+$/,"")}`;Be.context!==s&&(hs(Be),Be.useContext(s)),e.persist?e.miAPI.personalAccessToken?gs(Be,{projectRoot:e.projectRoot,miUrl:e.miUrl,checkToken:t=>De(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).")):hs(Be)}const fs="10mb",ys=(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 (${fs}).`:`The request body could not be read: ${e.message}`;s.status(n).json({error:i})};function ws(e){return(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0)+512}function vs(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 bs="<redacted>",ks=new RegExp(`(^|;\\s*)(${we}=)[^;]*`,"gi"),$s=new RegExp(`^(\\s*${we}=)[^;]*`,"i");function xs(e){const t={...e};if("string"==typeof t.authorization){const[e,s]=t.authorization.split(/\s+/,2);t.authorization=void 0===s?bs:`${e} ${bs}`}return void 0!==t.token&&(t.token=bs),"string"==typeof t.cookie&&(t.cookie=t.cookie.replace(ks,`$1$2${bs}`)),t}function Ss(e){const t={...e},s=t["set-cookie"],r=e=>e.replace($s,`$1${bs}`);return Array.isArray(s)?t["set-cookie"]=s.map(r):"string"==typeof s&&(t["set-cookie"]=r(s)),t}const As=/^\/(?:login|auth)(?:[/?#]|$)/i,Es=/pass(?:word|wd|code)?|pwd|secret|token|otp|mfa|2fa/i;function Ts(e,t){return Array.isArray(e)?e.map(e=>Ts(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,s])=>Es.test(e)?(t.any=!0,[e,bs]):[e,Ts(s,t)])):e}function Is(e,t,s){if(!s)return s;if(As.test(e))return Buffer.from(bs);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=>Es.test(e));return t.forEach(t=>e.set(t,bs)),t.length?Buffer.from(e.toString()):s}if("application/json"===r||r.endsWith("+json")){const e={any:!1},t=Ts(JSON.parse(s.toString("utf8")),e);return e.any?Buffer.from(JSON.stringify(t)):s}}catch{}return s}const Ps=["/@","/_next/","/__nextjs_"],Ns=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=L.cwd(),backupFolder:n="backups",distZipFolder:i=I.resolve(r,"dist-zip"),distZipFilename:a=t.createDefaultZipFileName(this.pageName),backupNameTemplate:o=`{${Rt}}-{${jt}}.zip`,versionFileTemplate:c="VERSION-v{packageversion}-{currentDate}.json",buildInputFolder:l,dateFormat:d=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,""),nextBuild:u,maxBackups:p=Ot,buildTimeoutMs:h=It,metaDir:g}=s||{};this.root=r,this.backupFolder=I.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?I.join(this.backupFolder,".pp-dev-meta"):I.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(I.join(this.metaDir,Ut),{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await d.promises.writeFile(I.join(this.metaDir,Ut),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=I.resolve(this.backupFolder,e);try{return await d.promises.stat(t),t}catch{return null}}backupName(e,t=new Date){return this.backupNameTemplate.replace(`{${Rt}}`,e).replace(`{${jt}}`,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+":Mt(e)).join(""),n=[{token:`{${Rt}}`,pattern:Mt(t)},{token:`{${jt}}`,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+=Mt(e.slice(a,r))+s,a=r+t.length;return new RegExp(`${i}${Mt(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(I.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(I.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=I.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=I.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 N.createHash("sha256").update(t).digest("hex")}buildBackupFingerprint(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("\n");return N.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===Dt}async pickTemplateVariablesFromBackupZip(e,t){const s=e.find(e=>I.basename(e)===Dt);if(!s)return null;const r=I.join(t,s),n=await d.promises.readFile(r);return{relativePath:s,content:n,actualHash:N.createHash("sha256").update(n).digest("hex"),manifestHash:null}}async resolveBackupAnalysisFromZip(e){const s=await d.promises.mkdtemp(I.join(R.tmpdir(),"pp-dev-backup-")),r=I.join(s,"backup.zip"),n=I.join(s,"extracted");try{await d.promises.mkdir(n,{recursive:!0}),await d.promises.writeFile(r,e),await Tt(r,n);const s=await this.normalizeExtractedRootDir(n),i=(await this.listFilesRecursive(s)).map(e=>this.pathToPosix(I.relative(s,e))),a=i.filter(e=>I.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=I.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=>I.basename(t)===I.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(I.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=I.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=I.join(s,e),n=await d.promises.readFile(r).catch(()=>null);if(!n)throw new Error(`VERSION manifest references missing file: ${e}`);const i=N.createHash("sha256").update(n).digest("hex");g[e]=i,i!==t&&m.push({relativePath:e,expected:t,actual:i}),this.isTemplateVariablesBasename(I.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=I.join(s,e),r=await d.promises.readFile(t),n=N.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=I.resolve(this.root,"public",Dt),t=await d.promises.readFile(e).catch(()=>null);return t?N.createHash("sha256").update(t).digest("hex"):null}async readPublicTemplateVariablesFile(){const e=I.resolve(this.root,"public",Dt);return await d.promises.readFile(e).catch(()=>null)}async saveTemplateVariablesFile(e){const t=I.resolve(this.root,"public",Dt);return await d.promises.mkdir(I.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(I.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=Nt("pp-dev build","node",[I.resolve(Bt,"./bin/pp-dev.js"),"build"],{cwd:this.root,env:Object.assign({},L.env,{NODE_ENV:"production"}),timeoutMs:this.buildTimeoutMs,signal:this.builds.signal});try{if(await this.logBuild("Build",e),this.buildInputFolder){const e=I.resolve(this.root,this.buildInputFolder);if(!await this.isDirectory(e))throw new Error(`Build input directory ${e} not found`);const t=await Et(e);return this.throwIfStopped("pp-dev build"),t}const t=I.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",Lt(e,{timeoutMs:this.buildTimeoutMs,signal:this.builds.signal}));const r=I.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 Et(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=H,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(Ie.has(l))this.#k=Ie.get(l);else{const t=new T.Agent({keepAlive:!1,...a?{rejectUnauthorized:!1}:{}});this.#k=A.create({baseURL:e,headers:r,timeout:3e4,maxRedirects:5,httpAgent:new E.Agent({keepAlive:!1}),httpsAgent:t}),Ie.set(l,this.#k)}this.appId=n,this.templateLess=i,this.assetsApi=new(o?ne:re)(this.#k),this.pageApi=new he(this.#k),this.pageTemplateApi=new ge(this.#k),this.pageVariableApi=new me(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),pe(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===Te);return s||(this.logger.warn(t.colors.yellow("Creating dev page template...")),s=await this.pageApi.create({enabled:"Y",name:Te,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 "${Te}" 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.#B(r,s):await this.#C(r,s)}catch(e){this.#O(e,r)}}async#B(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#C(e,t){return await this.pageApi.get(e,t)}#O(e,s){if(pe(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=Ae(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"!==Ae(e).code){const s=Ae(e);throw n.quiet||(this.logger.error(t.colors.red(`API request failed: ${s.userFriendlyMessage}`)),function(e,s,r){const n=Ae(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-=ws(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=ws(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(vs(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(vs(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=as,exports.VARIABLES_EDITOR_PATH=Qt,exports.createInternalServer=function({allowedHosts:e=[]}={}){const s=M();return s.use(t.createOriginGuard(e)),s.use(M.json({limit:fs})),s.use(M.urlencoded({extended:!0})),s.use(ys),s},exports.createRequestCaptureMiddleware=function(e,t=10485760,s=Be){return(r,n,i)=>{const a=r.url||"/",o=a.split("?")[0];if(Ps.some(e=>a.startsWith(e))||Ns.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=Is(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:xs(r.headers),requestBody:t,requestBodyTruncated:h,responseHeaders:Ss(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=je(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",`${Fe(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.extractZipSafe=Tt,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=Ae,exports.getUserNameFromHost=je,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=te(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(kt)){let e;d.info(t.colors.blue("Trying to authenticate and redirect to base"));const c=t=>{e=t};try{if(h?await St(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${kt}${encodeURIComponent("/")}`},r,u,c,d):await xt(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${kt}${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")),ee(u,o??"/",302))}catch(e){if(u.headersSent||u.writableEnded)return;return p()}}if(!m&&!f)return p();if(!h){return await xt(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${kt}${encodeURIComponent("/")}`},r,u,p,d)}return await St(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${kt}${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)}`)),bt(),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}`)),ee(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(He,"$2")}}(n),u=n.replace(He,"$1$2"),p=import("file-type"),h=t.createLogger(),g=e.sessionUsers??new Ue(l,function(e){return async t=>(await _e(e,{Cookie:`${we}=${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=X.get(e);return t||(t=new RegExp(`^https?://${K(e)}(?=[/?#]|$)`,"i"),X.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}`),Je.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&&je(r.headers.host)!==g.name){m=g.session;const t=m?(f=r.headers.cookie,y=m,[...Oe(f),`${we}=${y}`].join("; ")):function(e){const t=Oe(e);return t.length?t.join("; "):void 0}(r.headers.cookie);t?e.setHeader("cookie",t):e.removeHeader("cookie")}var f,y;Ze.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"]=$e(e.headers["set-cookie"],fe(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,`${fe(s)?"https":"http"}://${r}`):e}(e.headers.location,d,s));const n=function(e,t){if(!We.test(e.url??""))return;const s=je(e.headers.host);return void 0===s?void 0:t.get(s)}(s,l),i=Ze.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:`${Fe(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=je(s.headers.host)===a.name&&!t}if(!c){const t=function(e){const t=(e??[]).filter(e=>void 0===ke(e,we));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(Q(ze,"/login",Y(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}`),Qe(u)(e,s,r);const m=function(e){const t=e["content-type"];if("string"==typeof t&&t.trim()&&!Ge(t))return"pipe";const s=Number(e["content-length"]);return Number.isFinite(s)&&s>=10485760&&Ye(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 Qe("stream"===m?u:void 0)(e,s,r);const f=o.responseInterceptor(async(e,t,s,r)=>{r.setHeader(Ve,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);qe.test(e.pathname)&&(r.includes("<html")||r.includes("<body")||r.includes("<head")||r.includes("html>"))&&!je(s.headers.host)&&(t+=`<script>(${xe.toString()})(${n=d,JSON.stringify(n).replace(/</g,"\\u003c")})<\/script>`)}catch{}const r=s.headers.host??"";return Q(ze,"/login",Y(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=tt,maxSize:n=st,maxItems:i=rt,users:a=Be}=e,o=t.createLogger();return n===st&&i===rt||(it.maxSize=n,it.maxItems=i),s.cache=it,lt.has(a)||(lt.add(a),a.onRemove(e=>ut(e.name,"user removed")),a.onSessionChange(e=>ut(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(Ve)?pt(e,s,i.key):void 0;t&&ut(i.key,`${t} (${e.method} ${te(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 et.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&&(je(e.headers.host)!==s.name||be(e.headers.cookie,we)===s.session)}(e,i))return n();const u=it.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(Ve)?!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>=nt)}(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>nt&&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=ht(g);const e=Buffer.byteLength(h);if(200===s.statusCode&&e>0&&e<nt&&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};it.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=ht(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=Z(e,J(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=Z(t,J(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=ct,exports.isSecureRequest=fe,exports.redirect=ee,exports.registerInspectorRoutes=function(e,t,s=10485760,r=U){const n=V.get(e);if(n)return n.store=t,void(n.captureLimit=s);const i={store:t,captureLimit:s};V.set(e,i),e.get("/@api/requests",(e,t)=>{const{store:s}=i,r=q(e.query.limit),n=q(e.query.offset),a=q(e.query.method),o=q(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:W(s.memoryUsage),maxMemoryFormatted:W(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=z(s.requestHeaders["content-type"]),n=z(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})}),D(e,{path:H,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=I.resolve(e,s,"dev","types");return P.existsSync(r)?(P.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=$e,exports.runNextBuildProcess=Lt,exports.startKeepingUsers=ms,exports.startSyncAndUsers=function(e){const{distService:s,miAPI:r}=e,n=new Ht(e.server,{distService:s,miAPI:r});return is(e.internalServer,{distService:s,miAPI:r}),function(e,s){const r=os.get(e);if(r)return void(r.deps=s);const n={deps:s};os.set(e,n);const i=t.createLogger(),a=()=>n.deps.users??Be;e.get(as,(e,t)=>{const s=a();t.json({available:Boolean(n.deps.miAPI.personalAccessToken),users:s.list().map(t=>cs(t,e)),defaultUser:s.defaultUser?.name??null})}),e.put(`${as}/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 ls(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 ls(s,404,"NOT_FOUND",`There is no user named "${n}"`);else ls(s,400,"INVALID_NAME","name must be a user name or null")}),e.post(as,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 ls(s,400,"INVALID_KIND",'kind must be "token" or "session"');if(!r.personalAccessToken)return void ls(s,409,"ORIGINAL_TOKEN_REQUIRED","Adding users needs your own API token: set mi.token or MI_ACCESS_TOKEN.");const p=Re(l);if(p)return void ls(s,400,"INVALID_NAME",p);if(o.get(l))return void ls(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 ${Fe(e,r.name)}/login`),void s.status(201).json({user:cs(r,e)})}if(!d)return void ls(s,400,"TOKEN_REQUIRED","The API token is required");const h=o.context,g=await De(r,d);if(o.context!==h||n.deps.miAPI!==r||a()!==o)return void ls(s,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; add the user again");if(!g.ok)return void(g.rejected?ls(s,400,"INVALID_TOKEN",g.message):ls(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 ls(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 ${Fe(e,f.name)}`),s.status(201).json({user:cs(f,e)})}),e.patch(`${as}/: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 ls(s,404,"NOT_FOUND",`There is no user named "${c}"`);if("token"!==l.kind)return void ls(s,400,"NOT_EDITABLE","Only users added with an API token can be edited. Remove this user and add it again.");const h=Re(u);if(h)return void ls(s,400,"INVALID_NAME",h);if(u!==c&&o.get(u))return void ls(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 De(r,p);if(o.context!==e||n.deps.miAPI!==r||a()!==o)return void ls(s,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; edit the user again");if(!t.ok)return void(t.rejected?ls(s,400,"INVALID_TOKEN",t.message):ls(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 ls(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:cs(g,e)})}else s.json({user:cs(l,e)});else ls(s,409,"USER_CHANGED",`The user "${c}" changed meanwhile; edit it again`)}),e.delete(`${as}/: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()):ls(s,404,"NOT_FOUND",`There is no user named "${r}"`)})}(e.internalServer,{miAPI:r}),ms({persist:e.persistUsers,miAPI:r,projectRoot:e.projectRoot,miUrl:e.miUrl}),n},exports.urlReplacer=Y,exports.zipDirectoryToBuffer=Et;
2
+ //# sourceMappingURL=request-capture.middleware-Chm27VXb.js.map