@smart-cloud/publisher-exporter 1.1.46 → 1.1.48

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.
@@ -1 +1,11 @@
1
- import A from'fs/promises';import ss from'http';import An from'https';import S from'path';import'crypto';import'playwright';import'zlib';import'fast-glob';import'os';import'worker_threads';import'@aws-sdk/client-s3';import'@aws-sdk/lib-storage';import'mime-types';import'@aws-sdk/client-cloudfront';function jn(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function ls(e){let t=String(e??"").trim();if(!t)return "";let n=t;if(/^https?:\/\//i.test(n))try{n=new URL(n).pathname;}catch{return ""}if(n=n.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!n)return "";let s=n.endsWith("/"),r=n.replace(/^\/+/,"").split("/").map(a=>a.replace(/[^A-Za-z0-9._-]/g,"")).filter(a=>a.length>0&&a!=="."&&a!=="..");if(r.length===0)return "";let i=`/${r.join("/")}`;return s&&S.extname(i)===""&&(i+="/"),i==="/"?"":i}function Lt(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function ds(e){if(!e||typeof e!="object")return {};let t={};for(let[n,s]of Object.entries(e)){let r=n.trim();if(!r||!s||typeof s!="object")continue;let i=s,a={};if(typeof i.targetOrigin=="string"){let o=jn(i.targetOrigin);o&&(a.targetOrigin=o);}let c=Lt(i.extraReplacements);if(Object.keys(c).length>0&&(a.extraReplacements=c),i.s3&&typeof i.s3=="object"){let o={},u=i.s3;typeof u.bucket=="string"&&(o.bucket=u.bucket.trim()),typeof u.prefix=="string"&&(o.prefix=u.prefix.trim()),typeof u.region=="string"&&(o.region=u.region.trim()),typeof u.htmlCacheControl=="string"&&(o.htmlCacheControl=u.htmlCacheControl.trim()),typeof u.assetCacheControl=="string"&&(o.assetCacheControl=u.assetCacheControl.trim()),Object.keys(o).length>0&&(a.s3=o);}if(i.cloudFront&&typeof i.cloudFront=="object"){let o={},u=i.cloudFront;typeof u.distributionId=="string"&&(o.distributionId=u.distributionId.trim()),Array.isArray(u.invalidationPaths)&&(o.invalidationPaths=u.invalidationPaths.map(l=>String(l??"").trim()).filter(l=>l.length>0)),Object.keys(o).length>0&&(a.cloudFront=o);}t[r]=a;}return t}function _t(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function ps(e,t){if(!e||typeof e!="object")return null;let n=e,s=n.command;if(s!=="publish"&&s!=="crawl"&&s!=="deploy"&&s!=="invalidate"&&s!=="retry-timeouts"&&s!=="url"&&s!=="content-sync")return null;let r=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let i=String(n.id??`${s}-${t+1}`).trim();if(!i)return null;let a=String(n.deploymentProfile??"").trim(),c=String(n.url??"").trim(),o=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(l=>String(l??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],u=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(l=>String(l??"").trim()).filter(Boolean))]:[];return s==="content-sync"&&o.length===0?null:{id:i,enabled:n.enabled!==false,command:s,intervalMinutes:r,...s==="publish"||s==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(s==="publish"||s==="deploy"||s==="invalidate"||s==="content-sync")&&a?{deploymentProfile:a}:{},...c?{url:c}:{},...o.length>0?{postTypes:o}:{},...u.length>0?{listingPaths:u}:{},...typeof n.includeSubsites=="boolean"?{includeSubsites:n.includeSubsites}:{},...typeof n.includePostTypeArchives=="boolean"?{includePostTypeArchives:n.includePostTypeArchives}:{},...typeof n.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:n.includeTaxonomyArchives}:{},...typeof n.includeAuthorArchives=="boolean"?{includeAuthorArchives:n.includeAuthorArchives}:{},...typeof n.includeDateArchives=="boolean"?{includeDateArchives:n.includeDateArchives}:{},...typeof n.includePostsPage=="boolean"?{includePostsPage:n.includePostsPage}:{},...typeof n.includeSitemapChain=="boolean"?{includeSitemapChain:n.includeSitemapChain}:{}}}function Un(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((s,r)=>ps(s,r)).filter(s=>!!s):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function gs(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of ["accountId","siteId"]){let i=t[r];typeof i=="string"&&i.trim()!==""&&(n[r]=i.trim());}let s=Number(t.lastUpdate??0);return Number.isFinite(s)&&s>0&&(n.lastUpdate=Math.floor(s)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function Nt(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),s=String(t.siteId??"").trim(),r=t.subscriber===true,i=gs(t.siteSettings),a={...i??{},...n?{accountId:i?.accountId??n}:{},...s?{siteId:i?.siteId??s}:{},...i?.subscriber===true||r?{subscriber:true}:{}},c={},o=String(t.apiBase??"").trim();o&&(c.apiBase=o);let u=String(t.runtimeToken??t.nonce??"").trim();u&&(c.runtimeToken=u);let l=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();l&&(c.virtualAssetBaseUrl=l),Object.keys(a).length>0&&(c.siteSettings=a);let d=_t(t.subscriptionType);return d&&(c.subscriptionType=d),c}function fs(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function Ln(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function ms(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[s,r]of new Headers(t.headers).entries())n.set(s,r);return n}async function qn(e,t,n=5){let s=new URL(Ln(e)),r=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),i=s.protocol==="http:"?ss:An,a=ms(e,t);return await new Promise((c,o)=>{let u=i.request(s,{method:r,headers:Object.fromEntries(a.entries()),...s.protocol==="https:"?{rejectUnauthorized:false}:{}},l=>{let d=[];l.on("data",p=>{d.push(Buffer.isBuffer(p)?p:Buffer.from(p));}),l.on("error",o),l.on("end",()=>{let p=l.statusCode??0,g=l.headers.location;if(n>0&&g&&[301,302,303,307,308].includes(p)){c(qn(new URL(g,s),{method:p===303?"GET":r},n-1));return}let f=new Headers;for(let[w,m]of Object.entries(l.headers))Array.isArray(m)?f.set(w,m.join(", ")):typeof m=="string"&&f.set(w,m);c(new Response(Buffer.concat(d),{status:p,statusText:l.statusMessage??"",headers:f}));});});u.on("error",o),u.end();})}function hs(e){let t=Nt(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},s=String(n.accountId??"").trim(),r=String(n.siteId??"").trim(),i=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...i?{virtualAssetBaseUrl:i}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!s||!r||!i)return false;fs(e.sourceOrigin);let a=globalThis,o={...a.WpSuite??{},siteSettings:n,uploadUrl:i};return t.apiBase&&(o.apiBase=t.apiBase),a.WpSuite=o,true}async function ws(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!hs(e)){let r=e.wpsuite?.siteSettings,i=[String(r?.accountId??"").trim()?"":"accountId",String(r?.siteId??"").trim()?"":"siteId",t?"":"virtualAssetBaseUrl"].filter(Boolean);return {remote:null,diagnostic:{status:"invalid-runtime",virtualAssetBaseUrl:t,subscriptionType:null,error:`Missing WP Suite runtime field(s): ${i.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,s=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(o,u)=>{let l=Ln(o);if(l.startsWith(t)){let d=(()=>{try{return new URL(l).pathname}catch{return l}})();try{let p=e.ignoreHttpsErrors&&l.startsWith("https://")?await qn(o,u):await n(o,u);return s.push({path:d,status:p.status,ok:p.ok,error:null}),p}catch(p){throw s.push({path:d,status:null,ok:!1,error:p instanceof Error?p.message:String(p)}),p}}return n(o,u)}));let{getConfig:r}=await import('@smart-cloud/wpsuite-core'),i=await r("publisher"),a=i&&typeof i=="object"?i:null,c=_t(a?.subscriptionType);return {remote:a,diagnostic:{status:a?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:c??null,error:a?null:"WP Suite publisher config loader returned no configuration.",requests:s}}}catch(r){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:r instanceof Error?r.message:String(r),requests:s}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function ys(e,t){let n=ds(t?.deploymentProfiles),s=String(t?.defaultDeploymentProfile??"").trim(),r=n[s]?s:"",i=_t(t?.subscriptionType),a=Nt(e.wpsuite);return {...e,scheduler:Un(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:r,...i?{subscriptionType:i}:{},wpsuite:{...a,...a.siteSettings||i?{siteSettings:{...a.siteSettings??{},...a.siteSettings?.subscriber===true||i==="PROFESSIONAL"||i==="AGENCY"?{subscriber:true}:{}}}:{},...i?{subscriptionType:i}:{}}}}function qt(e,t){let s=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!s)return t;let r=s.split("/").map(i=>i.trim()).filter(i=>i.length>0&&i!=="."&&i!=="..");return r.length>0?r.join("/"):t}function Ss(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function On(e,t,n){let s=String(t||"").trim();return s&&S.isAbsolute(s)?S.resolve(s):S.resolve(e,qt(s,n))}async function G(e,t={}){let n=String("").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",s=await A.readFile(n,"utf8"),r=JSON.parse(s);r.sourceOrigin=r.sourceOrigin.replace(/\/$/,""),r.targetOrigin=jn(r.targetOrigin),r.ignoreHttpsErrors??=false,r.outputDir=String(r.outputDir||"export").trim()||"export",r.urlRewriteMode||=r.targetOrigin==="."?"relative":"absolute",r.noJavaScriptRenderPathPrefixes||=[],r.seedPaths||=[],r.generated404RequestPath=ls(r.generated404RequestPath),r.sitemapPaths||=["/sitemap_index.xml","/sitemap.xml"],r.allowedAssetHosts||=[],r.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],r.blockedPathPrefixes||=[],r.blockedSearchFragments||=[],r.concurrency||=1,r.maxPages||=0,r.extraReplacements=Lt(r.extraReplacements),r.postCrawlCopyMap=Lt(r.postCrawlCopyMap),r.logDir=String(r.logDir||"logs").trim()||"logs",r.verbose??=false,r.logLevel||=r.verbose?"debug":"info",r.s3SyncMode||="sdk-upload-delete",r.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},r.readiness.timeoutMs??=1500,r.readiness.fallbackWaitMs??=1500,r.viewport||={width:1440,height:1200},r.navigationTimeoutMs||=3e4,r.assetDownloadConcurrency=Number(r.assetDownloadConcurrency)>0?Number(r.assetDownloadConcurrency):r.concurrency,r.rewriteConcurrency=Number(r.rewriteConcurrency)>0?Number(r.rewriteConcurrency):r.assetDownloadConcurrency,r.wpsuite=Nt(r.wpsuite),r.scheduler=Un(void 0),r.deploymentProfiles={},r.defaultDeploymentProfile="",r.deploymentTargetOverride=String(r.deploymentTargetOverride??"").trim();let i=await ws(r);t.onRemotePublisherConfigDiagnostic?.(i.diagnostic);let a=ys(r,i.remote),c=Ss(),o=c?S.resolve(c,".."):"";return o?(a.outputDir=On(o,a.outputDir,"export"),a.logDir=On(o,a.logDir,"logs")):(S.isAbsolute(a.outputDir)||(a.outputDir=qt(a.outputDir,"export")),S.isAbsolute(a.logDir)||(a.logDir=qt(a.logDir,"logs"))),a}var Yn=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";Yn?S.join(Yn,"current-progress.json"):"";Promise.resolve();var qo=["SIGINT","SIGTERM"],It=new Set,Ct=new Map,jr=null;async function No(){let e=[...It];e.length!==0&&await Promise.allSettled(e.map(async t=>{It.delete(t),await A.rm(t,{recursive:true,force:true});}));}function Bo(){if(!(Ct.size>0))for(let e of qo){let t=()=>{jr||(jr=No().finally(()=>{for(let[n,s]of Ct)process.off(n,s);Ct.clear(),process.exit(1);}));};Ct.set(e,t),process.on(e,t);}}Bo();async function Kr(e=process.argv.slice(2)){let n=e.indexOf("--capture-baseline-cutoffs");if(n>=0){let a=String(e[n+1]||"").trim();if(!a)throw new Error("--capture-baseline-cutoffs requires a release job ID.");if(((await G()).scheduler?.rules??[]).some(u=>u.command==="content-sync"&&u.enabled!==false))throw new Error("Content-sync is unavailable in the free exporter runtime.");return}let s=e.indexOf("--establish-baselines");if(s>=0){let a=String(e[s+1]||"").trim();if(!a)throw new Error("--establish-baselines requires a release job ID.");if(((await G()).scheduler?.rules??[]).some(u=>u.command==="content-sync"&&u.enabled!==false))throw new Error("Content-sync is unavailable in the free exporter runtime.");return}throw new Error("Content-sync is unavailable in the free exporter runtime.")}Kr().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1);});
1
+ import A from'fs/promises';import ss from'http';import An from'https';import S from'path';import Vn,{createHash}from'crypto';import {request,chromium}from'playwright';import {gunzipSync}from'zlib';import Ts from'fast-glob';import {availableParallelism}from'os';import {Worker}from'worker_threads';import {S3Client,ListObjectsV2Command,HeadObjectCommand,GetObjectCommand,DeleteObjectsCommand}from'@aws-sdk/client-s3';import {Upload}from'@aws-sdk/lib-storage';import Uo from'mime-types';import {CloudFrontClient,waitUntilInvalidationCompleted,CreateInvalidationCommand}from'@aws-sdk/client-cloudfront';var es=new Set(["post-type","taxonomy","author","date","posts-page","listing"]);function Ce(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function ts(e){return new URL(e).pathname.split("/").filter(Boolean).some(n=>{try{return decodeURIComponent(n).endsWith("__trashed")}catch{return n.endsWith("__trashed")}})}function Et(e){return Array.isArray(e)?e.map(Et):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Et(n)])):e}function ns(e){return JSON.stringify(Et(e))}function oe(e){return createHash("sha256").update(ns(e)).digest("hex")}function bn(e){return oe({schemaVersion:1,wordpressFingerprint:e.wordpressFingerprint,targetFingerprint:e.targetFingerprint,sourceOrigin:e.sourceOrigin,sitemapPaths:[...e.sitemapPaths].sort(),blockedPathPrefixes:[...e.blockedPathPrefixes].sort(),assetPathPrefixes:[...e.assetPathPrefixes].sort(),noJavaScriptRenderPathPrefixes:[...e.noJavaScriptRenderPathPrefixes].sort(),urlRewriteMode:e.urlRewriteMode})}function Mt(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Unsupported source origin protocol: ${t.protocol}`);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,""),t.toString().replace(/\/$/,"")}function fe(e,t){let n=new URL(Mt(e)),s=new URL(t,`${n.toString().replace(/\/$/,"")}/`);if(s.origin!==n.origin)throw new Error(`Content-sync URL is outside the source origin: ${t}`);let r=n.pathname.replace(/\/+$/,"");if(r&&s.pathname!==r&&!s.pathname.startsWith(`${r}/`))throw new Error(`Content-sync URL is outside the source site path: ${t}`);return s.hash="",s.toString()}function We(e){let t=Ce((e.postTypes??[]).map(s=>String(s).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let n=Ce((e.listingPaths??[]).map(s=>{let r=String(s).trim();if(!r)return "";let i=new URL(r,"https://content-sync.invalid/");if(i.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(r))throw new Error("Content-sync listing routes must be same-site paths.");let a=`/${i.pathname.replace(/^\/+|\/+$/g,"")}`;return a==="/"?"/":`${a}/`}));return {postTypes:t,listingPaths:n,includeSubsites:e.includeSubsites===true,includePostTypeArchives:e.includePostTypeArchives!==false,includeTaxonomyArchives:e.includeTaxonomyArchives!==false,includeAuthorArchives:e.includeAuthorArchives===true,includeDateArchives:e.includeDateArchives===true,includePostsPage:e.includePostsPage!==false,includeSitemapChain:e.includeSitemapChain!==false}}function vn(e,t,n){return oe({schemaVersion:1,sourceOrigin:Mt(e),ruleId:t.trim(),scope:We(n)})}function Cn(e){return oe({schemaVersion:1,...e})}function Rn(e){let t=String(e.siteId??"").trim()||String(e.accountId??"").trim()||Mt(e.sourceOrigin);return `content-sync:${oe({siteIdentity:t,ruleId:e.ruleId.trim(),targetFingerprint:e.targetFingerprint}).slice(0,48)}`}function In(e){let t=[...e].sort((r,i)=>r.sequence-i.sequence),n=new Map,s=-1;for(let r of t){if(!Number.isSafeInteger(r.sequence)||r.sequence<=s)throw new Error("Content-sync journal events are not strictly ordered.");if(s=r.sequence,!Number.isSafeInteger(r.blogId)||r.blogId<1)throw new Error("Content-sync journal event has an invalid multisite identity.");let i=`${r.blogId}:${r.postType}:${r.postId}`,a=n.get(i);if(!a){n.set(i,{postId:r.postId,blogId:r.blogId,postType:r.postType,fromSequence:r.sequence,toSequence:r.sequence,before:r.before,after:r.after,operations:[r.operation],correlationIds:r.correlationId?[r.correlationId]:[]});continue}a.toSequence=r.sequence,a.after=r.after,a.operations.push(r.operation),r.correlationId&&!a.correlationIds.includes(r.correlationId)&&a.correlationIds.push(r.correlationId);}return [...n.values()].sort((r,i)=>r.fromSequence-i.fromSequence)}function Pn(e){return e?.status==="publish"&&!!e.url}function rs(e,t){return e==="post-type"?t.includePostTypeArchives:e==="taxonomy"?t.includeTaxonomyArchives:e==="author"?t.includeAuthorArchives:e==="date"?t.includeDateArchives:e==="posts-page"?t.includePostsPage:e==="listing"}function Ft(e){let t=We(e.scope),n=new Map;In(e.events);for(let s of e.events)for(let r of [s.before,s.after])for(let i of r?.archiveFamilies??[]){if(!es.has(i.kind)||!rs(i.kind,t))continue;let a={...i,url:fe(e.sourceOrigin,i.url)};n.set(`${a.kind}|${a.url}`,a);}for(let s of t.listingPaths){let r=fe(e.sourceOrigin,s);n.set(`listing|${r}`,{kind:"listing",url:r});}return [...n.values()].sort((s,r)=>s.url.localeCompare(r.url))}function xn(e){let t=We(e.scope),n=In(e.events),s=new Set,r=new Set,i=new Map(Ft({events:e.events,scope:t,sourceOrigin:e.sourceOrigin}).map(d=>[`${d.kind}|${d.url}`,d]));for(let d of n){let p=d.before,g=d.after,f=Pn(p),w=Pn(g);w&&g.url&&s.add(fe(e.sourceOrigin,g.url)),f&&p.url&&(!w||p.url!==g.url)&&r.add(fe(e.sourceOrigin,p.url));}let a=new Map(e.resolvedArchiveFamilies.map(d=>[`${d.kind}|${fe(e.sourceOrigin,d.url)}`,{...d,url:fe(e.sourceOrigin,d.url),pageUrls:Ce(d.pageUrls.map(p=>fe(e.sourceOrigin,p)))}])),c=[...i.entries()].map(([d,p])=>{let g=a.get(d);if(!g)throw new Error(`WordPress did not resolve archive family ${d}.`);return {...p,...g}}).sort((d,p)=>d.url.localeCompare(p.url)),o=Ce(c.flatMap(d=>d.pageUrls)),u=t.includeSitemapChain?Ce(e.sitemapUrls.map(d=>fe(e.sourceOrigin,d))):[],l={schemaVersion:1,generatedAt:new Date().toISOString(),jobId:e.jobId,ruleId:e.ruleId,consumerId:e.consumerId,coalesceKey:e.coalesceKey,scopeFingerprint:e.scopeFingerprint,targetFingerprint:e.targetFingerprint,baselineId:e.baselineId,fromSequence:e.fromSequence,toSequence:e.toSequence,eventCount:e.events.length,foldedCount:n.length,directRenderUrls:Ce([...s]),archiveFamilyUrls:o,sitemapUrls:u,deleteUrls:Ce([...r]),archiveFamilies:c};return {...l,impactHash:oe(l)}}function He(e){let{impactHash:t,...n}=e;if(e.schemaVersion!==1||!t)throw new Error("Invalid content-sync impact plan schema.");if(oe(n)!==t)throw new Error("Content-sync impact plan hash mismatch.");for(let s of [...e.directRenderUrls,...e.deleteUrls])if(ts(s))throw new Error(`Content-sync impact contains a WordPress trash alias instead of the last public URL: ${s}`)}var is="wp-json/smartcloud-static-publisher/v1/content-sync/",os=25*1024*1024,nt=class extends Error{status;code;constructor(t,n,s){super(s),this.name="ContentSyncApiError",this.status=t,this.code=n;}},rt=class{options;constructor(t){if(!t.runtimeToken.trim())throw new Error("Content-sync requires a WordPress runtime token.");this.options={...t,timeoutMs:t.timeoutMs??6e4};}endpoint(t){let n=this.options.sourceOrigin.replace(/\/+$/,"")+"/";return new URL(`${is}${t}`,n)}async post(t,n){let s=this.endpoint(t),r=Buffer.from(JSON.stringify(n),"utf8"),i=s.protocol==="https:"?An:ss,a=s.protocol==="https:"?new An.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((c,o)=>{let u=i.request(s,{method:"POST",agent:a,headers:{"content-type":"application/json","content-length":String(r.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},l=>{let d=[],p=0;l.on("data",g=>{if(p+=g.byteLength,p>os){l.destroy(new Error("Content-sync API response exceeded the size limit."));return}d.push(g);}),l.on("error",o),l.on("end",()=>{let g=Buffer.concat(d).toString("utf8"),f;try{f=g?JSON.parse(g):{};}catch{o(new nt(l.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let w=l.statusCode??500;if(w<200||w>=300){o(new nt(w,String(f.code??"request-failed"),String(f.message??`Content-sync API request failed (${w}).`)));return}c(f);});});u.on("timeout",()=>u.destroy(new Error(`Content-sync API request timed out: ${t}`))),u.on("error",o),u.end(r);})}async head(t){return this.post("head",t)}async unboundHead(t,n){return this.post("head",{postTypes:t,includeSubsites:n})}async events(t){let n=[],s=t.afterSequence,r=new Set(t.postTypes);for(;s<t.throughSequence;){let i=await this.post("events",{...t,afterSequence:s,limit:250});if(i.fromSequence!==s||i.throughSequence!==t.throughSequence||i.nextSequence<s||i.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(i.items))throw new Error("Content-sync API returned a malformed event page.");let a=s;for(let c of i.items){if(!Number.isSafeInteger(c.sequence)||c.sequence<=a||c.sequence>t.throughSequence||!Number.isSafeInteger(c.postId)||c.postId<=0||!Number.isSafeInteger(c.blogId)||c.blogId<=0||!r.has(c.postType)||typeof c.operation!="string"||!c.operation)throw new Error("Content-sync API returned an invalid or out-of-scope journal event.");a=c.sequence;}if(i.items.length>0&&i.nextSequence!==a)throw new Error("Content-sync API event cursor does not match the final returned event.");if(n.push(...i.items),!i.hasMore)break;if(i.nextSequence===s)throw new Error("Content-sync API event pagination did not advance.");s=i.nextSequence;}if(t.throughSequence>t.afterSequence&&n.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return n}async resolveImpactFamilies(t,n){let s=await this.post("impact",{families:t,includeSubsites:n});return Array.isArray(s.families)?s.families:[]}async releaseFingerprint(t=false){let n=await this.post("fingerprint",{includeSubsites:t}),s=String(n.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(s))throw new Error("WordPress returned an invalid release fingerprint.");return s}async establishBaseline(t){return this.post("baseline",t)}async acknowledge(t){return this.post("ack",t)}};function st(e){let t=S.resolve(e);return {state:S.join(t,"content-sync-state.json"),current:S.join(t,"content-sync-current.json"),impact:S.join(t,"content-sync-impact-plan.json"),checkpoint:S.join(t,"content-sync-checkpoint.json"),baseline:S.join(t,"content-sync-baseline.json"),releaseCutoff:S.join(t,"content-sync-release-cutoff.json"),candidateManifest:S.join(t,"content-sync-candidate-manifest.json"),trustedManifest:S.join(t,"crawl-manifest.json"),invalidation:S.join(t,"content-sync-invalidation.json"),deployPlan:S.join(t,"deploy-plan.json")}}async function Dt(e){let t=await ze(e.releaseCutoff);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.entries||typeof n.entries!="object"||Array.isArray(n.entries))throw new Error("Invalid content-sync release-cutoff store.");return n}async function Tn(e,t){await ke(e.releaseCutoff,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function ke(e,t){await A.mkdir(S.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(n,JSON.stringify(t,null,2),"utf8"),await A.rename(n,e);}async function ze(e){try{return JSON.parse(await A.readFile(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new Error(`Invalid or unreadable content-sync state file ${e}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async function Ot(e){let t=await ze(e.baseline);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.entries||typeof n.entries!="object"||Array.isArray(n.entries))throw new Error("Invalid content-sync baseline store.");return n}async function kn(e,t){await ke(e.baseline,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function jt(e){let t=await ze(e.current);if(t===null)return null;let n=t;if(n.schemaVersion!==1||typeof n.jobId!="string"||typeof n.phase!="string"||!Number.isSafeInteger(n.fromSequence)||!Number.isSafeInteger(n.toSequence))throw new Error("Invalid content-sync current-range state.");return n}async function $n(e,t){await ke(e.current,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function En(e){let t=await ze(e.impact);if(t===null)return null;let n=t;return He(n),n}async function Mn(e,t){He(t),await ke(e.impact,t);}async function Fn(e,t){await ke(e.checkpoint,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function it(e){let t=await ze(e.state);if(t===null)return {schemaVersion:1,updatedAt:"",rules:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.rules||typeof n.rules!="object"||Array.isArray(n.rules))throw new Error("Invalid content-sync state store.");return n}async function ot(e,t){await ke(e.state,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Ut(e){await Promise.all([e.current,e.checkpoint].map(async t=>{try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}));}async function Dn(e,t){let n=await jt(e);return !n||n.coalesceKey!==t?false:(await Promise.all([e.current,e.checkpoint,e.impact,e.candidateManifest,e.invalidation,e.deployPlan].map(async s=>{try{await A.unlink(s);}catch(r){if(r.code!=="ENOENT")throw r}})),true)}function jn(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function ls(e){let t=String(e??"").trim();if(!t)return "";let n=t;if(/^https?:\/\//i.test(n))try{n=new URL(n).pathname;}catch{return ""}if(n=n.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!n)return "";let s=n.endsWith("/"),r=n.replace(/^\/+/,"").split("/").map(a=>a.replace(/[^A-Za-z0-9._-]/g,"")).filter(a=>a.length>0&&a!=="."&&a!=="..");if(r.length===0)return "";let i=`/${r.join("/")}`;return s&&S.extname(i)===""&&(i+="/"),i==="/"?"":i}function Lt(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function ds(e){if(!e||typeof e!="object")return {};let t={};for(let[n,s]of Object.entries(e)){let r=n.trim();if(!r||!s||typeof s!="object")continue;let i=s,a={};if(typeof i.targetOrigin=="string"){let o=jn(i.targetOrigin);o&&(a.targetOrigin=o);}let c=Lt(i.extraReplacements);if(Object.keys(c).length>0&&(a.extraReplacements=c),i.s3&&typeof i.s3=="object"){let o={},u=i.s3;typeof u.bucket=="string"&&(o.bucket=u.bucket.trim()),typeof u.prefix=="string"&&(o.prefix=u.prefix.trim()),typeof u.region=="string"&&(o.region=u.region.trim()),typeof u.htmlCacheControl=="string"&&(o.htmlCacheControl=u.htmlCacheControl.trim()),typeof u.assetCacheControl=="string"&&(o.assetCacheControl=u.assetCacheControl.trim()),Object.keys(o).length>0&&(a.s3=o);}if(i.cloudFront&&typeof i.cloudFront=="object"){let o={},u=i.cloudFront;typeof u.distributionId=="string"&&(o.distributionId=u.distributionId.trim()),Array.isArray(u.invalidationPaths)&&(o.invalidationPaths=u.invalidationPaths.map(l=>String(l??"").trim()).filter(l=>l.length>0)),Object.keys(o).length>0&&(a.cloudFront=o);}t[r]=a;}return t}function _t(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function ps(e,t){if(!e||typeof e!="object")return null;let n=e,s=n.command;if(s!=="publish"&&s!=="crawl"&&s!=="deploy"&&s!=="invalidate"&&s!=="retry-timeouts"&&s!=="url"&&s!=="content-sync")return null;let r=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let i=String(n.id??`${s}-${t+1}`).trim();if(!i)return null;let a=String(n.deploymentProfile??"").trim(),c=String(n.url??"").trim(),o=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(l=>String(l??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],u=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(l=>String(l??"").trim()).filter(Boolean))]:[];return s==="content-sync"&&o.length===0?null:{id:i,enabled:n.enabled!==false,command:s,intervalMinutes:r,...s==="publish"||s==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(s==="publish"||s==="deploy"||s==="invalidate"||s==="content-sync")&&a?{deploymentProfile:a}:{},...c?{url:c}:{},...o.length>0?{postTypes:o}:{},...u.length>0?{listingPaths:u}:{},...typeof n.includeSubsites=="boolean"?{includeSubsites:n.includeSubsites}:{},...typeof n.includePostTypeArchives=="boolean"?{includePostTypeArchives:n.includePostTypeArchives}:{},...typeof n.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:n.includeTaxonomyArchives}:{},...typeof n.includeAuthorArchives=="boolean"?{includeAuthorArchives:n.includeAuthorArchives}:{},...typeof n.includeDateArchives=="boolean"?{includeDateArchives:n.includeDateArchives}:{},...typeof n.includePostsPage=="boolean"?{includePostsPage:n.includePostsPage}:{},...typeof n.includeSitemapChain=="boolean"?{includeSitemapChain:n.includeSitemapChain}:{}}}function Un(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((s,r)=>ps(s,r)).filter(s=>!!s):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function gs(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of ["accountId","siteId"]){let i=t[r];typeof i=="string"&&i.trim()!==""&&(n[r]=i.trim());}let s=Number(t.lastUpdate??0);return Number.isFinite(s)&&s>0&&(n.lastUpdate=Math.floor(s)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function Nt(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),s=String(t.siteId??"").trim(),r=t.subscriber===true,i=gs(t.siteSettings),a={...i??{},...n?{accountId:i?.accountId??n}:{},...s?{siteId:i?.siteId??s}:{},...i?.subscriber===true||r?{subscriber:true}:{}},c={},o=String(t.apiBase??"").trim();o&&(c.apiBase=o);let u=String(t.runtimeToken??t.nonce??"").trim();u&&(c.runtimeToken=u);let l=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();l&&(c.virtualAssetBaseUrl=l),Object.keys(a).length>0&&(c.siteSettings=a);let d=_t(t.subscriptionType);return d&&(c.subscriptionType=d),c}function fs(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function Ln(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function ms(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[s,r]of new Headers(t.headers).entries())n.set(s,r);return n}async function qn(e,t,n=5){let s=new URL(Ln(e)),r=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),i=s.protocol==="http:"?ss:An,a=ms(e,t);return await new Promise((c,o)=>{let u=i.request(s,{method:r,headers:Object.fromEntries(a.entries()),...s.protocol==="https:"?{rejectUnauthorized:false}:{}},l=>{let d=[];l.on("data",p=>{d.push(Buffer.isBuffer(p)?p:Buffer.from(p));}),l.on("error",o),l.on("end",()=>{let p=l.statusCode??0,g=l.headers.location;if(n>0&&g&&[301,302,303,307,308].includes(p)){c(qn(new URL(g,s),{method:p===303?"GET":r},n-1));return}let f=new Headers;for(let[w,m]of Object.entries(l.headers))Array.isArray(m)?f.set(w,m.join(", ")):typeof m=="string"&&f.set(w,m);c(new Response(Buffer.concat(d),{status:p,statusText:l.statusMessage??"",headers:f}));});});u.on("error",o),u.end();})}function hs(e){let t=Nt(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},s=String(n.accountId??"").trim(),r=String(n.siteId??"").trim(),i=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...i?{virtualAssetBaseUrl:i}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!s||!r||!i)return false;fs(e.sourceOrigin);let a=globalThis,o={...a.WpSuite??{},siteSettings:n,uploadUrl:i};return t.apiBase&&(o.apiBase=t.apiBase),a.WpSuite=o,true}async function ws(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!hs(e)){let r=e.wpsuite?.siteSettings,i=[String(r?.accountId??"").trim()?"":"accountId",String(r?.siteId??"").trim()?"":"siteId",t?"":"virtualAssetBaseUrl"].filter(Boolean);return {remote:null,diagnostic:{status:"invalid-runtime",virtualAssetBaseUrl:t,subscriptionType:null,error:`Missing WP Suite runtime field(s): ${i.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,s=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(o,u)=>{let l=Ln(o);if(l.startsWith(t)){let d=(()=>{try{return new URL(l).pathname}catch{return l}})();try{let p=e.ignoreHttpsErrors&&l.startsWith("https://")?await qn(o,u):await n(o,u);return s.push({path:d,status:p.status,ok:p.ok,error:null}),p}catch(p){throw s.push({path:d,status:null,ok:!1,error:p instanceof Error?p.message:String(p)}),p}}return n(o,u)}));let{getConfig:r}=await import('@smart-cloud/wpsuite-core'),i=await r("publisher"),a=i&&typeof i=="object"?i:null,c=_t(a?.subscriptionType);return {remote:a,diagnostic:{status:a?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:c??null,error:a?null:"WP Suite publisher config loader returned no configuration.",requests:s}}}catch(r){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:r instanceof Error?r.message:String(r),requests:s}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function ys(e,t){let n=ds(t?.deploymentProfiles),s=String(t?.defaultDeploymentProfile??"").trim(),r=n[s]?s:"",i=_t(t?.subscriptionType),a=Nt(e.wpsuite);return {...e,scheduler:Un(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:r,...i?{subscriptionType:i}:{},wpsuite:{...a,...a.siteSettings||i?{siteSettings:{...a.siteSettings??{},...a.siteSettings?.subscriber===true||i==="PROFESSIONAL"||i==="AGENCY"?{subscriber:true}:{}}}:{},...i?{subscriptionType:i}:{}}}}function qt(e,t){let s=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!s)return t;let r=s.split("/").map(i=>i.trim()).filter(i=>i.length>0&&i!=="."&&i!=="..");return r.length>0?r.join("/"):t}function Ss(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function On(e,t,n){let s=String(t||"").trim();return s&&S.isAbsolute(s)?S.resolve(s):S.resolve(e,qt(s,n))}async function ne(e,t={}){let n=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",s=await A.readFile(n,"utf8"),r=JSON.parse(s);r.sourceOrigin=r.sourceOrigin.replace(/\/$/,""),r.targetOrigin=jn(r.targetOrigin),r.ignoreHttpsErrors??=false,r.outputDir=String(r.outputDir||"export").trim()||"export",r.urlRewriteMode||=r.targetOrigin==="."?"relative":"absolute",r.noJavaScriptRenderPathPrefixes||=[],r.seedPaths||=[],r.generated404RequestPath=ls(r.generated404RequestPath),r.sitemapPaths||=["/sitemap_index.xml","/sitemap.xml"],r.allowedAssetHosts||=[],r.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],r.blockedPathPrefixes||=[],r.blockedSearchFragments||=[],r.concurrency||=1,r.maxPages||=0,r.extraReplacements=Lt(r.extraReplacements),r.postCrawlCopyMap=Lt(r.postCrawlCopyMap),r.logDir=String(r.logDir||"logs").trim()||"logs",r.verbose??=false,r.logLevel||=r.verbose?"debug":"info",r.s3SyncMode||="sdk-upload-delete",r.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},r.readiness.timeoutMs??=1500,r.readiness.fallbackWaitMs??=1500,r.viewport||={width:1440,height:1200},r.navigationTimeoutMs||=3e4,r.assetDownloadConcurrency=Number(r.assetDownloadConcurrency)>0?Number(r.assetDownloadConcurrency):r.concurrency,r.rewriteConcurrency=Number(r.rewriteConcurrency)>0?Number(r.rewriteConcurrency):r.assetDownloadConcurrency,r.wpsuite=Nt(r.wpsuite),r.scheduler=Un(void 0),r.deploymentProfiles={},r.defaultDeploymentProfile="",r.deploymentTargetOverride=String(r.deploymentTargetOverride??"").trim();let i=await ws(r);t.onRemotePublisherConfigDiagnostic?.(i.diagnostic);let a=ys(r,i.remote),c=Ss(),o=c?S.resolve(c,".."):"";return o?(a.outputDir=On(o,a.outputDir,"export"),a.logDir=On(o,a.logDir,"logs")):(S.isAbsolute(a.outputDir)||(a.outputDir=qt(a.outputDir,"export")),S.isAbsolute(a.logDir)||(a.logDir=qt(a.logDir,"logs"))),a}var Ps=".deploy-plan.json",bs="deploy-plan.json",vs=".crawl-incomplete.json",Cs="crawl-incomplete.json";function _n(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function Nn(e){let t=String(e||"").replace(/\\/g,"/").replace(/^\/+/,"").trim(),n=S.posix.normalize(t);return !t||!n||n==="."||/^[a-zA-Z]:/.test(n)||n.startsWith("../")||n===".."?null:n}function Rs(e){let t=String(e||"").trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("*")||t.includes("#"))return null;try{let n=new URL(t,"https://content-sync.invalid");return n.origin!=="https://content-sync.invalid"?null:`${S.posix.normalize(n.pathname)}${n.search}`}catch{return null}}function he(e){return [...new Set(e.map(Nn).filter(t=>t!==null))]}function Bn(e,t){let n={generatedAt:String(t.generatedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir),runMode:t.runMode,crawlMode:t.crawlMode,fullSyncRequired:!!t.fullSyncRequired,changedFiles:he(t.changedFiles||[]),deletedFiles:he(t.deletedFiles||[]),rewriteTargets:he(t.rewriteTargets||[])};return t.schemaVersion===2?{...n,schemaVersion:2,runMode:"content-sync",crawlMode:"incremental",fullSyncRequired:false,consumerId:String(t.consumerId||"").trim(),fromSequence:Math.max(0,Number(t.fromSequence)||0),toSequence:Math.max(0,Number(t.toSequence)||0),impactHash:String(t.impactHash||"").trim(),uploadGroups:{assets:he(t.uploadGroups?.assets||[]),content:he(t.uploadGroups?.content||[]),listings:he(t.uploadGroups?.listings||[]),sitemapLeaves:he(t.uploadGroups?.sitemapLeaves||[]),sitemapIndexes:he(t.uploadGroups?.sitemapIndexes||[])},invalidationPaths:[...new Set((t.invalidationPaths||[]).map(Rs).filter(s=>s!==null))].sort()}:{schemaVersion:1,...n,runMode:t.runMode}}function Is(e){if(!e||typeof e!="object")return false;let t=e;if(t.schemaVersion===2){let n=t;return n.runMode==="content-sync"&&n.crawlMode==="incremental"&&n.fullSyncRequired===false&&typeof n.generatedAt=="string"&&typeof n.outputDir=="string"&&typeof n.consumerId=="string"&&n.consumerId.trim()!==""&&Number.isSafeInteger(n.fromSequence)&&Number.isSafeInteger(n.toSequence)&&Number(n.toSequence)>=Number(n.fromSequence)&&typeof n.impactHash=="string"&&/^[a-f0-9]{64}$/.test(n.impactHash)&&Array.isArray(n.changedFiles)&&Array.isArray(n.deletedFiles)&&Array.isArray(n.rewriteTargets)&&!!n.uploadGroups&&Array.isArray(n.uploadGroups.assets)&&Array.isArray(n.uploadGroups.content)&&Array.isArray(n.uploadGroups.listings)&&Array.isArray(n.uploadGroups.sitemapLeaves)&&Array.isArray(n.uploadGroups.sitemapIndexes)&&Array.isArray(n.invalidationPaths)}return t.schemaVersion===1&&typeof t.generatedAt=="string"&&typeof t.outputDir=="string"&&(t.runMode==="full"||t.runMode==="retry-timeouts"||t.runMode==="single-url")&&(t.crawlMode==="full"||t.crawlMode==="incremental")&&typeof t.fullSyncRequired=="boolean"&&Array.isArray(t.changedFiles)&&Array.isArray(t.deletedFiles)&&Array.isArray(t.rewriteTargets)}function Bt(e){let t=S.join(S.resolve(e.outputDir),Ps),n=_n();return n?[S.join(n,bs),t]:[t]}function Wt(e){let t=S.join(S.resolve(e.outputDir),vs),n=_n();return n?[S.join(n,Cs),t]:[t]}function we(e,t){let n=S.resolve(e),s=S.resolve(t),r=S.relative(n,s).replace(/\\/g,"/");return Nn(r)}async function at(e){let t=S.resolve(e.outputDir);for(let n of Bt(e))try{let s=await A.readFile(n,"utf8"),r=JSON.parse(s);if(!Is(r)||S.resolve(r.outputDir)!==t)continue;return Bn(e,r)}catch{}return null}async function Ht(e,t){let n=Bn(e,t);for(let s of Bt(e)){await A.mkdir(S.dirname(s),{recursive:true});let r=`${s}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(r,JSON.stringify(n,null,2),"utf8"),await A.rename(r,s);}}async function $e(e){for(let t of Bt(e))try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}async function Wn(e,t){let n={schemaVersion:1,startedAt:String(t.startedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir)};for(let s of Wt(e)){await A.mkdir(S.dirname(s),{recursive:true});let r=`${s}.${process.pid}.tmp`;await A.writeFile(r,JSON.stringify(n,null,2),"utf8"),await A.rename(r,s);}}async function Hn(e){let t=S.resolve(e.outputDir);for(let n of Wt(e)){let s;try{s=await A.readFile(n,"utf8");}catch(i){if(i.code==="ENOENT")continue;throw i}let r;try{r=JSON.parse(s);}catch{throw new Error(`Invalid incomplete crawl marker: ${n}`)}if(r.schemaVersion!==1||typeof r.startedAt!="string"||typeof r.outputDir!="string"||S.resolve(r.outputDir)!==t)throw new Error(`Invalid incomplete crawl marker: ${n}`);return {schemaVersion:1,startedAt:r.startedAt,outputDir:t}}return null}async function zn(e){for(let t of Wt(e))try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}function Je(e,t=10){return Vn.createHash("sha1").update(e).digest("hex").slice(0,t)}async function xs(e){await A.mkdir(S.dirname(e),{recursive:true});}async function Ve(e,t,n){await xs(e);let s=S.join(S.dirname(e),`.${S.basename(e)}.${process.pid}.${Date.now()}.${Vn.randomBytes(6).toString("hex")}.tmp`);try{typeof t=="string"?await A.writeFile(s,t,n??"utf8"):await A.writeFile(s,t),await A.rename(s,e);}catch(r){throw await A.unlink(s).catch(()=>{}),r}}function ye(e){return [".html",".htm",".css",".js",".mjs",".json",".xml",".xsl",".txt",".svg",".map",".enc",".jws"].includes(S.extname(e).toLowerCase())}function ce(e){return e.replace(/&quot;/g,'"').replace(/&#34;/g,'"').replace(/&apos;/g,"'").replace(/&#39;/g,"'").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")}function Ee(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ct(e){return e.replace(/\//g,"\\/")}function Qn(e){return e.replace(/\//g,"\\\\/")}function As(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let n=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${n}`}catch{return null}}function Jn(e,t,n){if(!t)return;e[t]=n;let s=ct(t),r=ct(n);e[s]=r;let i=Qn(t),a=Qn(n);e[i]=a;let c=Ee(t),o=Ee(n);e[c]=o;let u=Ee(s),l=Ee(r);e[u]=l;let d=Ee(i),p=Ee(a);e[d]=p;}function ut(e,t,n){Jn(e,t,n);let s=As(t);s&&s!==t&&Jn(e,s,n);}function zt(e,t){let n=t.startsWith("/")?t:`/${t}`,s=(e||"").replace(/\/$/,"");return !s||s==="."||s==="/"?n:`${s}${n}`}function Kn(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function Gn(e,t,n){if(!t)return n;let s=S.dirname(S.resolve(t)),r=S.resolve(e,n.replace(/^\/+/,"")),i=S.relative(s,r).replace(/\\/g,"/");return i?(i.startsWith(".")||(i=`./${i}`),i):"."}var Ms=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],Fs=new Set([".html",".htm"]),Zn="WPSuite.io Static Publisher",Ds=Zn.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function js(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function Us(e,t,n){return js(t)?e.replace(new RegExp(`(?<!:)${Os(t)}`,"g"),n):e.split(t).join(n)}function Ls(e,t,n){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!n)return false;let r=S.extname(n).toLowerCase();return Fs.has(r)?/<head\b|<html\b|<!doctype html/i.test(t):false}function qs(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${Ds}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${Zn}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let s=e.includes(`\r
2
+ `)?`\r
3
+ `:`
4
+ `;return e.replace(/<head\b[^>]*>/i,r=>`${r}${s} ${t}`)}function _s(e){let t=ce(e).trim();return t.startsWith("{")||t.startsWith("[")||t.includes("\\/")||/"@context"|"@type"/.test(t)}function Ns(e,t){let n=[...new Set(t)].filter(i=>i.includes("/")&&!/\\+\//.test(i)).map(i=>[i,ct(i)]).filter(([i,a])=>i!==a).sort((i,a)=>a[0].length-i[0].length);if(!n.length)return e;let s=i=>{let a=i;for(let[c,o]of n)a=a.split(c).join(o);return a},r=e.replace(/(<script\b[^>]*\btype=["']application\/(?:ld\+)?json["'][^>]*>)([\s\S]*?)(<\/script>)/gi,(i,a,c,o)=>`${a}${s(c)}${o}`);return r=r.replace(/(<meta\b[^>]*\bcontent=(['"]))([\s\S]*?)(\2[^>]*>)/gi,(i,a,c,o,u)=>_s(o)?`${a}${s(o)}${u}`:i),r}function Bs(e,t){if(!t)return null;let n=S.dirname(S.resolve(t)),s=S.resolve(e.outputDir),r=S.relative(n,s).replace(/\\/g,"/");return r?(r.startsWith(".")||(r=`./${r}`),r.endsWith("/")?r:`${r}/`):"./"}function Ws(e,t,n){let s=Bs(t,n);if(!s)return e;let r=e;for(let i of Ms){let a=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`(?:\\.{1,}/)+${a}`,"g"),o=new RegExp(`(?<!\\.)/${a}`,"g");r=r.replace(c,`${s}${i}`).replace(o,`${s}${i}`);let u=i.replace(/\//g,"\\/"),l=s.replace(/\//g,"\\/"),d=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),p=new RegExp(`(?:\\.{1,}\\\\/)+${d}`,"g"),g=new RegExp(`(?:\\.{1,}(?:\\\\/|\\\\))+${d}`,"g"),f=new RegExp(`(?<![\\.\\\\])\\/${d}`,"g");r=r.replace(p,`${l}${u}`).replace(g,`${l}${u}`).replace(f,`${l}${u}`);}return r}function Jt(e,t,n){if(e.urlRewriteMode==="absolute")return t;let s=(()=>{try{return new URL(t,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin)}catch{return null}})(),r=s?s.pathname:Kn(t,e.targetOrigin),i=s?`${s.search}${s.hash}`:"";return e.urlRewriteMode==="root-relative"?`${r}${i}`:`${Gn(e.outputDir,n,r)}${i}`}function Qt(e,t,n,s,r){ut(e,n,Jt(t,s,r));}function Hs(e,t,n,s,r){if(!n||n===s)return;ut(e,n,s);let i=Jt(t,n,r),a=Jt(t,s,r);ut(e,i,a);}function Vt(e,t,n,s,r={}){let i=e,a={};Qt(a,t,t.sourceOrigin,t.targetOrigin,s);for(let[o,u]of Object.entries(t.extraReplacements))Qt(a,t,o,u,s);for(let[o,u]of Object.entries(n))Qt(a,t,o,u,s);for(let[o,u]of Object.entries(r)){let l=n[o];!l||l===u||Hs(a,t,u,l,s);}let c=Object.entries(a).sort((o,u)=>u[0].length-o[0].length);for(let[o,u]of c)i=Us(i,o,u);return t.urlRewriteMode!=="absolute"&&(i=Ws(i,t,s)),i=Ns(i,c.map(([,o])=>o)),Ls(t,i,s)&&(i=qs(i)),i}async function zs(e,t,n,s){let r=S.join(e.outputDir,s),i=S.extname(r).toLowerCase(),a;try{a=await A.readFile(r,"utf8");}catch(u){if(u.code!=="ENOENT")throw u;return {changed:false}}let o=Vt(a,e,t,i===".js"||i===".mjs"?void 0:r,n);return o!==a?(await Ve(r,o,"utf8"),{changed:true}):{changed:false}}async function Qs(e,t){return await new Promise((n,s)=>{let r=o=>{if(c(),o?.error){s(new Error(o.error));return}n({changed:!!o?.changed});},i=o=>{c(),s(o);},a=o=>{c(),o!==0&&s(new Error(`Rewrite worker exited with code ${o}.`));},c=()=>{e.off("message",r),e.off("error",i),e.off("exit",a);};e.on("message",r),e.on("error",i),e.on("exit",a),e.postMessage({file:t});})}async function lt(e,t,n={}){let r=(n.files?[...new Set(n.files)].map(p=>S.resolve(p)).filter(p=>p.startsWith(S.resolve(e.outputDir))).map(p=>S.relative(e.outputDir,p).replace(/\\/g,"/")).filter(p=>p.length>0):await Ts(["**/*"],{cwd:e.outputDir,onlyFiles:true,dot:true})).filter(p=>p!=="asset-map.json"&&ye(p)),i=0;if(r.length===0)return 0;let a=Math.max(1,Number(e.rewriteConcurrency||e.assetDownloadConcurrency||1)),c=Math.max(1,Math.min(a,r.length,availableParallelism()));await n.onStart?.({totalFiles:r.length,workerCount:c});let o=0,u=0,l=null;if(c===1){for(let p of r){let g=await zs(e,t,n.previousAssetMap??{},p);g.changed&&(i+=1),u+=1,await n.onProgress?.({index:u,totalFiles:r.length,changedTextFiles:i,file:p,changed:g.changed});}return i}let d=Array.from({length:c},async()=>{let p=new Worker(new URL("./rewrite-worker.js",import.meta.url),{workerData:{config:e,assetMap:t,previousAssetMap:n.previousAssetMap??{}}});try{for(;!l;){let g=o;if(g>=r.length)return;o+=1;let f=r[g],w=await Qs(p,f);w.changed&&(i+=1),u+=1,await n.onProgress?.({index:u,totalFiles:r.length,changedTextFiles:i,file:f,changed:w.changed});}}catch(g){throw l=g instanceof Error?g:new Error(String(g)),l}finally{await p.terminate().catch(()=>{});}});return await Promise.all(d),i}var ie={error:0,warn:1,info:2,debug:3},Js=/^(?:authorization|proxyAuthorization|runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken|xStaticPublisherToken|xApiKey)$/i;function Re(e){return e.replace(/((?:x-static-publisher-token|authorization|proxy-authorization|x-api-key|aws-access-key-id|aws-secret-access-key|aws-session-token)\s*:\s*)[^\r\n]+/gi,"$1[REDACTED]").replace(/\b(Basic|Bearer)\s+[^\s]+/gi,"$1 [REDACTED]").replace(/([?&](?:token|access_token|refresh_token|api_key|key|nonce)=)[^&\s]+/gi,"$1[REDACTED]").replace(/((?:"|')?(?:runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken)(?:"|')?\s*[:=]\s*(?:"|'))[^"']+/gi,"$1[REDACTED]")}function pt(e){return typeof e=="string"?Re(e):Array.isArray(e)?e.map(t=>pt(t)):e instanceof Error?{name:e.name,message:Re(e.message),...e.stack?{stack:Re(e.stack)}:{}}:e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Js.test(t)?"[REDACTED]":pt(n)])):e}function ft(e){return e?pt(e):void 0}var Yn=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",dt=Yn?S.join(Yn,"current-progress.json"):"",Xn=Promise.resolve();function er(e){return e.includes("crawl")?"crawl":e.includes("deploy")?"deploy":e.includes("invalidate")?"invalidate":e}function Vs(e,t){let n={...e},s=new Set(["pagesQueued","pagesRendered","assetsQueued","sitemapsQueued","pagesDiscovered","assetsDiscovered","sitemapsDiscovered","pagesSaved","assetsSaved","donePages","doneAssets","doneSitemaps","changedTextFiles","uploaded","failed","index","totalFiles","pageQueue","assetQueue","sitemapQueue"]);for(let[r,i]of Object.entries(t)){let a=n[r];if(typeof a=="number"&&typeof i=="number"&&s.has(r)){n[r]=Math.max(a,i);continue}n[r]=i;}return n}function tr(e,t,n){dt&&(Xn=Xn.then(async()=>{let s=new Date,r=s.toISOString();await A.mkdir(S.dirname(dt),{recursive:true});let i=await A.readFile(dt,"utf8").then(h=>JSON.parse(h)).catch(()=>null),a=i&&typeof i.details=="object"&&i.details?i.details:{},c=er(e),o=i?.currentStep||er(i?.source||""),u=i?.startedAt||r,l={...i?.stepDurationsSec??{}},d=i?.stepStartedAt||r;if(o&&o!==c&&i?.stepStartedAt){let h=Math.max(0,Math.round((s.getTime()-new Date(i.stepStartedAt).getTime())/1e3));l[o]=(l[o]??0)+h,d=r;}let p=Math.max(0,Math.round((s.getTime()-new Date(d).getTime())/1e3)),g=Math.max(0,Math.round((s.getTime()-new Date(u).getTime())/1e3)),f=Re(t),w=ft(n)??{},m={checkedAt:r,source:e,message:f,details:Vs(a,w),startedAt:u,currentStep:c,stepStartedAt:d,stepElapsedSec:p,totalElapsedSec:g,stepDurationsSec:l};await A.writeFile(dt,JSON.stringify(m,null,2),"utf8");}).catch(()=>{}));}async function nr(e,t){await A.mkdir(S.dirname(e),{recursive:true}),await A.appendFile(e,`${JSON.stringify(pt(t))}
5
+ `,"utf8");}function Ks(e,t){let n=typeof t?.phase=="string"?t.phase.trim():"";return n||(e==="page"?"render-pages":e==="asset"?"download-assets":e==="sitemap"?"discovery":e==="timing"&&typeof t?.name=="string"&&t.name.trim()||"crawl")}function Gs(e,t,n){let s=ft(n);return {checkedAt:new Date().toISOString(),currentStep:Ks(e,s),level:e,message:Re(t),details:s??{}}}var Me=class{constructor(t,n,s="info"){this.logDir=t;this.logFile=n;this.level=s;this.ensureLogFileReady();}logDir;logFile;level;startedAt=Date.now();marks=new Map;initPromise=null;writeQueue=Promise.resolve();writeError=null;get logPath(){return S.join(this.logDir,this.logFile)}artifactPath(t){return this.logFile.endsWith(".log.jsonl")?S.join(this.logDir,this.logFile.replace(/\.log\.jsonl$/u,`${t}.jsonl`)):S.join(this.logDir,`${this.logFile}${t}.jsonl`)}get errorsPath(){return this.artifactPath(".errors")}get rejectedPath(){return this.artifactPath(".rejected")}ensureLogFileReady(){return this.initPromise||(this.initPromise=(async()=>{await A.mkdir(this.logDir,{recursive:true}),await A.writeFile(this.logPath,"","utf8");})()),this.initPromise}enqueueTask(t){this.writeQueue=this.writeQueue.then(t).catch(n=>{this.writeError=n instanceof Error?n:new Error(String(n));});}enqueueLine(t){this.enqueueTask(async()=>{await this.ensureLogFileReady(),await A.appendFile(this.logPath,`${t}
6
+ `,"utf8");});}enqueueJsonLine(t,n){this.enqueueTask(()=>nr(t,n));}accepts(t){return ie[t]<=ie[this.level]}push(t,n,s){if(!this.accepts(t))return;let r=Re(n),i=ft(s),a=JSON.stringify({time:new Date().toISOString(),level:t,message:r,...i||{}});this.enqueueLine(a),t==="error"?console.error(`[ERROR] ${r}`,i?JSON.stringify(i):""):t==="warn"?console.warn(`[WARN] ${r}`,i?JSON.stringify(i):""):console.log(`[${t.toUpperCase().padEnd(5)}] ${r}`);}info(t,n){this.push("info",t,n);}progress(t,n){tr(this.logFile,t,n);}debug(t,n){this.push("debug",t,n);}warn(t,n){this.push("warn",t,n);}reject(t,n,s,r,i){let a={kind:t,url:n,reason:s,...r?{source:r}:{},...i||{}};this.enqueueJsonLine(this.rejectedPath,a),this.accepts("debug")&&this.push("debug",`Rejected ${t} ${n}: ${s}`,a);}error(t,n){this.enqueueJsonLine(this.errorsPath,{message:t,...n||{}}),this.push("error",t,n);}mark(t){this.marks.set(t,Date.now());}endMark(t,n){let s=this.marks.get(t);if(!s)return;let r=Date.now()-s,i=Number((r/1e3).toFixed(2));this.push("info",`Timing ${t}: ${i}s`,{name:t,ms:r,seconds:i,...n||{}});}async flush(){let t=Date.now()-this.startedAt,n=Number((t/1e3).toFixed(2));if(this.push("info",`Total time: ${n}s`,{name:"total",ms:t,seconds:n}),await this.writeQueue,this.writeError)throw this.writeError}},gt=class{constructor(t,n="info"){this.logDir=t;this.level=typeof n=="boolean"?n?"debug":"info":n,this.ensureLogFileReady();}logDir;startedAt=Date.now();marks=new Map;initPromise=null;writeQueue=Promise.resolve();writeError=null;level;get logPath(){return S.join(this.logDir,"crawl.log.jsonl")}get currentEventPath(){return S.join(this.logDir,"current-crawl-event.json")}get rejectedPath(){return S.join(this.logDir,"rejected.jsonl")}get ignoredPath(){return S.join(this.logDir,"ignored.jsonl")}get skippedPath(){return S.join(this.logDir,"skipped-http.jsonl")}get errorsPath(){return S.join(this.logDir,"errors.jsonl")}get timingsPath(){return S.join(this.logDir,"timings.jsonl")}ensureLogFileReady(){return this.initPromise||(this.initPromise=(async()=>{await A.mkdir(this.logDir,{recursive:true}),await A.writeFile(this.logPath,"","utf8");})()),this.initPromise}enqueueTask(t){this.writeQueue=this.writeQueue.then(t).catch(n=>{this.writeError=n instanceof Error?n:new Error(String(n));});}enqueueLine(t){this.enqueueTask(async()=>{await this.ensureLogFileReady(),await A.appendFile(this.logPath,`${t}
7
+ `,"utf8");});}enqueueJsonLine(t,n){this.enqueueTask(()=>nr(t,n));}updateCurrentEvent(t,n,s){let r=Gs(t,n,s);this.enqueueTask(async()=>{await A.mkdir(this.logDir,{recursive:true}),await A.writeFile(this.currentEventPath,JSON.stringify(r,null,2),"utf8");});}push(t,n,s){let r=Re(n),i=ft(s),a=JSON.stringify({time:new Date().toISOString(),level:t,message:r,...i||{}});this.enqueueLine(a),this.updateCurrentEvent(t,r,i),t==="error"?console.error(r,i||""):t==="warn"?console.warn(r,i||""):(ie[this.level]>=ie.debug||["summary","page","sitemap","asset","timing"].includes(t))&&console.log(r);}info(t,n){this.push("info",t,n);}debug(t,n){ie[this.level]<ie.debug||this.push("debug",t,n);}progress(t,n){tr("crawl.log.jsonl",t,n),this.updateCurrentEvent("progress",t,n);}checkpoint(t,n){this.updateCurrentEvent("checkpoint",t,n);}page(t,n){this.push("page",t,n);}sitemap(t,n){this.push("sitemap",t,n);}asset(t,n){this.push("asset",t,n);}warn(t,n){this.push("warn",t,n);}error(t,n){this.enqueueJsonLine(this.errorsPath,{message:t,...n||{}}),this.push("error",t,n);}summary(t,n){this.push("summary",t,n);}mark(t){this.marks.set(t,Date.now());}endMark(t,n){let s=this.marks.get(t);if(!s)return;let r=Date.now()-s,i={name:t,ms:r,seconds:Number((r/1e3).toFixed(2)),...n||{}};this.enqueueJsonLine(this.timingsPath,i),this.push("timing",`Timing ${t}: ${i.seconds}s`,i);}reject(t,n,s,r){let i={kind:t,url:n,reason:s,source:r};this.enqueueJsonLine(this.rejectedPath,i),ie[this.level]>=ie.debug&&this.push("reject",`Rejected ${t} ${n}: ${s}`,i);}ignore(t,n,s,r){let i={kind:t,url:n,reason:s,source:r};this.enqueueJsonLine(this.ignoredPath,i),ie[this.level]>=ie.debug&&this.push("ignore",`Ignored ${t} ${n}: ${s}`,i);}skip(t,n,s,r){let i={kind:t,url:n,status:s,source:r};this.enqueueJsonLine(this.skippedPath,i),this.push("warn",`Skipped ${t} ${n}: HTTP ${s}`,i);}async flush(){let t=Date.now()-this.startedAt,n={name:"total",ms:t,seconds:Number((t/1e3).toFixed(2))};if(this.enqueueJsonLine(this.timingsPath,n),await this.writeQueue,this.writeError)throw this.writeError}};var Kt="(?:css|js|mjs|json|map|xml|xsl|rss|atom|txt|enc|jws|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|pdf|mp4|webm)";function rr(e){return !!e&&/^(?:\.{1,2}\/)?[A-Za-z0-9@_][A-Za-z0-9@._/-]*\.(?:js|mjs)(?:[?#][^\s<>\\]*)?$/i.test(e)&&!e.startsWith("/")&&!e.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(e)&&!/(?:^|\/)node_modules(?:\/|$)|(?:^|\/)\.pnpm(?:\/|$)/i.test(e)}function sr(e){let t=new Set,n=[],s=/\bimport\s*\(\s*["'`]([^"'`\s<>\\]+)["'`]\s*\)/g,r=/\b(?:[A-Za-z_$][\w$]*\.)?u\s*=\s*(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>\s*["'`]([^"'`\s<>\\]+)["'`]/g;for(let i of e.matchAll(s))i[1]&&rr(i[1])&&n.push({index:i.index??0,value:i[1]});for(let i of e.matchAll(r))i[1]&&rr(i[1])&&n.push({index:i.index??0,value:i[1]});for(let i of n.sort((a,c)=>a.index-c.index))t.add(i.value);return [...t]}function ir(e,t){return typeof e=="string"&&e.length>0&&t?.supported===true&&typeof t.token=="string"&&t.token.length>0&&e===t.token}function or(e,t){try{let n=new URL(e),s=new URL(t,n);if(s.origin!==n.origin)return !1;let r=n.pathname.replace(/\/+$/,"");if(r&&s.pathname!==r&&!s.pathname.startsWith(`${r}/`))return !1;let i=r?s.pathname.slice(r.length)||"/":s.pathname;return ["/wp-includes/","/wp-content/plugins/","/wp-content/themes/","/wp-content/mu-plugins/"].some(a=>i.startsWith(a))}catch{return false}}var ei=["text/css","javascript","image/","font/","application/font","application/json","application/xml","text/xml","application/rss+xml","application/atom+xml","application/xslt+xml","text/xsl","image/svg+xml"],Sr=new Set([".css",".js",".mjs",".json",".map",".xml",".xsl",".rss",".atom",".txt",".enc",".jws",".png",".jpg",".jpeg",".gif",".webp",".avif",".svg",".ico",".woff",".woff2",".ttf",".otf",".eot",".pdf",".mp4",".webm"]),Pr=new Set(["",".html",".htm"]),ti=new Set([".css",".xml",".xsl",".svg",".json",".html",".htm",".txt",".enc",".jws"]),ni=["/wp-content/","/wp-includes/","/wp-admin/","/static/","/assets/","/build/","/_next/"];function ri(e){let t=[],n="full",s="full",r=false,i=false,a="";for(let c=0;c<e.length;c++){let o=e[c];if(o==="--retry-timeouts")n="retry-timeouts",r=true;else if(o==="--resume")r=true;else if(o==="--resume-rewrite")r=true,i=true;else if(o==="--crawl-mode"){let u=e[++c];if(!u)throw new Error("--crawl-mode requires a value");s=u==="incremental"?"incremental":"full",r||=s==="incremental";}else if(o.startsWith("--crawl-mode="))s=o.slice(13)==="incremental"?"incremental":"full",r||=s==="incremental";else if(o==="--incremental")s="incremental",r=true;else if(o==="--url"){let u=e[++c];if(!u)throw new Error("--url requires a value");n="single-url",r=true,t.push(u);}else if(o.startsWith("--url="))n="single-url",r=true,t.push(o.slice(6));else if(o==="--urls"){let u=e[++c];if(!u)throw new Error("--urls requires a file path");n="single-url",r=true,t.push(`@${u}`);}else if(o==="--content-sync-plan"){let u=e[++c];if(!u)throw new Error("--content-sync-plan requires a file path");n="content-sync",s="incremental",r=true,a=S.resolve(u);}else o.startsWith("--content-sync-plan=")&&(n="content-sync",s="incremental",r=true,a=S.resolve(o.slice(20)));}return {mode:n,crawlMode:s,urls:t,preserveOutput:r,resumeRewrite:i,contentSyncPlanPath:a}}function nn(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function si(){let e=nn();return e?S.resolve(e,".."):""}function ii(){let e=process.env.STATIC_PUBLISHER_WP_ROOT||process.env.WPSUITE_STATIC_PUBLISHER_WP_ROOT||"";return e.trim()?S.resolve(e):""}function oi(e){let t=e.trim(),n=[{alias:"@storage-root",root:si(),requiredEnv:"STATIC_PUBLISHER_RUNTIME_DIR or WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR"},{alias:"@runtime",root:nn(),requiredEnv:"STATIC_PUBLISHER_RUNTIME_DIR or WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR"},{alias:"@wp-root",root:ii(),requiredEnv:"STATIC_PUBLISHER_WP_ROOT or WPSUITE_STATIC_PUBLISHER_WP_ROOT"}];for(let s of n){if(t!==s.alias&&!t.startsWith(`${s.alias}/`))continue;if(!s.root)return {resolvedPath:null,alias:s.alias,requiredEnv:s.requiredEnv};let r=t.slice(s.alias.length).replace(/^\/+/,"");return {resolvedPath:r?S.resolve(s.root,r):s.root,alias:s.alias}}return {resolvedPath:S.resolve(t)}}function br(e){let t=String(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH||"").trim();if(t)return S.resolve(t);let n=nn();return n?S.join(n,"crawl-manifest.json"):S.join(e.outputDir,".crawl-manifest.json")}function vr(){return {schemaVersion:4,updatedAt:"",pages:{},assets:{}}}function ar(e){return {url:String(e.url||""),outputPath:String(e.outputPath||""),contentType:typeof e.contentType=="string"&&e.contentType?e.contentType:null,changeToken:typeof e.changeToken=="string"?e.changeToken:null,tokenSource:typeof e.tokenSource=="string"?e.tokenSource:null,sitemapLastmod:typeof e.sitemapLastmod=="string"?e.sitemapLastmod:null,discoveredPages:Array.isArray(e.discoveredPages)?e.discoveredPages.map(t=>String(t)):[],discoveredAssets:Array.isArray(e.discoveredAssets)?e.discoveredAssets.map(t=>String(t)):[],lastCrawledAt:String(e.lastCrawledAt||""),lastSeenRunId:String(e.lastSeenRunId||""),rewriteComplete:e.rewriteComplete===true}}function ai(e){let t=e.isText===true;return {url:String(e.url||""),outputPath:String(e.outputPath||""),isText:t,contentType:typeof e.contentType=="string"&&e.contentType?e.contentType:null,changeToken:typeof e.changeToken=="string"?e.changeToken:null,tokenSource:typeof e.tokenSource=="string"?e.tokenSource:null,discoveredAssets:Array.isArray(e.discoveredAssets)?e.discoveredAssets.map(n=>String(n)):[],lastCrawledAt:String(e.lastCrawledAt||""),lastSeenRunId:String(e.lastSeenRunId||""),rewriteComplete:e.rewriteComplete===true||!t}}function Zt(e){let t=e?.["content-type"]?.trim();return t||null}function ci(){return {rewriteTargets:new Set,changedFiles:new Set,deletedFiles:new Set}}function Y(e,t,n){let s=we(t.outputDir,n);s&&(e.changedFiles.add(s),e.deletedFiles.delete(s));}function cr(e,t,n){let s=we(t.outputDir,n);s&&(e.deletedFiles.add(s),e.changedFiles.delete(s));}function Ie(e,t){e.rewriteTargets.add(S.resolve(t));}async function ui(e){try{let t=await A.readFile(br(e),"utf8"),n=JSON.parse(t);if(n&&typeof n=="object"&&n.pages&&typeof n.pages=="object"){if((n.schemaVersion===2||n.schemaVersion===3||n.schemaVersion===4)&&n.assets&&typeof n.assets=="object")return {schemaVersion:4,updatedAt:String(n.updatedAt||""),pages:Object.fromEntries(Object.entries(n.pages).map(([s,r])=>[s,ar(r)])),assets:Object.fromEntries(Object.entries(n.assets).map(([s,r])=>[s,ai(r)]))};if(n.schemaVersion===1)return {schemaVersion:4,updatedAt:String(n.updatedAt||""),pages:Object.fromEntries(Object.entries(n.pages).map(([s,r])=>[s,ar(r)])),assets:{}}}}catch{}return vr()}function Yt(e){return JSON.parse(JSON.stringify(e))}async function li(e,t){let n=br(e);await A.mkdir(S.dirname(n),{recursive:true}),await A.writeFile(n,JSON.stringify(t,null,2),"utf8");}async function Se(e,t){if(!t.trackManifest)return;let n=async()=>{let s=Yt(t.manifest);s.updatedAt=new Date().toISOString(),t.manifest.updatedAt=s.updatedAt,await li(e,s);};t.manifestSaveChain=t.manifestSaveChain.then(n,n),await t.manifestSaveChain;}function Ke(e){if(!e)return null;let t=e.trim();return t||null}function di(e,t){let n=new Set,s=new Set([...Object.keys(e),...Object.keys(t)]);for(let r of s){let i=e[r],a=t[r];!i||!a||i===a||n.add(r);}return n}async function Cr(e,t,n,s){let r=[...new Set(n.map(c=>c.trim()).filter(Boolean))],i=String(e.wpsuite?.runtimeToken||"").trim();if(r.length===0||!i)return new Map;let a=new URL("/wp-json/smartcloud-static-publisher/v1/change-tokens",e.sourceOrigin).toString();try{let c=await t.post(a,{timeout:3e4,failOnStatusCode:!1,headers:{"content-type":"application/json","x-static-publisher-token":i},data:JSON.stringify({urls:r})});if(!c.ok())return s.warn(`Change token lookup failed with HTTP ${c.status()}`,{endpoint:a,status:c.status()}),new Map;let o=await c.json().catch(()=>null);if(!o||!Array.isArray(o.items))return new Map;let u=new Map;for(let l of o.items)!l||typeof l.url!="string"||u.set(l.url,l);return u}catch(c){return s.warn("Change token lookup failed; falling back to sitemap metadata",{endpoint:a,error:c instanceof Error?`${c.name}: ${c.message.split(/\r?\n/u,1)[0]}`:"Unknown change-token request failure"}),new Map}}async function wt(e,t,n,s,r){if(!n.enabled&&!n.trackManifest)return null;if(n.changeTokenCache.has(s))return n.changeTokenCache.get(s)??null;let a=(await Cr(e,t,[s],r)).get(s)??null;return on(e,s)&&(!a||a.supported!==true||!a.token)&&(a=await fi(e,t,s,r)),a=Rr(e,a),n.changeTokenCache.set(s,a),a}async function pi(e,t,n,s,r){if(!n.trackManifest)return;let i=[...new Set(s.map(a=>a.trim()).filter(Boolean))].filter(a=>!n.changeTokenCache.has(a));for(let a=0;a<i.length;a+=250){let c=i.slice(a,a+250),o=await Cr(e,t,c,r);for(let u of c)n.changeTokenCache.set(u,Rr(e,o.get(u)??null));}}function gi(e){return `subscriber=${e.wpsuite?.siteSettings?.subscriber===true?"1":"0"}`}function Rr(e,t){if(!t?.supported||!t.token||t.tokenSource==="wp-media-file")return t;let n=gi(e);return {...t,token:Je(`${t.token}
8
+ ${n}`,40),tokenSource:t.tokenSource?`${t.tokenSource}+site-subscriber`:"site-subscriber"}}async function fi(e,t,n,s){try{let r=await t.get(n,{timeout:Math.min(e.navigationTimeoutMs,15e3),failOnStatusCode:!1});if(r.status()!==404)return s.warn(`Generated 404 fallback token skipped for ${n}`,{url:n,status:r.status(),requestPath:e.generated404RequestPath,source:"generated-404-change-token-fallback"}),null;let i=await r.text().catch(()=>""),a=Je(`${n}
9
+ 404
10
+ ${i}`,40);return s.info(`Using generated 404 fallback change token for ${n}`,{url:n,requestPath:e.generated404RequestPath,source:"generated-404-change-token-fallback"}),{url:n,supported:!0,token:a,tokenSource:"generated-404-response-hash",postId:null,dependencyPostIds:[],reason:null}}catch(r){return s.warn(`Generated 404 fallback token lookup failed for ${n}`,{url:n,error:String(r),requestPath:e.generated404RequestPath,source:"generated-404-change-token-fallback"}),null}}async function mi(e,t,n,s,r,i){let a=on(e,r);if(!s.enabled)return {action:"render",changeToken:s.trackManifest?await wt(e,t,s,r,i):null};let c=s.manifest.pages[r];if(!c)return {action:"render",changeToken:await wt(e,t,s,r,i)};let o=await wt(e,t,s,r,i);if(o?.supported&&o.token)return c.changeToken===o.token?a&&!await hi(e,t,r,i)?{action:"render",changeToken:o}:{action:"reuse",changeToken:o}:{action:"render",changeToken:o};let u=Ke(n.sitemapLastmodByPage[r]);return u&&c.sitemapLastmod&&c.sitemapLastmod===u?{action:"reuse",changeToken:o}:{action:"render",changeToken:o}}async function hi(e,t,n,s){try{let i=(await t.get(n,{timeout:Math.min(e.navigationTimeoutMs,15e3),failOnStatusCode:!1})).status();return i===404?!0:(s.warn(`Generated 404 request path no longer returns 404 for ${n}`,{url:n,status:i,requestPath:e.generated404RequestPath,source:"generated-404-status-probe"}),!1)}catch(r){return s.warn(`Generated 404 status probe failed for ${n}`,{url:n,error:String(r),requestPath:e.generated404RequestPath,source:"generated-404-status-probe"}),false}}async function wi(e,t,n,s,r){let i=ur(n.previousManifest,void 0,s,"previous-manifest"),a=0;for(let[p,g]of Object.entries(n.manifest.pages))if(!n.seenPages.has(p)){cr(r,e,g.outputPath);try{await A.unlink(g.outputPath);}catch(f){(f.code||"")!=="ENOENT"&&s.warn(`Failed to remove stale incremental page output for ${p}`,{url:p,outputPath:g.outputPath,error:String(f)});}delete n.manifest.pages[p],a++;}let c=ur(n.manifest,n.runId,s,"active-manifest"),o=new Set,u=new Set;for(let p of c){for(let w of Ge(e,p))o.add(w);let g=n.manifest.assets[p]?.outputPath;g&&u.add(g);let f=Oe(e,t.assetMap,p);f&&u.add(f);}for(let p of Object.keys(n.manifest.assets))c.has(p)||delete n.manifest.assets[p];let l=0,d=0;for(let p of i){let g=new Set,f=n.previousManifest.assets[p]?.outputPath;f&&g.add(f);let w=Oe(e,t.assetMap,p);if(!c.has(p)&&w)g.add(w);else if(!c.has(p)){let m=Di(e,p,s,"incremental-cleanup");m&&(g.add(m.originalFilePath),m.hashedFilePath&&g.add(m.hashedFilePath));}for(let m of g)if(!u.has(m)){cr(r,e,m);try{await A.unlink(m),l++;}catch(h){(h.code||"")!=="ENOENT"&&s.warn(`Failed to remove stale incremental asset output for ${p}`,{url:p,outputPath:m,error:String(h)});}}for(let m of Ge(e,p))o.has(m)||Object.prototype.hasOwnProperty.call(t.assetMap,m)&&(delete t.assetMap[m],d++);}(a>0||l>0||d>0)&&s.info(`Incremental cleanup removed ${a} stale pages, ${l} stale assets, ${d} stale asset mappings`,{removedPages:a,removedAssets:l,removedAssetMappings:d,phase:"incremental-cleanup"});}function ur(e,t,n,s){let r=new Set,i=a=>{let c=a.trim();if(c){if(n){let o=Pe(c,n,"asset",s??"manifest");if(!o)return;r.add(o.toString());return}r.add(c);}};for(let a of Object.values(e.pages))for(let c of a.discoveredAssets||[])i(c);for(let[a,c]of Object.entries(e.assets||{}))t&&c.lastSeenRunId!==t||i(a);return r}function lr(e,t,n){for(let s of t)for(let r of Ge(e,s))if(n.has(r))return true;return false}function yi(e,t,n,s,r){let i=new Set(n.rewriteTargets);for(let c of Object.values(t.manifest.pages))c.rewriteComplete||i.add(S.resolve(c.outputPath));for(let c of Object.values(t.manifest.assets))c.isText&&!c.rewriteComplete&&i.add(S.resolve(c.outputPath));let a=di(s,r);if(a.size===0)return [...i];for(let c of Object.values(t.manifest.pages))lr(e,c.discoveredAssets,a)&&i.add(S.resolve(c.outputPath));for(let[c,o]of Object.entries(t.manifest.assets)){o.isText&&lr(e,o.discoveredAssets,a)&&i.add(S.resolve(o.outputPath));for(let u of Ge(e,c))if(a.has(u)){Y(n,e,o.outputPath),o.isText&&i.add(S.resolve(o.outputPath));break}}return [...i]}function Si(e,t){let n=t?new Set(Array.from(t,r=>S.resolve(r))):null,s=r=>n===null||n.has(S.resolve(r));for(let r of Object.values(e.manifest.pages))s(r.outputPath)&&(r.rewriteComplete=true);for(let r of Object.values(e.manifest.assets)){if(!r.isText){r.rewriteComplete=true;continue}s(r.outputPath)&&(r.rewriteComplete=true);}}function Pi(e,t,n){let s=new Set,r=i=>{if(!i)return;let a=we(e.outputDir,i);a&&s.add(a);};for(let i of t.donePages)r(le(e,i));for(let i of Object.values(n.manifest.pages))i.lastSeenRunId===n.runId&&r(i.outputPath);for(let i of t.doneAssets)r(Oe(e,t.assetMap,i));for(let i of Object.values(n.manifest.assets))i.lastSeenRunId===n.runId&&r(i.outputPath);return s}async function bi(e,t,n,s,r){let i=[...s.deletedFiles].sort(),a=Pi(e,t,n),c=0;for(let l of [...a].sort()){try{if((await A.stat(S.join(e.outputDir,l))).isFile())continue}catch{}c++,r.warn(`Active output is missing after crawl: ${l}`,{phase:"deploy-plan",file:l,outputPath:S.join(e.outputDir,l)});}if(c>0&&r.warn(`Detected ${c} active output file(s) missing before deploy plan save.`,{phase:"deploy-plan",missingActiveOutputs:c}),i.length===0)return [];let o=[],u=0;for(let l of i){if(!a.has(l)){o.push(l);continue}u++;let d=S.join(e.outputDir,l),p;try{p=(await A.stat(d)).isFile();}catch{p=false;}r.warn(`Deploy plan protected active output from deletion: ${l}`,{phase:"deploy-plan",file:l,outputPath:d,exists:p});}return u>0&&r.info(`Deploy plan skipped ${u} active output deletion(s).`,{phase:"deploy-plan",protectedDeletes:u,deletedFiles:o.length}),o}function Ge(e,t){let n=new Set([t]);try{let s=new URL(t),i=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{i.push(new URL(e.targetOrigin).origin);}catch{}for(let a of i)try{n.add(new URL(a).origin+s.pathname+s.search);}catch{}n.add(s.pathname+s.search),n.add(s.pathname);}catch{}return [...n]}function vi(e,t){let n=new Set([t]);try{let s=new URL(t),i=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{i.push(new URL(e.targetOrigin).origin);}catch{}for(let a of i)try{n.add(new URL(a).origin+s.pathname+s.search);}catch{}n.add(s.pathname+s.search);}catch{}return [...n]}function Ir(e,t){let n=e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/"?e.targetOrigin:"https://relative.invalid/";try{let s=new URL(t,n);return S.join(e.outputDir,sn(s.pathname))}catch{return null}}function Ci(e,t,n){for(let s of vi(e,n)){let r=t[s];if(!r)continue;let i=Ir(e,r);if(i)return {outputPath:i,publicUrl:r}}return null}function Ri(e,t,n){for(let s of Ge(e,n)){let r=t[s];if(!r)continue;let i=Ir(e,r);if(i)return i}return null}function Oe(e,t,n){let s=Ri(e,t,n);if(s)return s;try{return bt(e,n).originalFilePath}catch{return null}}function Ii(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.join(S.resolve(e),"queue-runner-heartbeat.json"):""}async function dr(e){let t=Ii();if(t)try{let n=await A.readFile(t,"utf8"),s=JSON.parse(n);if(!s||typeof s!="object")return;await A.writeFile(t,JSON.stringify({...s,checkedAt:new Date().toISOString(),status:"running",currentStep:"rewrite",message:e},null,2),"utf8");}catch{}}function xi(e,t){let n=new Set;for(let s of t.donePages)n.add(S.resolve(le(e,s)));for(let s of t.doneAssets){let r=Oe(e,t.assetMap,s);!r||!ye(r)||n.add(S.resolve(r));}for(let s of t.doneSitemaps){let r=Oe(e,t.assetMap,s);!r||!ye(r)||n.add(S.resolve(r));}return [...n]}var St="re:",mt=new Map;function Ai(e){if(!e.startsWith(St))return null;let t=mt.get(e);if(t!==void 0)return t||null;let n=e.slice(St.length).trim();if(!n)return mt.set(e,false),null;try{let s=new RegExp(n);return mt.set(e,s),s}catch{return console.warn(`[crawl] Ignoring invalid path matcher regex: ${e}`),mt.set(e,false),null}}function rn(e,t){let n=Ai(t);return n?n.test(e):t.startsWith(St)?false:e.startsWith(t)}function Ti(e,t){return t.find(n=>rn(e,n))}function xr(e,t){let n=Ti(t.pathname,e.blockedPathPrefixes);if(n)return n.startsWith(St)?`blocked path regex: ${n}`:`blocked path prefix: ${n}`;let s=e.blockedSearchFragments.find(r=>t.search.includes(r));return s?`blocked search fragment: ${s}`:null}function ki(e){let t=new URL(e.sourceOrigin),n=new Set([t.hostname,...e.allowedAssetHosts]);if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{n.add(new URL(e.targetOrigin).hostname);}catch{}for(let s of Object.keys(e.extraReplacements||{}))try{n.add(new URL(s).hostname);}catch{}return n}function $i(e,t){return ki(e).has(t.hostname)}function Ei(e){let t=ce(e.trim()).replace(/\\\//g,"/").replace(/^['"]|['"]$/g,"").trim();return t=t.replace(/[)]+$/g,"").trim(),t=t.replace(/;.*$/g,"").trim(),t}function Xt(e){let t=ce(e).replace(/\\\//g,"/");return /[{}]|\bwindow\.|\blocation\.|\bincludes\(|\?\?null|\+|%7B|%7D|%22|<|>|\s/.test(t)||/[()[\]'"]/.test(t)}function Mi(e){let t=ce(e).replace(/\\\//g,"/").trim(),n=S.extname(t).toLowerCase();return Sr.has(n)||Pr.has(n)?false:/^(?:this|[A-Za-z_$][\w$]*)\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(t)}function je(e){return ni.some(t=>e.pathname.startsWith(t))}function W(e,t,n=e.sourceOrigin,s,r="url"){let i=Ei(t);if(!i||i.startsWith("data:")||i.startsWith("blob:")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("#"))return s?.ignore(r,t,"empty or unsupported scheme",n),null;if(Xt(i))return s?.ignore(r,t,"looks like JavaScript/code fragment",n),null;if(Mi(i))return s?.ignore(r,t,"looks like JavaScript property access",n),null;try{let a=new URL(i,n);if(Ar(a))return s?.reject(r,t,"malformed URL encoding",n),null;if(!["http:","https:"].includes(a.protocol))return s?.ignore(r,t,"unsupported protocol: ",n),null;if(!$i(e,a))return s?.ignore(r,a.toString(),"host not allowed",n),null;let c=xr(e,a);if(c)return s?.reject(r,a.toString(),c,n),null;let o=new URL(e.sourceOrigin);return a.protocol=o.protocol,a.host=o.host,a.hash="",a}catch{return s?.reject(r,t,"invalid URL",n),null}}function Ar(e){try{return decodeURIComponent(e.pathname),decodeURIComponent(e.search),decodeURIComponent(e.hash),!1}catch{return true}}function Pe(e,t,n,s){try{let r=new URL(e);return Ar(r)?(t.reject(n,e,"malformed URL encoding",s),null):r.protocol!=="http:"&&r.protocol!=="https:"?(t.reject(n,e,`unsupported protocol: ${r.protocol}`,s),null):r}catch{return t.reject(n,e,"invalid URL",s),null}}function Tr(e){return Sr.has(S.extname(e.pathname).toLowerCase())}function be(e){return je(e)?false:Pr.has(S.extname(e.pathname).toLowerCase())}function Ue(e){let t=e.pathname.toLowerCase();return t.endsWith(".xml")&&(t.includes("sitemap")||t.endsWith("/sitemap.xml"))}function L(e,t){return !!(Ue(t)||t.pathname==="/robots.txt"||t.pathname==="/llms.txt"||t.pathname.toLowerCase().endsWith(".xsl")||e.assetPathPrefixes.length>0&&e.assetPathPrefixes.some(n=>rn(t.pathname,n))||Tr(t)||!be(t)&&!je(t))}function le(e,t){let n=new URL(t),s=sn(n.pathname);return s.endsWith("/")?s+="index.html":S.extname(s)||(s+="/index.html"),S.join(e.outputDir,s)}function sn(e){try{return decodeURIComponent(e)}catch{return e}}function Fi(e){if(!e.generated404RequestPath)return null;try{let t=new URL(e.generated404RequestPath,e.sourceOrigin);return !t.pathname.endsWith("/")&&S.extname(t.pathname)===""&&(t.pathname+="/"),t.hash="",t.toString()}catch{return null}}function on(e,t){let n=Fi(e);if(!n)return false;try{return new URL(t,e.sourceOrigin).toString()===n}catch{return false}}function bt(e,t){let n=new URL(t),s=sn(n.pathname);s.endsWith("/")&&(s+="index.html");let r=!!n.search,i=s,a=S.join(e.outputDir,i),c=zt(e.targetOrigin,i),o=`${c}${n.search}`;if(!r)return {originalPathname:i,originalFilePath:a,originalPublicUrl:c,originalPublicUrlWithSearch:o,preferQueryHashed:r};let u=S.extname(s),d=`${u?s.slice(0,-u.length):s}.${Je(n.search)}${u||".bin"}`;return {originalPathname:i,originalFilePath:a,originalPublicUrl:c,originalPublicUrlWithSearch:o,preferQueryHashed:r,hashedPathname:d,hashedFilePath:S.join(e.outputDir,d),hashedPublicUrl:zt(e.targetOrigin,d)}}function Di(e,t,n,s){let r=Pe(t,n,"asset",s);return r?bt(e,r.toString()):null}function Oi(e,t,n,s,r){t[n]=s;try{let i=new URL(n),c=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{c.push(new URL(e.targetOrigin).origin);}catch{}for(let o of c)try{let u=new URL(o);t[u.origin+i.pathname+i.search]=s;}catch{}try{let o=(()=>{let u=new URL(s,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin);return `${u.pathname}${u.search}`})();t[i.pathname+i.search]=o;}catch{}try{let o=new URL(s,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin).pathname;t[i.pathname]=o;}catch{}try{let o=new URL(r,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin).pathname;t[i.pathname]=o;}catch{}}catch{}}async function kr(e){try{return await A.readFile(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function De(e){try{return await A.stat(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function ji(e){let t=String(e["content-length"]||"").trim();if(!t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)&&n>=0?n:null}function $r(e){let t=String(e["last-modified"]||"").trim();if(!t)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}function Ui(e,t){let n=$r(t),s=ji(t),r=e?.mtime.getTime();return n!==null&&Math.abs((r??0)-n)>=1e3||s!==null&&e?.size!==s?false:n!==null||s!==null}async function Li(e,t){if(!t)return;let n=$r(t);if(n===null)return;let s=await De(e);if(!s)return;let r=new Date(n);await A.utimes(e,s.atime,r).catch(()=>{});}function pr(e,t){let n=S.extname(e.pathname).toLowerCase(),s=t["content-type"]||"";return ti.has(n)||ei.some(r=>s.includes(r))&&!s.startsWith("image/")&&!s.includes("font")}function qi(e){try{let t=S.extname(new URL(e).pathname).toLowerCase();return t===".js"||t===".mjs"}catch{return false}}function Fe(e,t){(e.doneAssets.size%25===0||e.doneAssets.size===1||e.doneAssets.size===e.stats.assetsQueued)&&t.progress(`Asset processing progress: processed ${e.doneAssets.size}, discovered ${e.stats.assetsQueued}.`,{doneAssets:e.doneAssets.size,assetsQueued:e.stats.assetsQueued,phase:"download-assets"});}function _i(e){return Je(e.toString("base64"),40)}function Ni(e,t,n){let s=e.assetVariantDigestsByOriginalPath.get(t);if(!s||s.size===0)return false;for(let r of s)if(r!==n)return true;return false}function Bi(e,t,n){let s=e.assetVariantDigestsByOriginalPath.get(t);s||(s=new Set,e.assetVariantDigestsByOriginalPath.set(t,s)),s.add(n);}async function en(e,t,n,s,r,i,a){let c=bt(e,n),o=_i(s),u=c.originalFilePath,l=c.originalPublicUrlWithSearch;if(c.preferQueryHashed&&c.hashedFilePath&&c.hashedPublicUrl&&Ni(r,c.originalFilePath,o)){let f=Ci(e,t,n);f?(u=f.outputPath,l=f.publicUrl):(u=c.hashedFilePath,l=c.hashedPublicUrl);}Oi(e,t,n,l,c.originalPublicUrl);let d=ye(u)?Buffer.from(Vt(s.toString("utf8"),e,t,u),"utf8"):s,p=await kr(u),g=false;return (p===null||!p.equals(d))&&(await Ve(u,d),g=true),i?.debug(`${g?"Saved":"Skipped unchanged"} asset output ${n}`,{phase:"download-assets",url:n,outputPath:u,bytes:d.length,wroteFile:g}),Bi(r,c.originalFilePath,o),await Li(u,a),r.stats.assetsSaved++,i&&(r.stats.assetsSaved%50===0||r.stats.assetsSaved===1)&&i.progress(`Asset progress: saved ${r.stats.assetsSaved}, discovered ${r.stats.assetsQueued}, pending ${r.assetQueue.length}.`,{assetsSaved:r.stats.assetsSaved,assetsQueued:r.stats.assetsQueued,assetQueue:r.assetQueue.length,phase:"download-assets"}),{outputPath:u,publicUrl:l,wroteFile:g}}function Ze(e,t,n,s,r){let i=()=>{let d=String(r??"").trim();if(!d)return {discoveredFrom:"",discoveredFromType:"unknown"};if(d==="seed-path"||d==="cli"||d==="generated-404-request-path")return {discoveredFrom:d,discoveredFromType:d};if(/^https?:\/\//i.test(d))try{let p=new URL(d);return Ue(p)?{discoveredFrom:d,discoveredFromType:"sitemap"}:L(e,p)?{discoveredFrom:d,discoveredFromType:"asset"}:be(p)&&!je(p)?{discoveredFrom:d,discoveredFromType:"page"}:{discoveredFrom:d,discoveredFromType:"url"}}catch{return {discoveredFrom:d,discoveredFromType:"url"}}return {discoveredFrom:d,discoveredFromType:"url"}},a=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,c=W(e,n,a,s,"page");if(!c)return;if(!be(c)||Tr(c)){if(L(e,c)){s.info(`Seeded/non-page URL queued as asset: ${c.toString()}`,{url:c.toString(),source:r}),H(e,t,c.toString(),s,r);return}s.reject("page",c.toString(),je(c)?"asset/internal path cannot be page":"not page-like",r);return}let o=c.toString(),{discoveredFrom:u,discoveredFromType:l}=i();u&&!t.pageDiscoverySources.has(o)&&t.pageDiscoverySources.set(o,u),!t.donePages.has(o)&&!t.queuedPages.has(o)&&(t.queuedPages.add(o),t.pageQueue.push(o),t.stats.pagesQueued++,s.debug(`Queued discovered page ${o}`,{phase:"discovery",url:o,discoveredFrom:u,discoveredFromType:l,outputPath:le(e,o)}),(t.stats.pagesQueued%25===0||t.stats.pagesQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,pageQueue:t.pageQueue.length,phase:"discovery"}));}function H(e,t,n,s,r){let i=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,a=W(e,n,i,s,"asset");if(!a)return;if(!L(e,a)){s.reject("asset",a.toString(),"not a safe asset path/prefix",r);return}let c=a.toString();!t.doneAssets.has(c)&&!t.queuedAssets.has(c)&&(t.queuedAssets.add(c),t.assetQueue.push(c),t.stats.assetsQueued++,(t.stats.assetsQueued%100===0||t.stats.assetsQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,assetQueue:t.assetQueue.length,phase:"discovery"}));}function Pt(e,t,n,s,r){let i=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,a=W(e,n,i,s,"sitemap");if(!a)return;if(!Ue(a)){s.reject("sitemap",a.toString(),"not sitemap-like",r);return}let c=a.toString();!t.doneSitemaps.has(c)&&!t.queuedSitemaps.has(c)&&(t.queuedSitemaps.add(c),t.sitemapQueue.push(c),t.stats.sitemapsQueued++,(t.stats.sitemapsQueued%10===0||t.stats.sitemapsQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,sitemapQueue:t.sitemapQueue.length,phase:"discovery"}));}function Wi(e){let t=ce(e),n=[...t.matchAll(/<url>\s*([\s\S]*?)\s*<\/url>/gi)].map(s=>s[1]);return n.length>0?n.map(s=>{let r=s.match(/<loc>\s*([^<]+?)\s*<\/loc>/i);if(!r?.[1])return null;let i=s.match(/<lastmod>\s*([^<]+?)\s*<\/lastmod>/i);return {loc:r[1].trim(),lastmod:Ke(i?.[1]??null)}}).filter(s=>!!s):[...t.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/gi)].map(s=>({loc:s[1].trim(),lastmod:null})).filter(s=>s.loc)}function Hi(e){return e.split(",").map(t=>t.trim().split(/\s+/)[0]).filter(Boolean)}function zi(e){let t=[],n=/url\(\s*(?:"([^"]+)"|'([^']+)'|([^)]*?))\s*\)/gi;for(let s of e.matchAll(n)){let r=e.slice(Math.max(0,s.index-8),s.index);if(/\bnew\s+$/i.test(r))continue;let i=(s[1]||s[2]||s[3]||"").trim();i&&t.push(i);}return t}function Qi(e){return e.replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi,"")}function Ji(e,t){if(t==="dom-style")return true;let n=(()=>{try{return S.extname(new URL(e).pathname).toLowerCase()}catch{return ""}})();return !(n===".js"||n===".mjs"||n===".map"||t.includes("javascript"))}function Gt(e){return e.trim().replace(/\\/g,"/").replace(/^https?:\/\/[^/]+/i,"").replace(/^\/+/,"")}async function Er(e,t,n,s){let r=[];await A.mkdir(t,{recursive:true});let i=await A.readdir(e,{withFileTypes:true});for(let a of i){let c=S.join(e,a.name),o=S.join(t,a.name);if(a.isDirectory()){r.push(...await Er(c,o,n,s));continue}await Mr(c,o,n,s)&&r.push(o);}return r}async function Vi(e,t){try{let[n,s]=await Promise.all([A.stat(e),A.stat(t)]);if(n.size!==s.size)return !1;let[r,i]=await Promise.all([A.readFile(e),A.readFile(t)]);return r.equals(i)}catch{return false}}async function Mr(e,t,n,s){let r=S.resolve(t);return n.has(r)?(s.debug("Skipped post-crawl copy over crawled page output",{phase:"copy-extra-paths",sourcePath:e,targetPath:t}),false):await Vi(e,t)?(s.debug("Skipped unchanged post-crawl copy target",{phase:"copy-extra-paths",sourcePath:e,targetPath:t}),false):(await A.mkdir(S.dirname(t),{recursive:true}),await A.copyFile(e,t),true)}async function Ki(e,t,n){let s=Object.entries(e.postCrawlCopyMap||{}).map(([c,o])=>({sourcePath:c.trim(),prefix:String(o||"").trim()}));if(s.length===0)return [];let r=0,i=[],a=new Set([...t.donePages].map(c=>S.resolve(le(e,c))));n.mark("copy-extra-paths");for(let c of s){let o=c.sourcePath,u=c.prefix;if(!o||!u){n.warn("Skipped post-crawl copy mapping with empty key/value",{sourcePath:o,prefixPath:u});continue}let l=oi(o);if(!l.resolvedPath){n.warn("Skipped post-crawl copy source because alias root is not configured",{sourcePath:o,alias:l.alias||"",requiredEnv:l.requiredEnv||"",prefixPath:u});continue}let d=l.resolvedPath,p=Gt(u);if(!p){n.warn("Skipped post-crawl copy mapping with invalid export prefix",{sourcePath:o,prefixPath:u});continue}let g;try{g=await A.stat(d);}catch{n.warn("Skipped post-crawl copy source because it does not exist",{sourcePath:o,sourceAbs:d,prefixPath:u});continue}let f=S.resolve(e.outputDir,p);if(g.isDirectory()){let b=await Er(d,f,a,n);i.push(...b),r+=b.length,b.length>0&&n.progress(`Copied static directory to export: ${d} -> /${p}`,{phase:"copy-extra-paths",sourcePath:d,targetPath:`/${p}`,copiedItems:r,changedFiles:b.length});continue}let w=S.basename(d),m=u.endsWith("/")?S.join(f,w):f;await Mr(d,m,a,n)&&(i.push(m),r++,n.progress(`Copied static file to export: ${d} -> /${Gt(u.endsWith("/")?`${u}${w}`:u)}`,{phase:"copy-extra-paths",sourcePath:d,targetPath:`/${Gt(u.endsWith("/")?`${u}${w}`:u)}`,copiedItems:r}));}return n.endMark("copy-extra-paths",{mappedSources:s.length,copiedItems:r}),i}function Ye(e,t,n,s,r){let i=new Set,a=ce(n).replace(/\\\//g,"/"),c=r==="page-html"?Qi(a):a,o=Ji(t,r);if(o){for(let l of zi(c)){let d=W(e,l,t,s,`${r}:css-url`);d&&L(e,d)&&i.add(d.toString());}for(let l of c.matchAll(/@import\s+(?:url\()?\s*['"]?([^'"\s;]+)['"]?\s*\)?/gi)){let d=W(e,l[1],t,s,`${r}:css-import`);d&&L(e,d)&&i.add(d.toString());}}if(o||r==="page-html")for(let l of c.matchAll(/<\?xml-stylesheet[^>]+href=["']([^"']+)["'][^>]*\?>/gi)){let d=W(e,l[1],t,s,`${r}:xml-stylesheet`);d&&L(e,d)&&i.add(d.toString());}let u=new RegExp(`(?:https?:)?//[^\\s'"<>\\);]+\\.${Kt}(?:\\?[^\\s'"<>\\);]*)?|(?<!\\.)/[^\\s'"<>\\);]+\\.${Kt}(?:\\?[^\\s'"<>\\);]*)?`,"gi");if(r==="page-html")for(let l of a.matchAll(u)){let d=l[0].startsWith("//")?`${new URL(e.sourceOrigin).protocol}${l[0]}`:l[0];if(Xt(d)){s.ignore(`${r}:serialized-url`,d,"looks like JavaScript/code fragment",t);continue}let p=W(e,d,t,s,`${r}:serialized-url`);p&&L(e,p)?i.add(p.toString()):p&&s.ignore("asset",p.toString(),"serialized URL did not pass safe asset path filter",t);}if(r!=="page-html"&&qi(t))for(let l of sr(a)){if(Xt(l)||!/\.(?:js|mjs)(?:[?#]|$)/i.test(l))continue;let d=W(e,l,t,s,`${r}:relative-asset`);d&&L(e,d)&&i.add(d.toString());}return [...i]}function Gi(e,t,n,s){let r=new Set,i=ce(n);for(let a of i.matchAll(/href=["']([^"'#\s][^"']*?)["']/gi)){let c=a[1],o=W(e,c,t,s,"page-link");o&&(xr(e,o)||be(o)&&!je(o)&&!L(e,o)&&r.add(o.toString()));}return [...r]}async function gr(e,t,n,s,r,i,a=false){let c=new Map,o=(u,l)=>{let d=[l],p=new Set;for(;d.length>0;){let g=d.pop();if(g===u)return true;p.has(g)||(p.add(g),d.push(...c.get(g)??[]));}return false};for(;n.sitemapQueue.length>0;){let u=n.sitemapQueue.shift();n.queuedSitemaps.delete(u);let l=Pe(u,s,"sitemap","sitemap-queue");if(!l)continue;let d=l.toString();if(!n.doneSitemaps.has(d)){n.doneSitemaps.add(d),s.sitemap(`Fetching sitemap ${d}`,{url:d});try{let p=await t.get(d,{timeout:6e4});if(!p.ok()){if(s.skip("sitemap",d,p.status()),a)throw new Error(`Required content-sync sitemap returned HTTP ${p.status()}: ${d}`);continue}let g=await p.body(),f=p.url()||d,w=Pe(f,s,"sitemap-response",d);if(!w)continue;let m=w.toString(),h=await en(e,n.assetMap,m,g,n,s);Y(r,e,h.outputPath),Ie(r,h.outputPath);let b=g.toString("utf8");/<sitemapindex(?:\s|>)/i.test(b)?n.sitemapIndexUrls.add(m):n.sitemapLeafUrls.add(m);let k=Ye(e,m,b,s,"sitemap");for(let F of k)H(e,n,F,s,m);let M=[];for(let F of Wi(b)){let x=W(e,F.loc,m,s,"sitemap-loc");if(!x){if(a)throw new Error(`Content-sync sitemap contains an inadmissible location: ${F.loc}`);continue}if(Ue(x)){if(o(m,x.toString()))throw new Error(`Sitemap index cycle detected: ${m} -> ${x.toString()}`);c.has(m)||c.set(m,new Set),c.get(m).add(x.toString()),M.push(x.toString()),Pt(e,n,x.toString(),s,m);}else if(a){if(be(x)&&!L(e,x)){let j=i.requiredUrls.has(x.toString()),v=i.manifest.pages[x.toString()],P=!!v&&!!await De(v.outputPath);if(!j&&!P)throw new Error(`Content-sync sitemap coverage is incomplete for ${x.toString()}.`)}s.ignore("sitemap-loc",x.toString(),"content-sync sitemap-only traversal does not enqueue urlset locations",m);}else L(e,x)?H(e,n,x.toString(),s,m):be(x)?(F.lastmod&&(n.sitemapLastmodByPage[x.toString()]=F.lastmod),Ze(e,n,x.toString(),s,m)):s.reject("sitemap-loc",x.toString(),"not page/sitemap/asset-like",m);}i.trackManifest&&(i.manifest.assets[m]={url:m,outputPath:h.outputPath,isText:!0,contentType:p.headers()["content-type"]??"application/xml",changeToken:null,tokenSource:null,discoveredAssets:[...new Set([...k,...M])],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},await Se(e,i));}catch(p){if(s.error(`Failed sitemap ${d}`,{url:d,error:String(p)}),a)throw p}}}}async function Zi(e,t,n,s,r,i,a){let c=W(e,s,e.sourceOrigin,r,"asset-fetch");if(!c||!L(e,c))return;let o=c.toString();if(n.doneAssets.has(o))return;let u=i.enabled||i.strictTargeted?i.previousManifest.assets[o]:void 0,l=i.trackManifest?await wt(e,t,i,o,r):null,d=l?.token??null,p=ir(u?.changeToken,l),g=i.strictTargeted&&(!l?.supported||!l.token)&&or(e.sourceOrigin,o),f=i.strictTargeted?i.manifest.assets[o]:void 0;if(f?.lastSeenRunId===i.runId&&await De(f.outputPath)){n.doneAssets.add(o);for(let m of f.discoveredAssets||[])H(e,n,m,r,o);Y(a,e,f.outputPath),f.isText&&Ie(a,f.outputPath),r.info(`Resumed completed content-sync asset ${o}`,{url:o,source:"content-sync-checkpoint"}),Fe(n,r);return}if(u&&(p||g)&&await De(u.outputPath)){i.manifest.assets[o]={...u,changeToken:d,tokenSource:l?.tokenSource??u.tokenSource,discoveredAssets:[...u.discoveredAssets||[]],lastSeenRunId:i.runId},delete i.manifest.pages[o],n.doneAssets.add(o);for(let m of u.discoveredAssets||[])H(e,n,m,r,o);r.info(`Reused unchanged trusted asset ${o}.`,{url:o,tokenSource:l?.tokenSource??"unknown",phase:"download-assets",source:p?"asset-change-token-match":"content-sync-release-fingerprint"}),Fe(n,r);return}let w=(m,h={})=>{if(!u||i.strictTargeted)return false;i.manifest.assets[o]={...u,discoveredAssets:[...u.discoveredAssets||[]],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId},delete i.manifest.pages[o],n.doneAssets.add(o);for(let b of u.discoveredAssets||[])H(e,n,b,r,o);return r.warn(`Keeping previous incremental asset ${o} after fetch issue.`,{url:o,reason:m,preservedFromPreviousManifest:true,...h,phase:"download-assets"}),Fe(n,r),true};r.asset(`Fetching asset ${o}`,{url:o});try{let m=Oe(e,n.assetMap,o),h=m?await De(m):null;if(m&&h)try{let y=await N(`fetch asset headers ${o}`,6e4,()=>t.head(o,{timeout:6e4})),R=y.headers();if(y.ok()&&Ui(h,R)){let U=await kr(m);if(U!==null){let q=y.url()||o,Z=Pe(q,r,"asset-response",o);if(!Z)return;let V=Z.toString(),_=await en(e,n.assetMap,V,U,n,r,R);_.wroteFile&&(Y(a,e,_.outputPath),ye(_.outputPath)&&Ie(a,_.outputPath)),n.doneAssets.add(o),r.info(`Reused existing asset ${o} based on response headers.`,{url:o,filePath:m,lastModified:R["last-modified"]||"",contentLength:R["content-length"]||"",phase:"download-assets"}),Fe(n,r);let $=pr(c,R),ge=u?.discoveredAssets?[...u.discoveredAssets]:[];if($||u?.isText){let ve=U.toString("utf8"),et=Ye(e,V,ve,r,"asset:cached");(et.length>0||!u)&&(ge=et);for(let kt of ge)H(e,n,kt,r,V);}if(i.trackManifest){let ve=$||!!u?.isText;i.manifest.assets[o]={url:o,outputPath:_.outputPath,isText:ve,contentType:Zt(R)||u?.contentType||null,changeToken:l?.supported?l.token:null,tokenSource:l?.supported?l.tokenSource??null:null,discoveredAssets:ge,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!ve},delete i.manifest.pages[o],(i.enabled||i.strictTargeted)&&ve&&await Se(e,i);}return}}}catch{}let b=await N(`fetch asset ${o}`,6e4,()=>t.get(o,{timeout:6e4}));if(!b.ok()){if(w(`http-${b.status()}`,{status:b.status()}))return;if(i.strictTargeted)throw new Error(`Required content-sync asset returned HTTP ${b.status()}: ${o}`);r.skip("asset",o,b.status());return}let k=await N(`read asset response ${o}`,6e4,()=>b.body()),M=b.url()||o,F=Pe(M,r,"asset-response",o);if(!F)return;let x=F.toString(),j=b.headers(),v=await en(e,n.assetMap,x,k,n,r,j);v.wroteFile&&(Y(a,e,v.outputPath),ye(v.outputPath)&&Ie(a,v.outputPath)),n.doneAssets.add(o),Fe(n,r);let P=pr(c,j),C=[];if(P){let y=k.toString("utf8");C=Ye(e,x,y,r,`asset:${S.extname(c.pathname).toLowerCase()||j["content-type"]||"unknown"}`);for(let R of C)H(e,n,R,r,x);}i.trackManifest&&(i.manifest.assets[o]={url:o,outputPath:v.outputPath,isText:P,contentType:Zt(j),changeToken:l?.supported?l.token:null,tokenSource:l?.supported?l.tokenSource??null:null,discoveredAssets:C,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!P},delete i.manifest.pages[o],(i.enabled||i.strictTargeted)&&P&&await Se(e,i));}catch(m){if(w("fetch-error",{error:String(m)}))return;if(r.error(`Failed asset ${o}`,{url:o,error:String(m)}),i.strictTargeted)throw m}finally{n.doneAssets.has(o)||(n.doneAssets.add(o),Fe(n,r));}}async function Yi(e,t,n,s,r,i){let a=Math.max(1,Number(e.assetDownloadConcurrency||e.concurrency||1)),c=Array.from({length:a},async()=>{for(;n.assetQueue.length>0;){let o=n.assetQueue.shift();o&&(n.queuedAssets.delete(o),await Zi(e,t,n,o,s,r,i));}});await Promise.all(c);}function Xi(e){let t=Math.ceil(e/1e3);return `${t} second${t===1?"":"s"}`}function ue(e){return Math.max(6e4,e.navigationTimeoutMs*2,e.readiness.timeoutMs+e.readiness.fallbackWaitMs+15e3)}function yt(e){return Math.max(15e3,Math.min(6e4,ue(e)))}function eo(e){return Math.max(15e3,e.readiness.timeoutMs+e.readiness.fallbackWaitMs+1e4)}function an(e){return e.stats.pagesCompleted}function Fr(e){let n=e.options?.browserProcess;return {pid:typeof n?.process?.pid=="number"?n.process.pid:null,kill:typeof n?.kill=="function"?n.kill.bind(n):null}}async function to(e,t,n){let s=Fr(e);try{if(s.kill){await s.kill(),t.warn(`Force-killed crawl worker browser after ${n}`,{browserPid:s.pid,reason:n});return}if(s.pid!==null){process.kill(s.pid,"SIGKILL"),t.warn(`Sent SIGKILL to crawl worker browser after ${n}`,{browserPid:s.pid,reason:n});return}t.warn(`Could not resolve crawl worker browser PID after ${n}`,{reason:n});}catch(r){t.error(`Failed to force-kill crawl worker browser after ${n}`,{browserPid:s.pid,reason:n,error:String(r)});}}async function N(e,t,n){let s;try{return await Promise.race([n(),new Promise((r,i)=>{s=globalThis.setTimeout(()=>{i(new Error(`${e} timed out after ${Xi(t)}.`));},t);})])}finally{s!==void 0&&globalThis.clearTimeout(s);}}async function no(e,t){let n=eo(e);await t.evaluate(async s=>{await new Promise(r=>{let i=0,a=700,c=Date.now(),o=()=>{window.clearInterval(u),window.scrollTo(0,0),r();},u=window.setInterval(()=>{if(Date.now()-c>=s.maxDurationMs){o();return}window.scrollBy(0,a),i+=a;let l=document.body?.scrollHeight||0,d=document.documentElement?.scrollHeight||0,p=Math.max(l,d);i>=p+window.innerHeight&&o();},120);});},{maxDurationMs:n});}async function ro(e,t){await t.waitForLoadState("domcontentloaded",{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForSelector&&await t.waitForSelector(e.readiness.waitForSelector,{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForFunction&&await t.waitForFunction(e.readiness.waitForFunction,void 0,{timeout:e.readiness.timeoutMs}).catch(()=>{}),await no(e,t),await t.waitForTimeout(e.readiness.fallbackWaitMs);}async function so(e,t){await t.waitForLoadState("domcontentloaded",{timeout:e.readiness.timeoutMs}).catch(()=>{}),await t.waitForLoadState("load",{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForSelector&&await t.waitForSelector(e.readiness.waitForSelector,{timeout:e.readiness.timeoutMs}).catch(()=>{}),await t.waitForTimeout(e.readiness.fallbackWaitMs);}function io(e,t){return e.noJavaScriptRenderPathPrefixes.some(n=>rn(t,n))}async function oo(e,t,n,s,r=true){let i=new Set;if(r){let c=await t.evaluate(()=>{let o=new Set,u=["href","src","poster","data-src","data-lazy-src","data-original","data-bg","data-background","data-href"],l=new Set,d=["srcset","data-srcset","data-lazy-srcset"];return document.querySelectorAll("*").forEach(p=>{for(let f of u){let w=p.getAttribute(f);w&&o.add(w);}for(let f of d){let w=p.getAttribute(f);w&&w.split(",").forEach(m=>{let h=m.trim().split(/\s+/)[0];h&&o.add(h);});}let g=p.getAttribute("style");g&&l.add(g);}),{attrs:[...o],styles:[...l]}});for(let o of c.attrs)for(let u of Hi(o)){let l=W(e,u,n,s,"dom-attr");l&&L(e,l)&&i.add(l.toString());}for(let o of c.styles)for(let u of Ye(e,n,o,s,"dom-style"))i.add(u);}let a=await t.content();for(let c of Ye(e,n,a,s,"page-html"))i.add(c);return [...i]}async function fr(e,t,n,s,r){let i=le(e,t);await Ve(i,n,"utf8");let a=await A.stat(i);r?.debug(`Saved page output ${t}`,{phase:"save-pages",url:t,outputPath:i,bytes:a.size}),s.stats.pagesSaved++;let c=Math.min(s.stats.pagesQueued,an(s)+1);r&&(s.stats.pagesSaved%10===0||s.stats.pagesSaved===1)&&r.progress(`Page progress: processed ${c}, rendered ${s.stats.pagesRendered}, saved ${s.stats.pagesSaved}, discovered ${s.stats.pagesQueued}.`,{donePages:c,claimedPages:s.donePages.size,pagesRendered:s.stats.pagesRendered,pagesSaved:s.stats.pagesSaved,pagesQueued:s.stats.pagesQueued,pageQueue:s.pageQueue.length,phase:"save-pages"});}function ao(e){let t=an(e);return t%5===0||t===1||t===e.stats.pagesQueued}function co(e,t){let n=an(e);t.progress(`Render progress: processed ${n}, rendered ${e.stats.pagesRendered}, saved ${e.stats.pagesSaved}, discovered ${e.stats.pagesQueued}.`,{donePages:n,claimedPages:e.donePages.size,pagesRendered:e.stats.pagesRendered,pagesSaved:e.stats.pagesSaved,pagesQueued:e.stats.pagesQueued,phase:"render-pages"});}async function uo(e){await e.addInitScript(()=>{Object.defineProperty(window,"__WPSUITE_STATIC_EXPORT__",{value:true,writable:false,configurable:true});let t=n=>{if(n==null||String(n)==="")return true;try{let s=new URL(String(n),window.location.href),r=new URL(window.location.href);return s.hash="",r.hash="",s.href===r.href}catch{return false}};try{let n=window.location.assign.bind(window.location),s=window.location.replace.bind(window.location),r=window.location.reload.bind(window.location);Object.defineProperty(window.location,"assign",{configurable:!0,value:i=>{if(t(i)){console.warn("[smartcloud-static-publisher] blocked same-page location.assign",i??"");return}return n(i)}}),Object.defineProperty(window.location,"replace",{configurable:!0,value:i=>{if(t(i)){console.warn("[smartcloud-static-publisher] blocked same-page location.replace",i??"");return}return s(i)}}),Object.defineProperty(window.location,"reload",{configurable:!0,value:()=>{console.warn("[smartcloud-static-publisher] blocked location.reload");}});}catch{}});}async function lo(e,t,n){let s=await e.newContext({viewport:t.viewport,userAgent:"WPSuiteStaticPublisher/0.8 Playwright SitemapOnly",ignoreHTTPSErrors:t.ignoreHttpsErrors,...n?{javaScriptEnabled:false}:{}});return n||await uo(s),s}async function po(e,t,n,s,r,i,a){let c=await chromium.launch({headless:true}),o=Fr(c);o.pid!==null&&n.debug(`Launched crawl worker browser PID ${o.pid}`,{browserPid:o.pid});try{for(;t.pageQueue.length>0&&!(e.maxPages>0&&t.donePages.size>=e.maxPages);){let u=t.pageQueue.shift();if(!u)break;t.queuedPages.delete(u);let l=null,d=null;try{let p=Pe(u,n,"page","page-queue");if(!p)continue;let g=p.toString();if(u=g,t.queuedPages.delete(u),t.donePages.has(u))continue;t.donePages.add(u),i.enabled&&i.seenPages.add(u);let f=on(e,u),w=io(e,p.pathname);if(!be(p)||L(e,p)||je(p)){if(L(e,p)){n.info(`Worker redirected non-page URL to asset queue: ${u}`,{url:u,source:"worker-guard"}),H(e,t,u,n,"worker-guard");continue}n.reject("page",u,"guard rejected non-page URL before rendering","worker");continue}let m=i.strictTargeted?i.manifest.pages[u]:void 0;if(m?.lastSeenRunId===i.runId&&await De(m.outputPath)){i.seenPages.add(u);for(let y of m.discoveredAssets||[])H(e,t,y,n,u);Y(a,e,m.outputPath),Ie(a,m.outputPath),n.info(`Resumed completed content-sync page ${u}`,{url:u,source:"content-sync-checkpoint"});continue}let h=await mi(e,r,t,i,u,n);if(i.enabled&&s!=="single-url"&&s!=="content-sync"){let y=i.manifest.pages[u];if(h.action==="reuse"&&y){for(let R of y.discoveredAssets)H(e,t,R,n,u);for(let R of y.discoveredPages)Ze(e,t,R,n,u);y.lastSeenRunId=i.runId,y.sitemapLastmod=Ke(t.sitemapLastmodByPage[u])??y.sitemapLastmod,h.changeToken?.supported&&(y.changeToken=h.changeToken.token,y.tokenSource=h.changeToken.tokenSource??y.tokenSource),n.info(`Incremental reuse skipped unchanged page ${u}`,{url:u,mode:"incremental",reason:h.changeToken?.supported===!0?"change-token-match":"sitemap-lastmod-match"});continue}}l=await N(`create page context ${u}`,ue(e),()=>lo(c,e,w)),d=await N(`create page ${u}`,ue(e),()=>l.newPage());let b=!1,k=new Set;await d.route("**/*",async y=>{let R=y.request();if(R.isNavigationRequest()&&R.frame()===d.mainFrame())try{let U=new URL(R.url()),q=new URL(g);if(U.hash="",q.hash="",U.href===q.href){if(b){n.warn(`Blocked same-page navigation/reload for ${u}`,{url:u,requestUrl:R.url()}),await y.abort("aborted");return}b=!0;}}catch{}await y.continue();}),d.on("response",y=>{try{let R=W(e,y.url(),e.sourceOrigin,n,"network-response");R&&L(e,R)&&(k.add(R.toString()),H(e,t,R.toString(),n,u));}catch{}}),n.page(`Rendering ${u}`,{url:u});let M=null,F=null;try{if(M=await d.goto(u,{waitUntil:"domcontentloaded",timeout:e.navigationTimeoutMs}),M&&M.ok())try{F=await N(`read response body ${u}`,ue(e),()=>M.text());}catch{F=null;}}catch(y){n.warn(`Navigation issue for ${u}; saving current DOM if available`,{url:u,error:String(y)});}if(s==="content-sync"&&M){let y=Pe(M.url(),n,"content-sync-final-response",u)?.toString();if(y&&y!==g){if(i.deleteOnMissingUrls.has(u)){await tn(e,i,a,u,i.deleteOnMissingUrls),n.info(`Removed stale content-sync archive route redirected to ${y}`,{url:u,finalResponseUrl:y,source:"content-sync-tombstone"});continue}throw new Error(`Required content-sync route redirected outside its planned URL: ${u} -> ${y}`)}}if(f){let y=M?.status()??null;if(y!==404){n.error(`Generated 404 request path returned unexpected status for ${u}`,{url:u,expectedStatus:404,status:y,requestPath:e.generated404RequestPath});continue}n.info(`Capturing rendered 404 page for ${u}`,{url:u,status:y,outputPath:le(e,u)});}else if(M&&!M.ok()){if(s==="content-sync"&&(M.status()===404||M.status()===410)&&i.deleteOnMissingUrls.has(u)){await tn(e,i,a,u,i.deleteOnMissingUrls),n.info(`Removed stale content-sync archive page ${u}`,{url:u,status:M.status(),source:"content-sync-tombstone"}),await d.close();continue}if(s==="content-sync")throw new Error(`Required content-sync route returned HTTP ${M.status()}: ${u}`);n.skip("page",u,M.status(),t.pageDiscoverySources.get(u)),await d.close();continue}w?(n.info(`Rendering without JS execution for ${u}`,{url:u,mode:"no-js"}),await N(`wait for rendered page ${u}`,ue(e),()=>so(e,d))):await N(`wait for rendered page ${u}`,ue(e),()=>ro(e,d)),t.stats.pagesRendered++;let x=await N(`extract rendered assets ${u}`,ue(e),()=>oo(e,d,g,n,!w));for(let y of x)H(e,t,y,n,u);let j=[...new Set([...x,...k])],v=F??await N(`capture rendered html ${u}`,ue(e),()=>d.content()),P=s!=="single-url"&&s!=="content-sync"&&!f?Gi(e,u,v,n):[];if(s!=="single-url"&&s!=="content-sync"&&!f)for(let y of P)Ze(e,t,y,n,u);await fr(e,u,v,t,n);let C=le(e,u);if(Y(a,e,C),Ie(a,C),i.trackManifest){let y=M?.headers();i.manifest.pages[u]={url:u,outputPath:C,contentType:Zt(y),changeToken:h.changeToken?.supported?h.changeToken.token:null,tokenSource:h.changeToken?.supported?h.changeToken.tokenSource??null:null,sitemapLastmod:Ke(t.sitemapLastmodByPage[u])??null,discoveredPages:P,discoveredAssets:j,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},(i.enabled||i.strictTargeted)&&await Se(e,i);}}catch(p){if(i.strictTargeted)throw n.error(`Failed required content-sync page ${u}`,{url:u,error:String(p)}),p;try{let g=d?await N(`capture partial html ${u}`,ue(e),()=>d.content()):"";if(g&&g.trim()){await fr(e,u,g,t,n);let f=le(e,u);if(Y(a,e,f),Ie(a,f),i.trackManifest){let w=i.manifest.pages[u]??i.previousManifest.pages[u];i.manifest.pages[u]={url:u,outputPath:f,contentType:w?.contentType??null,changeToken:null,tokenSource:null,sitemapLastmod:Ke(t.sitemapLastmodByPage[u])??w?.sitemapLastmod??null,discoveredPages:w?.discoveredPages?[...w.discoveredPages]:[],discoveredAssets:w?.discoveredAssets?[...w.discoveredAssets]:[],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},(i.enabled||i.strictTargeted)&&await Se(e,i);}n.warn(`Saved partial DOM for ${u}`,{url:u,error:String(p)});}}catch(g){n.error(`Could not save partial DOM for ${u}`,{url:u,error:String(g)});}n.error(`Failed page ${u}`,{url:u,error:String(p)});}finally{t.stats.pagesCompleted++,ao(t)&&co(t,n),d&&await N(`close page ${u}`,yt(e),()=>d.close()).catch(p=>{n.warn(`Timed out while closing page ${u}`,{url:u,browserPid:o.pid,error:String(p)});}),l&&await N(`close page context ${u}`,yt(e),()=>l.close()).catch(p=>{n.warn(`Timed out while closing page context for ${u}`,{url:u,browserPid:o.pid,error:String(p)});});}}}finally{await N("close worker browser",yt(e),()=>c.close()).catch(u=>(n.warn("Timed out while closing crawl worker browser",{browserPid:o.pid,error:String(u)}),to(c,n,"browser.close timeout")));}}async function go(e){try{let t=await A.readFile(e),s=(e.endsWith(".gz")?gunzipSync(t):t).toString("utf8").trim();if(!s)return [];try{let r=JSON.parse(s);if(Array.isArray(r))return r;if(r&&typeof r=="object")return [r]}catch{return s.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).map(r=>{try{let i=JSON.parse(r);return i&&typeof i=="object"?i:null}catch{return null}}).filter(r=>r!==null)}return []}catch{return []}}function mr(e){let t=String(e||"").toLowerCase();return t.includes("timeout")||t.includes("timed out")||t.includes("navigation timeout")}function fo(e){let t=String(e?.job?.command||"").trim(),n=String(e?.job?.crawlMode||"full").trim();return t!=="publish"&&t!=="crawl"?false:n!=="incremental"}function mo(e){let t=[e?.archivedAt,e?.job?.endedAt,e?.job?.startedAt];for(let n of t){let s=Date.parse(String(n||""));if(Number.isFinite(s))return s}return 0}async function Dr(e){try{let t=await A.readFile(e,"utf8"),n=JSON.parse(t);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function hr(e){let t=String(e.originalFileName||"").toLowerCase();return t.endsWith("errors.jsonl")?0:t.endsWith("errors.json")?1:2}function ho(e,t){let n=Array.isArray(t?.artifacts)?t.artifacts.filter(s=>String(s?.role||"").trim()==="errors"&&String(s?.storedFileName||"").trim()!=="").sort((s,r)=>hr(s)-hr(r)).map(s=>S.join(e,String(s.storedFileName))):[];return [...new Set([...n,S.join(e,"errors.jsonl"),S.join(e,"errors.json"),S.join(e,"errors.jsonl.gz"),S.join(e,"errors.json.gz")])]}async function wr(e){let t=await Dr(S.join(e,"job.json"));for(let n of ho(e,t)){let s=await go(n);if(s.length>0)return s}return []}async function wo(e){let t=S.join(e.logDir,"archive"),n;try{n=await A.readdir(t);}catch{return ""}let s="",r=0;for(let i of n){let a=S.join(t,i);if(!(await A.stat(a).catch(()=>null))?.isDirectory())continue;let o=await Dr(S.join(a,"job.json"));if(!fo(o))continue;let u=mo(o);u>=r&&(r=u,s=a);}return s}async function yo(e){let t=await wo(e),n=t!==""?await wr(t):await wr(e.logDir),s=new Set;for(let r of n)if(mr(r.error)||mr(r.message)){let i=r.url;typeof i=="string"&&i&&s.add(i);}return [...s]}async function So(e){let t=[];for(let n of e)if(n.startsWith("@")){let s=n.slice(1),r=await A.readFile(s,"utf8");t.push(...r.split(/\r?\n/).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")));}else t.push(n);return t}async function Po(e){if(!e)throw new Error("Content-sync crawl requires an immutable impact plan.");let t=JSON.parse(await A.readFile(e,"utf8"));return He(t),t}function bo(e,t){let n;try{n=new URL(e);}catch{return false}return t.archiveFamilies.some(s=>{let r=new URL(s.url);if(n.origin!==r.origin)return false;if(n.toString()===r.toString())return true;if(n.searchParams.has("paged")&&n.pathname===r.pathname)return /^\d+$/.test(n.searchParams.get("paged")||"");let i=r.pathname.replace(/\/+$/,""),a=n.pathname.slice(i.length).replace(/^\/+/,""),c=String(s.paginationBase||"page").replace(/^\/+|\/+$/g,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.pathname.startsWith(`${i}/`)&&new RegExp(`^${c}/\\d+/?$`).test(a)})}function ht(e,t,n){let s=n==="page"?le(e,t):bt(e,t).originalFilePath;return we(e.outputDir,s)}async function tn(e,t,n,s,r){let i=t.manifest.pages[s];if(!i)return;let a=we(e.outputDir,i.outputPath);if(!a)throw new Error(`Manifest-owned page path escaped output root: ${s}`);let c=S.resolve(i.outputPath);Object.entries(t.manifest.pages).some(([u,l])=>u!==s&&!r.has(u)&&S.resolve(l.outputPath)===c)||(await A.rm(i.outputPath,{force:true}),n.deletedFiles.add(a)),delete t.manifest.pages[s];}function vo(e,t){let n=new Set,s=[...t];for(;s.length>0;){let r=s.shift();if(n.has(r))continue;n.add(r);let i=e.assets[r];for(let a of i?.discoveredAssets??[])try{Ue(new URL(a))&&s.push(a);}catch{}}return n}async function Co(e,t,n,s,r){let i=vo(n.previousManifest,r);for(let a of i){if(t.doneSitemaps.has(a))continue;let c=n.previousManifest.assets[a];if(!c)continue;let o=we(e.outputDir,c.outputPath);if(!o)throw new Error(`Manifest-owned sitemap path escaped output root: ${a}`);await A.rm(c.outputPath,{force:true}),s.deletedFiles.add(o),delete n.manifest.assets[a];}await Se(e,n);}async function Ro(e){try{let t=await A.readFile(S.join(e.outputDir,"asset-map.json"),"utf8");return JSON.parse(t)}catch{return {}}}async function Io(e){let t=["crawl.log.jsonl","current-crawl-event.json","rejected.jsonl","ignored.jsonl","skipped-http.jsonl","errors.jsonl","timings.jsonl","rejected.json","ignored.json","skipped-http.json","errors.json","timings.json"];await A.mkdir(e,{recursive:true}),await Promise.all(t.map(async n=>{try{await A.unlink(S.join(e,n));}catch(s){if(s.code!=="ENOENT")throw s}}));}function yr(e,t,n,s,r){let i=W(e,n,e.sourceOrigin,s,"manual-url");i&&(Ue(i)?Pt(e,t,i.toString(),s,r):L(e,i)?H(e,t,i.toString(),s,r):be(i)?Ze(e,t,i.toString(),s,r):s.reject("manual-url",i.toString(),"not page/sitemap/asset-like",r));}async function Or(e=process.argv.slice(2)){let t=[],n=await ne(void 0,{onRemotePublisherConfigDiagnostic:P=>{t.push(P);}}),s=t.at(-1)??null,r=ri(e),i=r.mode==="content-sync"?await Po(r.contentSyncPlanPath):null;if(r.resumeRewrite&&r.mode!=="full")throw new Error("--resume-rewrite is only supported for full crawl/publish jobs.");let a=[];r.mode==="retry-timeouts"&&(a=await yo(n)),r.mode==="single-url"&&(a=await So(r.urls)),i&&(a=[...i.directRenderUrls,...i.archiveFamilyUrls]);let c=r.crawlMode==="incremental"&&r.mode==="full",o=c&&typeof n.subscriptionType=="string"&&n.subscriptionType.trim()!=="";if(i&&n.subscriptionType!=="PROFESSIONAL"&&n.subscriptionType!=="AGENCY")throw new Error("Content-sync requires an active Professional or Agency subscription.");let u=(r.mode==="full"||r.mode==="single-url"||r.mode==="content-sync")&&!r.resumeRewrite,l=r.mode!=="full"||r.resumeRewrite||o,d=l?await Ro(n):{},p=o||r.mode==="single-url"||r.mode==="content-sync"?await ui(n):vr(),g=new Set(a),f=new Set;if(i){for(let P of i.archiveFamilies)if(P.foundPosts===0)for(let C of P.pageUrls)f.add(C);for(let P of Object.keys(p.pages))bo(P,i)&&!g.has(P)&&(a.push(P),f.add(P));}let w={enabled:o,trackManifest:u,manifest:Yt(p),previousManifest:Yt(p),runId:i?.jobId??`${Date.now()}`,seenPages:new Set,changeTokenCache:new Map,manifestSaveChain:Promise.resolve(),strictTargeted:!!i,requiredUrls:g,deleteOnMissingUrls:f};await Io(n.logDir);let m=new gt(n.logDir,n.logLevel);if(s){let P={status:s.status,virtualAssetBaseUrl:s.virtualAssetBaseUrl,subscriptionType:s.subscriptionType??null,error:s.error,requests:s.requests,source:"remote-publisher-config"};s.status==="loaded"&&s.subscriptionType?m.info("Loaded remote WP Suite publisher configuration.",P):m.warn("Remote WP Suite publisher configuration is unavailable or has no active subscription type.",P);}if(c&&!o){let P="Incremental crawl requires an active remote publisher subscription; refusing to fall back to a destructive full crawl.";throw m.error(P,{requestedMode:r.crawlMode,subscriptionType:n.subscriptionType??null,source:"incremental-subscription-guard"}),await m.flush(),new Error(P)}let h={pageQueue:[],queuedPages:new Set,donePages:new Set,pageDiscoverySources:new Map,assetQueue:[],queuedAssets:new Set,doneAssets:new Set,sitemapQueue:[],queuedSitemaps:new Set,doneSitemaps:new Set,sitemapIndexUrls:new Set,sitemapLeafUrls:new Set,sitemapLastmodByPage:{},assetMap:{...d},assetVariantDigestsByOriginalPath:new Map,stats:{pagesQueued:0,pagesRendered:0,pagesCompleted:0,assetsQueued:0,sitemapsQueued:0,assetsSaved:0,pagesSaved:0}},b=ci();if(await $e(n),await Wn(n,{startedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir)}),l||await A.rm(n.outputDir,{recursive:true,force:true}),await A.mkdir(n.outputDir,{recursive:true}),i){let P=new Set([...i.deleteUrls,...w.deleteOnMissingUrls]);for(let C of i.deleteUrls)await tn(n,w,b,C,P);}if(r.resumeRewrite)m.info("Resuming final rewrite from existing output.",{phase:"rewrite-text",mode:r.mode,crawlMode:r.crawlMode});else {let P=await request.newContext({ignoreHTTPSErrors:n.ignoreHttpsErrors});try{if(m.mark("discovery"),r.mode==="full"?(n.sitemapPaths.forEach(y=>Pt(n,h,y,m)),await gr(n,P,h,m,b,w),n.seedPaths.forEach(y=>yr(n,h,y,m,"seed-path")),n.generated404RequestPath&&Ze(n,h,n.generated404RequestPath,m,"generated-404-request-path")):(a.forEach(y=>yr(n,h,y,m,"cli")),i?.sitemapUrls.forEach(y=>Pt(n,h,y,m,"content-sync-impact")),await gr(n,P,h,m,b,w,r.mode==="content-sync"),i&&await Co(n,h,w,b,i.sitemapUrls)),m.endMark("discovery",{pages:h.pageQueue.length,assets:h.assetQueue.length,sitemaps:h.sitemapQueue.length}),m.summary(`Queued ${h.pageQueue.length} pages, ${h.assetQueue.length} assets, ${h.sitemapQueue.length} sitemaps.`,{mode:r.mode,crawlMode:r.crawlMode,queuedPages:h.pageQueue.length,queuedAssets:h.assetQueue.length,queuedSitemaps:h.sitemapQueue.length}),r.mode==="retry-timeouts"&&h.pageQueue.length===0&&h.assetQueue.length===0&&h.sitemapQueue.length===0){m.summary("No timed-out URLs were queued. Skipping retry crawl.",{mode:r.mode,crawlMode:r.crawlMode,queuedPages:0,queuedAssets:0,queuedSitemaps:0}),await m.flush();return}m.mark("render-pages");let C=Array.from({length:Math.max(1,n.concurrency)},()=>po(n,h,m,r.mode,P,w,b));if(await Promise.all(C),m.endMark("render-pages",{pages:h.stats.pagesCompleted}),m.mark("download-assets"),m.progress("Asset download phase started.",{phase:"download-assets",doneAssets:h.doneAssets.size,assetsQueued:h.stats.assetsQueued,assetQueue:h.assetQueue.length}),await pi(n,P,w,[...h.assetQueue],m),await Yi(n,P,h,m,w,b),m.endMark("download-assets",{assets:h.doneAssets.size}),w.enabled&&n.maxPages===0&&await wi(n,h,w,m,b),r.mode==="full"){let y=await Ki(n,h,m);for(let R of y)Y(b,n,R);}}finally{await N("dispose crawl request context",yt(n),()=>P.dispose()).catch(C=>{m.warn("Timed out while disposing crawl request context",{error:String(C)});});}}w.trackManifest&&await Se(n,w),await A.writeFile(S.join(n.outputDir,"asset-map.json"),JSON.stringify(h.assetMap,null,2),"utf8"),JSON.stringify(d,null,2)!==JSON.stringify(h.assetMap,null,2)&&Y(b,n,S.join(n.outputDir,"asset-map.json"));let k=r.mode==="single-url"||r.mode==="content-sync"?xi(n,h):w.enabled&&!r.resumeRewrite?yi(n,w,b,d,h.assetMap):void 0;m.mark("rewrite-text");let M=r.mode==="single-url"||r.mode==="content-sync"?`Rewriting text files touched by URL crawl: 0/${k?.length??0}`:"Rewriting text files...";m.progress(M,{phase:"rewrite-text",index:0,totalFiles:k?.length,changedTextFiles:0}),await dr(M);let F=Date.now(),x=await lt(n,h.assetMap,{files:k,previousAssetMap:d,onStart:({totalFiles:P,workerCount:C})=>{m.info(`Rewrite phase scanning ${P} text files.`,{phase:"rewrite-text",totalFiles:P,workerCount:C});},onProgress:async({index:P,totalFiles:C,changedTextFiles:y,file:R,changed:U})=>{U&&Y(b,n,S.join(n.outputDir,R)),m.checkpoint(`Rewriting text file ${P}/${C}`,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:R}),m.debug(`${U?"Rewrote":"Checked unchanged"} text file ${P}/${C}: ${R}`,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:R,changed:U});let q=Date.now();if(!(P===1||P===C||P%50===0||q-F>=5e3))return;F=q;let V=`Rewriting text files: ${P}/${C}`;m.progress(V,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:R}),await dr(V);}});w.trackManifest&&(Si(w,k),await Se(n,w)),m.endMark("rewrite-text",{changedTextFiles:x});let j=i?[...b.deletedFiles].sort():w.enabled&&!r.resumeRewrite?await bi(n,h,w,b,m):[],v=[...new Set((k||[]).map(P=>we(n.outputDir,S.isAbsolute(P)?P:S.join(n.outputDir,P))).filter(P=>P!==null))].sort();if(i){let P=[...b.changedFiles].sort(),C=new Set(P),y=new Set(i.directRenderUrls.map($=>ht(n,$,"page")).filter($=>!!$&&C.has($))),R=new Set(i.archiveFamilyUrls.map($=>ht(n,$,"page")).filter($=>!!$&&C.has($))),U=new Set([...h.sitemapLeafUrls].map($=>ht(n,$,"asset")).filter($=>!!$&&C.has($))),q=new Set([...h.sitemapIndexUrls].map($=>ht(n,$,"asset")).filter($=>!!$&&C.has($))),Z=new Set([...y,...R,...U,...q]),V=P.filter($=>!Z.has($)),_=[...new Set([...i.directRenderUrls,...i.archiveFamilyUrls,...i.sitemapUrls,...h.sitemapLeafUrls,...h.sitemapIndexUrls,...i.deleteUrls].map($=>{let ge=new URL($);return `${ge.pathname}${ge.search}`}))].sort();await Ht(n,{schemaVersion:2,generatedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir),runMode:"content-sync",crawlMode:"incremental",fullSyncRequired:false,changedFiles:P,deletedFiles:j,rewriteTargets:v,consumerId:i.consumerId,fromSequence:i.fromSequence,toSequence:i.toSequence,impactHash:i.impactHash,uploadGroups:{assets:V,content:[...y].sort(),listings:[...R].sort(),sitemapLeaves:[...U].sort(),sitemapIndexes:[...q].reverse()},invalidationPaths:_});}else await Ht(n,{schemaVersion:1,generatedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir),runMode:r.mode,crawlMode:r.crawlMode,fullSyncRequired:!(w.enabled&&!r.resumeRewrite),changedFiles:w.enabled&&!r.resumeRewrite?[...b.changedFiles].sort():[],deletedFiles:w.enabled&&!r.resumeRewrite?j:[],rewriteTargets:w.enabled&&!r.resumeRewrite?v:[]});await zn(n),m.summary(r.resumeRewrite?`Done. Resumed final rewrite over existing output and changed ${x} text files.`:`Done. Rendered ${h.stats.pagesRendered} pages, processed ${h.doneSitemaps.size} sitemaps and ${h.doneAssets.size} assets.`,{mode:r.mode,crawlMode:r.crawlMode,resumeRewrite:r.resumeRewrite,...h.stats,pagesRendered:h.stats.pagesRendered,donePages:h.stats.pagesCompleted,claimedPages:h.donePages.size,doneSitemaps:h.doneSitemaps.size,doneAssets:h.doneAssets.size,changedTextFiles:x}),await m.flush();}function xo(e){let t=e/6e4;if(Number.isInteger(t)&&t>=1)return `${t} minute${t===1?"":"s"}`;let n=Math.ceil(e/1e3);return `${n} second${n===1?"":"s"}`}async function X(e,t,n){let s=new AbortController,r=globalThis.setTimeout(()=>{s.abort(new Error(`${e} timed out after ${xo(t)}.`));},t);try{return await n({abortController:s,httpOptions:{abortSignal:s.signal,requestTimeout:t}})}finally{globalThis.clearTimeout(r);}}function Ao(e){return typeof e.subscriptionType=="string"&&e.subscriptionType.trim()!==""}function vt(e){let t="";for(let s=0;s<e.length;s++){let r=e[s];if(r==="--profile"){let i=(e[s+1]||"").trim();if(!i)throw new Error("Missing value for --profile.");t=i,s+=1;}else if(r.startsWith("--profile=")){let i=r.slice(10).trim();if(!i)throw new Error("Missing value for --profile.");t=i;}}let n=String(process.env.PUBLISHER_DEPLOY_PROFILE||process.env.PUBLISHER_DEPLOYMENT_PROFILE||"").trim();return t||n||null}function To(e,t){return {...e,...t??{}}}function ko(e,t){return {...e,...t??{},invalidationPaths:[...(t?.invalidationPaths??e.invalidationPaths)||[]]}}function Le(e,t){let n=String(t??e.deploymentTargetOverride??"").trim();if(!Ao(e)){if(n)throw new Error(`Deployment target "${n}" requires an active WPSuite subscription and remote publisher config.`);return {name:null,profile:null,config:e}}let s=String(n||e.defaultDeploymentProfile||"").trim();if(!s)return {name:null,profile:null,config:e};let r=e.deploymentProfiles?.[s];if(!r)throw new Error(`Unknown deployment profile "${s}". Check the linked WPSuite publisher configuration.`);return {name:s,profile:r,config:{...e,targetOrigin:r.targetOrigin??e.targetOrigin,s3:To(e.s3,r.s3),cloudFront:ko(e.cloudFront,r.cloudFront)}}}var qr="wpsuite-sha256",_r="wpsuite-normalized-sha256",Lo=/(?:^|[-_:.])(id|uid|nonce|token|hash|instance)(?:$|[-_:.])/i,gn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,qo=["SIGINT","SIGTERM"],It=new Set,Ct=new Map,jr=null;function _o(e){It.add(e);let t=false;return ()=>{t||(t=true,It.delete(e));}}async function No(){let e=[...It];e.length!==0&&await Promise.allSettled(e.map(async t=>{It.delete(t),await A.rm(t,{recursive:true,force:true});}));}function Bo(){if(!(Ct.size>0))for(let e of qo){let t=()=>{jr||(jr=No().finally(()=>{for(let[n,s]of Ct)process.off(n,s);Ct.clear(),process.exit(1);}));};Ct.set(e,t),process.on(e,t);}}Bo();function Wo(e,t){let n=String(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH||"").trim();if(n)return S.resolve(n);let s=t.trim();return s?S.join(S.resolve(s),"crawl-manifest.json"):S.join(S.resolve(e),".crawl-manifest.json")}function Nr(e){return S.normalize(e).split(S.sep).join("/")}function Ur(e,t){let n=S.relative(S.resolve(e),S.resolve(t));return !n||n.startsWith("..")||S.isAbsolute(n)?null:Nr(n)}async function Ho(e,t,n){let s=Wo(e.outputDir,t),r;try{r=await A.readFile(s,"utf8");}catch(l){return l.code==="ENOENT"?(n.warn("Deploy rewrite guard disabled because the crawl manifest is missing.",{manifestPath:s,source:"deploy-guard"}),null):(n.warn("Deploy rewrite guard disabled because the crawl manifest could not be read.",{manifestPath:s,error:l instanceof Error?l.message:String(l),source:"deploy-guard"}),null)}let i;try{i=JSON.parse(r);}catch(l){return n.warn("Deploy rewrite guard disabled because the crawl manifest is invalid JSON.",{manifestPath:s,error:l instanceof Error?l.message:String(l),source:"deploy-guard"}),null}let a=new Map,c=new Map,o=0,u=0;for(let[l,d]of Object.entries(i.pages||{})){let p=String(d?.outputPath||"").trim(),g=p?Ur(e.outputDir,p):null;if(g){let f=typeof d?.contentType=="string"&&d.contentType?d.contentType:null;f&&c.set(g,f);}!p||d?.rewriteComplete===true||g&&(o++,a.has(g)||a.set(g,{kind:"page",sourceUrl:l,outputPath:S.resolve(p),relativePath:g}));}for(let[l,d]of Object.entries(i.assets||{})){let p=String(d?.outputPath||"").trim(),g=d?.isText===true,f=p?Ur(e.outputDir,p):null;if(f){let w=typeof d?.contentType=="string"&&d.contentType?d.contentType:null;w&&c.set(f,w);}!p||!g||d?.rewriteComplete===true||f&&(u++,a.has(f)||a.set(f,{kind:"asset",sourceUrl:l,outputPath:S.resolve(p),relativePath:f}));}return {manifestPath:s,byRelativePath:a,contentTypeByRelativePath:c,pendingPages:o,pendingTextAssets:u}}function zo(e){return e&&(gn.test(e)?"__uuid__":/^[0-9a-f]{6,}$/i.test(e)?"__hex__":/^[0-9]{8,}$/.test(e)?"__num__":/^(?=.*[a-z])(?=.*\d)[a-z0-9]{8,}$/i.test(e)?"__alnum__":e)}function un(e){return e.split(/([_:.\-/=?&#]+)/g).map((t,n)=>n%2===1?t:zo(t)).join("")}function Qo(e){return e.split(/([_:.\-/=?&#]+)/g).map((t,n)=>n%2===1?t:gn.test(t)?"__uuid__":/^[0-9a-f]{6,}$/i.test(t)?"__hex__":/^[0-9]{6,}$/.test(t)?"__num__":/^[a-z0-9_-]{6,}$/i.test(t)?"__id__":t).join("")}function xt(e,t){return Array.isArray(e)?e.map(n=>xt(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,s])=>[n,xt(s,n)])):typeof e!="string"?e:t&&Lo.test(t)?Qo(e):gn.test(e)?"__uuid__":/^[0-9a-f]{6,}$/i.test(e)||/^[0-9]{8,}$/.test(e)?un(e):e}function Jo(e){return e.replace(/((?:https?:\/\/[^"'\s>]+|\/)(?:wp-content|wp-includes)\/[^"'\s>?]+)\?ver=[A-Za-z0-9._-]+(?=$|[#"'])/gi,"$1")}function Vo(e,t){let n=t.trim();if((n.startsWith("{")||n.startsWith("[")||n.startsWith('"'))&&e.startsWith("data-"))try{let r=JSON.parse(n);return JSON.stringify(xt(r))}catch{}if(e.startsWith("data-")&&/^[A-Za-z0-9+/=]+$/.test(n))try{let r=Buffer.from(n,"base64").toString("utf8"),i=JSON.parse(r),a=JSON.stringify(xt(i));return Buffer.from(a,"utf8").toString("base64")}catch{}return t}function Ko(e,t){let n=e.toLowerCase();return n==="class"?t.split(/(\s+)/).map((s,r)=>r%2===1?s:un(s)).join(""):n==="id"||n==="for"||n==="aria-controls"||n==="aria-labelledby"||n==="aria-describedby"||n==="aria-owns"||n==="aria-activedescendant"||n==="name"?un(t):n==="href"||n==="src"?Jo(t):Vo(n,t)}function Go(e){return e.replace(/<([a-z][^\s/>]*)([^<>]*?)>/gi,(t,n,s)=>{if(n.startsWith("/"))return t;let r=s.replace(/\s([:@a-zA-Z_][-:.a-zA-Z0-9_]*?)=(['"])([\s\S]*?)\2/g,(i,a,c,o)=>{let u=Ko(a,o);return ` ${a}=${c}${u}${c}`});return `<${n}${r}>`})}function cn(e){let t=S.extname(e).toLowerCase();return [".html",".htm",".xml",".xsl",".txt"].includes(t)||["robots.txt","sitemap.xml"].includes(S.basename(e))}function Rt(e,t){return [e.replace(/^\/+|\/+$/g,""),t.replace(/^\/+/,"")].filter(Boolean).join("/")}async function Zo(e,t,n,s){let r=new Map,i,a=0;do{a++;let c=await X(`S3 list objects page ${a} for s3://${t}/${n||""}`,3e5,({httpOptions:o})=>e.send(new ListObjectsV2Command({Bucket:t,Prefix:n||void 0,ContinuationToken:i}),o));for(let o of c.Contents||[]){if(!o.Key)continue;let u=(o.ETag||"").replace(/^"|"$/g,"").toLowerCase(),l=Number(o.Size??0);r.set(o.Key,{etag:u,size:l});}i=c.NextContinuationToken,s.debug(`Listed S3 keys page ${a}: ${r.size} keys so far`);}while(i);return r}async function Yo(e,t,n,s){if(s.has(n))return s.get(n)??null;try{let r=await X(`S3 head object ${n}`,3e5,({httpOptions:a})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),a)),i={etag:(r.ETag||"").replace(/^"|"$/g,"").toLowerCase(),size:Number(r.ContentLength??0)};return s.set(n,i),i}catch{return s.set(n,null),null}}async function Xo(e,t,n,s){let r=[...new Set(Array.from(n).filter(Boolean))];if(r.length===0)return s.info("No explicitly tombstoned S3 objects to delete."),[];s.info(`Deleting ${r.length} explicitly tombstoned S3 object(s)\u2026`);for(let i=0;i<r.length;i+=1e3){let a=r.slice(i,i+1e3);if(a.length===0)continue;let c=await X(`S3 delete objects batch ${Math.floor(i/1e3)+1}`,3e5,({httpOptions:o})=>e.send(new DeleteObjectsCommand({Bucket:t,Delete:{Objects:a.map(u=>({Key:u}))}}),o));if(c.Errors&&c.Errors.length>0){let o=c.Errors.map(u=>`${u.Key||"(unknown)"}: ${u.Code||"DeleteFailed"}`);throw new Error(`S3 reported ${o.length} object deletion error(s): ${o.join(", ")}`)}s.info(`Deleted batch of ${a.length} object(s).`);for(let o of a)s.debug(` deleted: ${o}`);}return r}function ea(e){return createHash("md5").update(e).digest("hex")}function Lr(e){return createHash("sha256").update(e).digest("hex")}function ln(e){return createHash("sha256").update(Go(e.toString("utf8"))).digest("hex")}async function ta(e,t,n,s){if(s.has(n))return s.get(n)??null;try{let a=((await X(`S3 head object metadata ${n}`,3e5,({httpOptions:c})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),c))).Metadata?.[qr]||"").trim().toLowerCase()||null;return s.set(n,a),a}catch{return s.set(n,null),null}}async function na(e,t,n,s,r){if(s.has(n))return s.get(n)??null;try{let a=((await X(`S3 head object normalized metadata ${n}`,3e5,({httpOptions:c})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),c))).Metadata?.[_r]||"").trim().toLowerCase();if(a)return s.set(n,a),a}catch{return s.set(n,null),null}if(r.has(n)){let i=r.get(n)??null;return s.set(n,i),i}try{let a=await(await X(`S3 get object ${n}`,3e5,({httpOptions:o})=>e.send(new GetObjectCommand({Bucket:t,Key:n}),o))).Body?.transformToByteArray(),c=a?ln(Buffer.from(a)):null;return r.set(n,c),s.set(n,c),c}catch{return r.set(n,null),s.set(n,null),null}}function ra(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"profile"}function sa(e,t){let n=e,s=Object.entries(t).sort((r,i)=>i[0].length-r[0].length);for(let[r,i]of s)r&&(n=n.split(r).join(i));return n}async function ia(e,t,n,s){let r=S.join(e,"asset-map.json"),i;try{i=await A.readFile(r,"utf8");}catch(o){if(o.code==="ENOENT")return;throw o}let a=JSON.parse(i);if(!a||typeof a!="object")return;let c=Object.fromEntries(Object.entries(a).map(([o,u])=>{let l=String(u??"");return t.urlRewriteMode==="absolute"&&t.targetOrigin&&n.targetOrigin&&t.targetOrigin!==n.targetOrigin&&(l=l.split(t.targetOrigin).join(n.targetOrigin)),l=sa(l,s),[o,l]}));await A.writeFile(r,JSON.stringify(c,null,2),"utf8");}async function oa(e,t,n,s,r,i){let a=e.targetOrigin!==t.targetOrigin,c=Object.keys(s).length>0;if(!n||!a&&!c)return {outputDir:e.outputDir,cleanup:async()=>{}};if(a&&e.urlRewriteMode!=="absolute")throw new Error(`Deployment profile "${n}" changes targetOrigin, but the base crawl output must use urlRewriteMode "absolute" for multi-target redeploys.`);let o=S.join(S.dirname(e.outputDir),`.deploy-profile-${ra(n)}-${Date.now()}`),u=_o(o);r.info(`Preparing deployment profile "${n}" from existing crawl output to ${o}...`);try{if(await A.rm(o,{recursive:!0,force:!0}),i){await A.mkdir(o,{recursive:!0});for(let g of i){let f=S.join(e.outputDir,g),w=S.join(o,g);await A.mkdir(S.dirname(w),{recursive:!0}),await A.copyFile(f,w);}}else await A.cp(e.outputDir,o,{recursive:!0});let l={...e,sourceOrigin:e.targetOrigin,targetOrigin:t.targetOrigin,extraReplacements:s,outputDir:o},d=1;r.info(`Rewriting text files for deployment profile "${n}"...`);let p=await lt(l,{},{files:i,onStart:({totalFiles:g,workerCount:f})=>{d=f,r.info(`Rewriting ${g} text file(s) for deployment profile "${n}" with ${f} worker(s).`);},onProgress:({index:g,totalFiles:f,changedTextFiles:w,file:m,changed:h})=>{let k=`Rewriting [${g}/${f}] ${m} (${h?"rewrote":"checked"}; ${w} changed so far)`;f<=200||g<=5||g%10===0||g===f?(r.progress(k,{file:m,index:g,totalFiles:f,changed:h,changedTextFiles:w,workerCount:d}),r.info(k)):r.debug(k);}});return await ia(o,e,t,s),r.info(`Prepared deployment profile "${n}" in ${o} (${p} rewritten text file(s)).`),{outputDir:o,cleanup:async()=>{u(),await A.rm(o,{recursive:!0,force:!0});}}}catch(l){throw r.error(`Failed to prepare deployment profile "${n}" temporary output.`,{tempDir:o,outputDir:e.outputDir,error:l instanceof Error?l.message:String(l),...l instanceof Error&&l.stack?{stack:l.stack}:{}}),await A.rm(o,{recursive:true,force:true}).catch(()=>{}),u(),await r.flush().catch(()=>{}),l}}async function Br(e=process.argv.slice(2)){let t=await ne(),n=vt(e),s=Le(t,n),r=S.resolve(s.config.logDir||"logs"),i=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",a=i?S.join(S.resolve(i),"deploy-diff.json"):"",c=new Me(r,"deploy.log.jsonl",s.config.logLevel??"info"),o=s.profile?.extraReplacements??{},u=async()=>{};try{let l=await at(t);if(e.includes("--content-sync")&&l?.schemaVersion!==2)throw new Error("Content-sync deployment requires a valid schema-2 targeted deploy plan.");let p=await Hn(t);if(p)throw new Error(`Deployment blocked: the crawl started at ${p.startedAt} did not complete its final rewrite. Run a successful crawl or resume the rewrite before deploying.`);let g=await oa(t,s.config,s.name,o,c,l?.schemaVersion===2?l.changedFiles:void 0);u=g.cleanup;let f={...s.config,outputDir:g.outputDir},w=f.s3SyncMode??"sdk-upload-delete";if(l?.schemaVersion===2&&l.deletedFiles.length>0&&w!=="sdk-upload-delete")throw new Error("Content-sync tombstones require the sdk-upload-delete S3 sync mode.");let m=l?.schemaVersion!==2&&g.outputDir!==t.outputDir&&(t.targetOrigin!==s.config.targetOrigin||Object.keys(o).length>0),h=!!l&&!l.fullSyncRequired&&!m;if(l?.schemaVersion===2&&!h)throw new Error("Content-sync deployment cannot widen into a full-output deployment.");s.name&&c.info(`Using deployment profile: ${s.name}`),c.info(`Starting deploy \u2014 s3://${f.s3.bucket}/${f.s3.prefix||""} (region: ${f.s3.region})`),c.info(`S3 sync mode: ${w}`),l&&l.fullSyncRequired?c.info("Deploy plan requests a full sync; scanning the whole output tree."):l&&m?c.info("Ignoring incremental deploy plan because deployment-profile rewrites require a full sync."):h&&c.info(`Using incremental deploy plan: ${l.changedFiles.length} changed file(s), ${l.deletedFiles.length} deleted file(s).`),c.mark("deploy");let b=new S3Client({region:f.s3.region}),k=g.outputDir===t.outputDir?await Ho(t,i,c):null,M=l?.schemaVersion===2?[...l.uploadGroups.assets,...l.uploadGroups.content,...l.uploadGroups.listings,...l.uploadGroups.sitemapLeaves,...l.uploadGroups.sitemapIndexes]:l?.changedFiles??[];if(l?.schemaVersion===2){let T=[...new Set(M)],z=[...new Set(l.changedFiles)];if(T.length!==z.length||z.some(I=>!T.includes(I)))throw new Error("Content-sync deploy-plan upload groups do not cover the exact changed-file set.")}let F=h?(await Promise.all(M.map(async T=>{try{return (await A.stat(S.join(f.outputDir,T))).isFile()?T:null}catch{if(l?.schemaVersion===2)throw new Error(`Content-sync planned upload is missing: ${T}`);return null}}))).filter(T=>T!==null):await Ts(["**/*"],{cwd:f.outputDir,onlyFiles:!0,dot:!0}),x=[],j=[],v=F.filter(T=>{let z=k?.byRelativePath.get(Nr(T));if(!z)return !0;let I=Rt(f.s3.prefix,T);return x.push(T),j.push(I),c.reject(z.kind,z.sourceUrl||T,"rewrite not completed; deploy upload blocked","deploy-guard",{file:T,key:I,outputPath:z.outputPath,manifestPath:k?.manifestPath}),!1}),P=new Set((h?v:F).map(T=>Rt(f.s3.prefix,T)));k&&(k.pendingPages>0||k.pendingTextAssets>0)&&c.info(`Deploy rewrite guard loaded ${k.pendingPages} pending page(s) and ${k.pendingTextAssets} pending text asset(s) from crawl manifest.`,{manifestPath:k.manifestPath,pendingPages:k.pendingPages,pendingTextAssets:k.pendingTextAssets,source:"deploy-guard"}),x.length>0&&c.warn(`Deploy rewrite guard blocked ${x.length} file(s) from upload because final crawl rewrite is incomplete.`,{rejected:x.length,manifestPath:k?.manifestPath,source:"deploy-guard"}),h?c.info(`Using ${v.length} eligible planned changed file(s) from deploy plan for upload${x.length>0?` (${x.length} blocked by deploy rewrite guard)`:""}.`):c.info(`Found ${F.length} file(s) in output directory "${f.outputDir}"${x.length>0?`; ${v.length} remain eligible for upload after deploy rewrite guard filtering`:""}.`),c.progress("Deploy preflight: comparing local output with remote S3 state.",{phase:"deploy",mode:w,totalFiles:v.length,scannedFiles:F.length,rejected:x.length,deploymentProfile:s.name||"",s3Bucket:f.s3.bucket,s3Prefix:f.s3.prefix||"",targetedPlan:h,deployGuardEnabled:g.outputDir===t.outputDir});let C=0,y=0,R=0,U=[],q=[],Z=[],V=[],_=[],$=new Map,ge=new Map,ve=new Map,et=new Map,kt=new Map;h||(c.info("Listing existing S3 objects to detect unchanged files..."),$=await Zo(b,f.s3.bucket,f.s3.prefix,c),c.info(`Found ${$.size} existing key(s) in S3.`));let Gr=async T=>$.has(T)?$.get(T)??null:h?Yo(b,f.s3.bucket,T,ge):null;for(let T of v){let z=S.join(f.outputDir,T),I=Rt(f.s3.prefix,T),ee=k?.contentTypeByRelativePath.get(T),_e=ee&&ee!=="application/octet-stream"?ee:Uo.lookup(T)||ee||"application/octet-stream",Zr=cn(T)?f.s3.htmlCacheControl:f.s3.assetCacheControl,O=C+y+R+1;v.length<=200||O<=5||O%10===0||O===v.length?(c.progress(`Uploading [${O}/${v.length}] ${I} (${_e})`,{file:T,key:I,index:O,totalFiles:v.length,contentType:_e,mode:w}),c.info(`Uploading [${O}/${v.length}] ${I} (${_e})`)):c.debug(`Uploading [${O}/${v.length}] ${I} (${_e})`);try{let te=await A.readFile(z),Ne=await Gr(I),Be=null,Ae=null;if(Ne){let $t=te.byteLength;if(Ne.size===$t){let tt=Ne.etag.includes("-");if(Ne.etag!==""&&!tt){let Yr=ea(te);if(Ne.etag===Yr){y++,v.length<=200||y<=5||y%25===0?(c.progress(`Skipped unchanged [${O}/${v.length}] ${I}`,{file:T,key:I,index:O,totalFiles:v.length,uploaded:C,skipped:y,failed:R,mode:w,reason:"etag-md5-match"}),c.info(`Skipped unchanged [${O}/${v.length}] ${I}`)):c.debug(`Skipped unchanged [${O}/${v.length}] ${I}`),q.push(I);continue}}Be=Lr(te);let Sn=await ta(b,f.s3.bucket,I,ve);if(Sn&&Sn===Be){y++,v.length<=200||y<=5||y%25===0?(c.progress(`Skipped unchanged [${O}/${v.length}] ${I}`,{file:T,key:I,index:O,totalFiles:v.length,uploaded:C,skipped:y,failed:R,mode:w,reason:"metadata-sha256-match"}),c.info(`Skipped unchanged [${O}/${v.length}] ${I}`)):c.debug(`Skipped unchanged [${O}/${v.length}] ${I}`),q.push(I);continue}}if(cn(T)){Ae=ln(te);let tt=await na(b,f.s3.bucket,I,et,kt);if(tt&&tt===Ae){y++,v.length<=200||y<=5||y%25===0?(c.progress(`Skipped semantically unchanged [${O}/${v.length}] ${I}`,{file:T,key:I,index:O,totalFiles:v.length,uploaded:C,skipped:y,failed:R,mode:w,reason:"normalized-html-match"}),c.info(`Skipped semantically unchanged [${O}/${v.length}] ${I}`)):c.debug(`Skipped semantically unchanged [${O}/${v.length}] ${I}`),q.push(I);continue}}}Be=Be??Lr(te),Ae=Ae??(cn(T)?ln(te):null),await X(`S3 upload ${I}`,9e5,({abortController:$t})=>new Upload({client:b,abortController:$t,params:{Bucket:f.s3.bucket,Key:I,Body:te,ContentType:_e,CacheControl:Zr,Metadata:{[qr]:Be,...Ae?{[_r]:Ae}:{}}}}).done()),C++,U.push(I),(C%25===0||C===v.length)&&(c.progress(`Uploaded ${C}/${v.length} file(s)\u2026`,{uploaded:C,skipped:y,failed:R,totalFiles:v.length,mode:w}),c.info(`Uploaded ${C}/${v.length} file(s)\u2026`));}catch(te){R++,Z.push(I),c.error(`Failed to upload ${I}: ${te.message}`,{key:I,error:String(te)});}}if(c.info(`Upload complete: ${C} uploaded, ${y} skipped unchanged, ${j.length} rejected by guard, ${R} failed.`),Z.length>0||j.length>0)throw new Error(`Deployment stopped before deletion because ${Z.length} upload(s) failed and ${j.length} upload(s) were rejected.`);if(w==="sdk-upload-delete"){let T=new Set((l?.deletedFiles??[]).map(I=>Rt(f.s3.prefix,I))),z=[...T].filter(I=>!P.has(I));if(!h&&(_=[...$.keys()].filter(ee=>!P.has(ee)).filter(ee=>!T.has(ee)),_.length>0)){c.warn(`Protected ${_.length} remote-only S3 object(s) from deletion because the crawl did not provide explicit tombstones.`,{protected:_.length,source:"deploy-delete-guard"});for(let ee of _)c.debug(` protected remote-only object: ${ee}`);}V=await Xo(b,f.s3.bucket,h?z:z.filter(I=>$.has(I)),c);}else c.info("Sync mode is sdk-upload-only \u2014 skipping stale object deletion.");a&&(await A.mkdir(S.dirname(a),{recursive:!0}),await A.writeFile(a,JSON.stringify({generatedAt:new Date().toISOString(),mode:w,summary:{totalFiles:F.length,eligibleFiles:v.length,uploaded:U.length,skipped:q.length,rejected:j.length,failed:Z.length,deleted:V.length,protected:_.length,...s.name?{profile:s.name}:{}},uploadedKeys:U,skippedKeys:q,rejectedKeys:j,failedKeys:Z,deletedKeys:V,protectedRemoteOnlyKeys:_},null,2),"utf8")),l?.schemaVersion!==2&&await $e(t),c.endMark("deploy"),await c.flush();}finally{await u().catch(()=>{});}}function ca(e){let t=e;return t.endsWith("/")?t+="index.html":S.posix.basename(t).includes(".")||(t+="/index.html"),t}function ua(e,t){let n=t.trim().replace(/^\/+|\/+$/g,"");if(!n)return null;let s=`/${n}`;return e===s||e.startsWith(`${s}/`)?e:`${s}${e.startsWith("/")?e:`/${e}`}`}function Wr(e,t){let n=new Set;for(let s of e){let r=new URL(s,"https://content-sync.invalid");if(r.origin!=="https://content-sync.invalid")continue;let i=`${r.pathname}${r.search}`,a=ca(r.pathname);n.add(i),n.add(`${a}${r.search}`);let c=ua(a,t);c&&n.add(`${c}${r.search}`);}return [...n].sort()}function ga(){let e=String(process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"").trim();return e?S.join(S.resolve(e),"content-sync-invalidation.json"):""}async function fn(e,t){if(!e)return;await A.mkdir(S.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(n,JSON.stringify({...t,updatedAt:new Date().toISOString()},null,2),"utf8"),await A.rename(n,e);}async function fa(e,t,n,s){if(!e)return null;try{let r=JSON.parse(await A.readFile(e,"utf8"));if(r.schemaVersion!==1||r.distributionId!==t||r.impactHash!==n||!Array.isArray(r.batches))throw new Error("Content-sync invalidation state does not match the deploy plan.");let i=r.batches.flatMap(a=>a.paths);return i.length!==s.length||i.some((a,c)=>a!==s[c])?null:r}catch(r){if(r.code==="ENOENT")return null;throw r}}function ma(e,t=3e3){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}async function zr(e=process.argv.slice(2)){let t=await ne(),n=vt(e),s=Le(t,n),r=s.config,i=new Me(r.logDir||"logs","invalidate.log.jsonl",r.logLevel??"info"),a=e.includes("--content-sync"),c=await at(t);if(a&&c?.schemaVersion!==2)throw new Error("Content-sync invalidation requires a valid schema-2 targeted deploy plan.");if(s.name&&i.info(`Using deployment profile: ${s.name}`),!r.cloudFront.distributionId){i.info("No CloudFront distributionId configured; skipping invalidation."),await i.flush();return}let o=c?.schemaVersion===2?c.invalidationPaths:r.cloudFront.invalidationPaths.length>0?r.cloudFront.invalidationPaths:["/*"],u=c?.schemaVersion===2?Wr(o,r.s3.prefix||""):o;if(c?.schemaVersion===2&&u.some(f=>f==="/*"))throw new Error("Content-sync cannot use a whole-distribution invalidation.");if(u.length===0){i.info("The targeted deploy plan has no CloudFront paths to invalidate."),await i.flush();return}let l=r.cloudFront.distributionId,d=new CloudFrontClient({region:"us-east-1",maxAttempts:5});if(i.mark("invalidate"),c?.schemaVersion!==2){let f=`smartcloud-static-publisher-${Date.now()}`;await X(`CloudFront invalidation for distribution ${l}`,3e5,({httpOptions:w})=>d.send(new CreateInvalidationCommand({DistributionId:l,InvalidationBatch:{CallerReference:f,Paths:{Quantity:u.length,Items:u}}}),w)),i.endMark("invalidate"),await i.flush();return}let p=ga(),g=await fa(p,l,c.impactHash,u);if(!g){let f=createHash("sha256").update(JSON.stringify(u)).digest("hex");g={schemaVersion:1,distributionId:l,impactHash:c.impactHash,updatedAt:new Date().toISOString(),batches:ma(u).map((w,m)=>({index:m,callerReference:`wpsuite-content-sync-${c.impactHash.slice(0,24)}-${f.slice(0,24)}-${m}`,paths:w,invalidationId:null,status:"pending"}))},await fn(p,g);}for(let f of g.batches){if(!f.invalidationId){let w=await X(`CloudFront targeted invalidation batch ${f.index+1}`,3e5,({httpOptions:h})=>d.send(new CreateInvalidationCommand({DistributionId:l,InvalidationBatch:{CallerReference:f.callerReference,Paths:{Quantity:f.paths.length,Items:f.paths}}}),h)),m=String(w.Invalidation?.Id||"").trim();if(!m)throw new Error("CloudFront did not return an invalidation ID.");f.invalidationId=m,f.status="created",await fn(p,g);}await waitUntilInvalidationCompleted({client:d,maxWaitTime:900,minDelay:2,maxDelay:15},{DistributionId:l,Id:f.invalidationId}),f.status="completed",await fn(p,g),i.info(`CloudFront invalidation batch ${f.index+1}/${g.batches.length} completed.`,{invalidationId:f.invalidationId,pathCount:f.paths.length});}i.endMark("invalidate"),await i.flush();}function Tt(e){let t=new URL(e);return t.hash="",t.href}function Qr(e,t){let n=new Set([...t].map(c=>Tt(c))),s=new Map,r=new Map,i=c=>{s.set(Tt(c),c);},a=c=>{if(!c)return;let o=Tt(c);s.has(o)||r.set(o,c);};for(let c of e.deleteUrls)i(c);for(let c of e.archiveFamilies)if(c.foundPosts===0)for(let o of c.pageUrls)n.has(Tt(o))||i(o);a(e.directRenderUrls[0]);for(let c of e.archiveFamilies)a(c.pageUrls[0]),a(c.pageUrls.at(-1));for(let c of e.sitemapUrls)a(c);return {expectedAvailable:[...r.values()],expectedMissing:[...s.values()]}}var Vr=["claimed","impact-planned","rendered","deployed","invalidated","verified","acknowledged"];function wn(){let e=String(process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"").trim();if(!e)throw new Error("Content-sync requires a runtime directory.");return S.resolve(e)}function qe(e,t){return Vr.indexOf(e)>=Vr.indexOf(t)}async function pe(e,t,n,s,r={}){let i={timestamp:new Date().toISOString(),eventType:t,status:t.endsWith("failed")?"failed":"success",actorSource:"content-sync",jobId:n.id||"",command:"content-sync",message:s,details:r};await A.mkdir(e,{recursive:true}),await A.appendFile(S.join(e,"audit-events.jsonl"),`${JSON.stringify(i)}
11
+ `,"utf8");}function wa(e){return We({postTypes:e.postTypes??[],listingPaths:e.listingPaths??[],includeSubsites:e.includeSubsites,includePostTypeArchives:e.includePostTypeArchives,includeTaxonomyArchives:e.includeTaxonomyArchives,includeAuthorArchives:e.includeAuthorArchives,includeDateArchives:e.includeDateArchives,includePostsPage:e.includePostsPage,includeSitemapChain:e.includeSitemapChain})}function ya(e,t){let n=(e.scheduler?.rules??[]).find(s=>s.command==="content-sync"&&s.id===t);if(!n)throw new Error(`Content-sync scheduler rule not found: ${t}`);if(n.enabled===false)throw new Error(`Content-sync scheduler rule is disabled: ${t}`);return n}async function yn(e,t){if(e.subscriptionType!=="PROFESSIONAL"&&e.subscriptionType!=="AGENCY")throw new Error("Content-sync requires an active Professional or Agency subscription.");let n=wa(t),s=Le(e,t.deploymentProfile),r=s.name||"",i=vn(e.sourceOrigin,String(t.id||""),n),a=Cn({sourceOrigin:e.sourceOrigin,targetOrigin:s.config.targetOrigin,deploymentProfile:r,s3Bucket:s.config.s3.bucket,s3Prefix:s.config.s3.prefix,cloudFrontDistributionId:s.config.cloudFront.distributionId,urlRewriteMode:s.config.urlRewriteMode,extraReplacements:s.profile?.extraReplacements??{}}),c=Rn({siteId:e.wpsuite?.siteSettings?.siteId,accountId:e.wpsuite?.siteSettings?.accountId,sourceOrigin:e.sourceOrigin,ruleId:String(t.id||""),targetFingerprint:a}),o=`content-sync:${String(t.id||"")}:${oe({scopeFingerprint:i,targetFingerprint:a}).slice(0,32)}`,u=new rt({sourceOrigin:e.sourceOrigin,runtimeToken:String(e.wpsuite?.runtimeToken||""),ignoreHttpsErrors:e.ignoreHttpsErrors}),l=await u.releaseFingerprint(n.includeSubsites),d=bn({wordpressFingerprint:l,targetFingerprint:a,sourceOrigin:e.sourceOrigin,sitemapPaths:e.sitemapPaths,blockedPathPrefixes:e.blockedPathPrefixes,assetPathPrefixes:e.assetPathPrefixes,noJavaScriptRenderPathPrefixes:e.noJavaScriptRenderPathPrefixes,urlRewriteMode:e.urlRewriteMode});return {rule:t,scope:n,deployment:s,deploymentProfile:r,scopeFingerprint:i,targetFingerprint:a,consumerId:c,coalesceKey:o,client:u,releaseFingerprint:d}}async function Sa(e){let t=wn(),n=st(t),s=await ne(),r=(s.scheduler?.rules??[]).filter(u=>u.command==="content-sync"&&u.enabled!==false);if(r.length===0)return 0;let i=await Ot(n),a=await it(n),c=await Dt(n),o=0;for(let u of r){let l=await yn(s,u),d=c.entries[l.coalesceKey];if(!d||d.releaseJobId!==e||d.scopeFingerprint!==l.scopeFingerprint||d.targetFingerprint!==l.targetFingerprint||d.releaseFingerprint!==l.releaseFingerprint)throw new Error(`The normal release has no matching pre-crawl content-sync cutoff for rule ${String(u.id||"")}.`);let p=oe({releaseJobId:e,releaseFingerprint:l.releaseFingerprint,scopeFingerprint:l.scopeFingerprint,targetFingerprint:l.targetFingerprint,sequence:d.sequence}),g=await l.client.establishBaseline({consumerId:l.consumerId,scopeFingerprint:l.scopeFingerprint,baselineId:p,postTypes:l.scope.postTypes,includeSubsites:l.scope.includeSubsites,sequence:d.sequence}),f={schemaVersion:1,ruleId:String(u.id||""),consumerId:l.consumerId,coalesceKey:l.coalesceKey,scopeFingerprint:l.scopeFingerprint,targetFingerprint:l.targetFingerprint,releaseFingerprint:l.releaseFingerprint,baselineId:p,deploymentProfile:l.deploymentProfile,committedSequence:g.committedSequence,releaseJobId:e,verifiedAt:new Date().toISOString()};i.entries[l.coalesceKey]=f;let w=a.rules[l.coalesceKey];a.rules[l.coalesceKey]={ruleId:String(u.id||""),consumerId:l.consumerId,coalesceKey:l.coalesceKey,committedSequence:g.committedSequence,observedHeadSequence:g.headSequence,lag:Math.max(0,g.headSequence-g.committedSequence),lastSuccessfulJobId:w?.lastSuccessfulJobId||e,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:g.headSequence>g.committedSequence,retryAttempt:0,nextRetryAt:null,lastError:null,baselineStatus:"ready",baselineReason:null};let m=await Dn(n,l.coalesceKey);await pe(t,"content-sync-baseline-established",{id:e},"A normal release established a verified content-sync baseline.",{ruleId:u.id,consumerId:l.consumerId,committedSequence:g.committedSequence,supersededCurrent:m}),o++;}return await kn(n,i),await ot(n,a),await A.rm(n.releaseCutoff,{force:true}),o}async function Pa(e){let t=wn(),n=st(t),s=await ne(),r=(s.scheduler?.rules??[]).filter(c=>c.command==="content-sync"&&c.enabled!==false);if(r.length===0)return 0;let i=await Dt(n),a=0;for(let c of r){let o=await yn(s,c),u=Object.values(i.entries).find(p=>p.releaseJobId===e&&p.ruleId===String(c.id||""));if(u){if(u.coalesceKey===o.coalesceKey&&u.scopeFingerprint===o.scopeFingerprint&&u.targetFingerprint===o.targetFingerprint&&u.releaseFingerprint===o.releaseFingerprint){a++;continue}throw new Error(`The normal release scope changed after its journal cutoff was captured for rule ${String(c.id||"")}. Start a new normal publish instead of resuming this release.`)}let l=await o.client.unboundHead(o.scope.postTypes,o.scope.includeSubsites),d={schemaVersion:1,releaseJobId:e,ruleId:String(c.id||""),coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,releaseFingerprint:o.releaseFingerprint,sequence:l.headSequence,capturedAt:new Date().toISOString()};i.entries[o.coalesceKey]=d,await pe(t,"content-sync-release-cutoff-captured",{id:e},"A normal release captured its pre-crawl content-sync journal cutoff.",{ruleId:c.id,consumerId:o.consumerId,sequence:l.headSequence}),a++;}return await Tn(n,i),a}async function ba(e,t){let n=JSON.parse(await A.readFile(S.join(e,"current-run.json"),"utf8"));if(n.id!==t||n.command!=="content-sync"||!String(n.ruleId||"").trim())throw new Error("The active queue job is not the requested content-sync job.");return n}async function hn(e,t,n=0){let s=e.protocol==="https:"?An:ss,r=e.protocol==="https:"?new An.Agent({rejectUnauthorized:!t}):void 0;return new Promise((i,a)=>{let c=s.get(e,{agent:r,timeout:3e4,headers:{"user-agent":"WP-Suite-Content-Sync/1"}},o=>{let u=o.statusCode??500,l=o.headers.location;if(u>=300&&u<400&&l&&n<5){o.resume(),hn(new URL(l,e),t,n+1).then(i,a);return}let d=[],p=0;o.on("data",g=>{p+=g.byteLength,p<=1048576&&d.push(g);}),o.on("error",a),o.on("end",()=>i({status:u,body:Buffer.concat(d).toString("utf8")}));});c.on("timeout",()=>c.destroy(new Error(`Verification timed out: ${e}`))),c.on("error",a);})}async function va(e,t,n,s){let r=t.deployment.config.targetOrigin;if(!/^https?:\/\//i.test(r))throw new Error("Content-sync verification requires an absolute HTTP(S) target origin.");let i=JSON.parse(await A.readFile(s,"utf8")),a=new Set;for(let[o,u]of Object.entries(i.pages??{}))a.add(o),typeof u.url=="string"&&a.add(u.url);let c=Qr(n,a);for(let o of c.expectedAvailable){let u=new URL(o),l=new URL(`${u.pathname}${u.search}`,r),d=await hn(l,e.ignoreHttpsErrors);if(d.status<200||d.status>=400)throw new Error(`Content-sync verification failed (${d.status}): ${l}`)}for(let o of c.expectedMissing.slice(0,10)){let u=new URL(o),l=new URL(`${u.pathname}${u.search}`,r),d=await hn(l,e.ignoreHttpsErrors);if(d.status>=200&&d.status<300)throw new Error(`Deleted content is still publicly available: ${l}`)}}async function Ca(e){let t=await A.readFile(e.candidateManifest,"utf8");JSON.parse(t);let n=`${e.trustedManifest}.${process.pid}.tmp`;await A.writeFile(n,t,"utf8"),await A.rename(n,e.trustedManifest);}async function Ra(e,t){try{let n=JSON.parse(await A.readFile(e.candidateManifest,"utf8"));if([...Object.values(n.pages??{}),...Object.values(n.assets??{})].some(r=>r?.lastSeenRunId===t))return "resumed"}catch(n){if(n.code!=="ENOENT")throw new Error(`The content-sync candidate manifest is invalid: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return await A.copyFile(e.trustedManifest,e.candidateManifest).catch(n=>{throw new Error(`A trusted crawl manifest is required before content-sync: ${n instanceof Error?n.message:String(n)}`,{cause:n})}),"initialized"}async function xe(e,t,n,s,r={},i=0,a=async()=>{}){t.phase=n,await $n(e,t),await Fn(e,{schemaVersion:1,jobId:t.jobId,phase:n,completedItems:s,totalItems:s,attempt:i,updatedAt:new Date().toISOString(),details:r}),await pe(S.dirname(e.state),"content-sync-checkpoint",{id:t.jobId},`Content-sync checkpoint completed: ${n}.`,{phase:n,completedItems:s,totalItems:s,attempt:i,...r}),await a(n,t);}async function Ia(e,t={}){let n={loadConfig:ne,resolveRuleContext:yn,runCrawl:Or,runDeploy:Br,runInvalidate:zr,verifyDeployment:va,promoteCandidateManifest:Ca,clearDeployPlan:$e,afterCheckpoint:async()=>{},...t},s=wn(),r=st(s),i=await ba(s,e),a=await n.loadConfig(),c=ya(a,String(i.ruleId)),o=await n.resolveRuleContext(a,c);if(i.coalesceKey&&i.coalesceKey!==o.coalesceKey)throw new Error("Queued content-sync demand no longer matches the active rule scope.");let l=(await Ot(r)).entries[o.coalesceKey];if(!l||l.scopeFingerprint!==o.scopeFingerprint||l.targetFingerprint!==o.targetFingerprint||l.releaseFingerprint!==o.releaseFingerprint)throw await pe(s,"content-sync-baseline-rejected",i,"Content-sync requires a new verified full or incremental release baseline.",{ruleId:c.id,reason:l?"mismatch":"missing"}),new Error("Content-sync baseline is missing or stale. Run a successful normal publish first.");let d=await jt(r),p=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites});if(d&&d.jobId!==i.id)throw new Error("Another immutable content-sync range is still active.");if(d||(d={schemaVersion:1,jobId:i.id,ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,baselineId:l.baselineId,fromSequence:p.committedSequence,toSequence:p.headSequence,phase:"claimed",impactHash:null,startedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},await xe(r,d,"claimed",0,{fromSequence:d.fromSequence,toSequence:d.toSequence},0,n.afterCheckpoint),await pe(s,"content-sync-range-claimed",i,"Content-sync claimed a closed journal range.",{fromSequence:d.fromSequence,toSequence:d.toSequence})),d.fromSequence===d.toSequence){let h=await it(r);h.rules[o.coalesceKey]={ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,committedSequence:d.toSequence,observedHeadSequence:p.headSequence,lag:Math.max(0,p.headSequence-d.toSequence),lastSuccessfulJobId:i.id,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:false,retryAttempt:0,nextRetryAt:null,lastError:null},await ot(r,h),await Ut(r);return}let g=await En(r);if(!qe(d.phase,"impact-planned")){let h=await o.client.events({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites,afterSequence:d.fromSequence,throughSequence:d.toSequence}),b=Ft({events:h,scope:o.scope,sourceOrigin:a.sourceOrigin}),k=await o.client.resolveImpactFamilies(b,o.scope.includeSubsites);g=xn({jobId:i.id,ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,baselineId:l.baselineId,sourceOrigin:a.sourceOrigin,scope:o.scope,fromSequence:d.fromSequence,toSequence:d.toSequence,events:h,resolvedArchiveFamilies:k,sitemapUrls:a.sitemapPaths}),await Mn(r,g),d.impactHash=g.impactHash,await xe(r,d,"impact-planned",h.length,{eventCount:h.length,foldedCount:g.foldedCount,impactHash:g.impactHash},0,n.afterCheckpoint),await pe(s,"content-sync-impact-planned",i,"Content-sync persisted an immutable impact plan.",{impactHash:g.impactHash,eventCount:h.length});}if(!g||g.jobId!==i.id||d.impactHash!==g.impactHash)throw new Error("The immutable content-sync impact plan is missing or mismatched.");if(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH=r.candidateManifest,!qe(d.phase,"rendered")){let h=await Ra(r,i.id);await pe(s,h==="resumed"?"content-sync-render-resumed":"content-sync-render-initialized",i,h==="resumed"?"Content-sync resumed its candidate crawl manifest.":"Content-sync initialized a candidate crawl manifest.",{impactHash:g.impactHash}),await n.runCrawl(["--content-sync-plan",r.impact]),await xe(r,d,"rendered",g.directRenderUrls.length+g.archiveFamilyUrls.length,{impactHash:g.impactHash},i.attempt??0,n.afterCheckpoint);}let f=o.deploymentProfile?["--profile",o.deploymentProfile]:[];if(qe(d.phase,"deployed")||(await n.runDeploy([...f,"--content-sync"]),await xe(r,d,"deployed",1,{impactHash:g.impactHash},0,n.afterCheckpoint),await pe(s,"content-sync-deployed",i,"Content-sync targeted deployment completed.",{impactHash:g.impactHash})),qe(d.phase,"invalidated")?qe(d.phase,"verified")||await n.runInvalidate([...f,"--content-sync"]):(await n.runInvalidate([...f,"--content-sync"]),await xe(r,d,"invalidated",1,{impactHash:g.impactHash},0,n.afterCheckpoint)),qe(d.phase,"verified")||(await n.verifyDeployment(a,o,g,r.candidateManifest),await n.promoteCandidateManifest(r),await xe(r,d,"verified",1,{impactHash:g.impactHash},0,n.afterCheckpoint)),p=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites}),p.committedSequence===d.fromSequence)await o.client.acknowledge({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,expectedSequence:d.fromSequence,sequence:d.toSequence,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites});else if(p.committedSequence!==d.toSequence)throw new Error("Content-sync acknowledgement cursor is in an unexpected state.");await xe(r,d,"acknowledged",1,{sequence:d.toSequence},0,n.afterCheckpoint),await pe(s,"content-sync-cursor-acknowledged",i,"Content-sync committed its journal cursor after verification.",{sequence:d.toSequence});let w=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites}),m=await it(r);m.rules[o.coalesceKey]={ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,committedSequence:d.toSequence,observedHeadSequence:w.headSequence,lag:Math.max(0,w.headSequence-d.toSequence),lastSuccessfulJobId:i.id,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:w.headSequence>d.toSequence,retryAttempt:0,nextRetryAt:null,lastError:null},await ot(r,m),await n.clearDeployPlan(a),await A.rm(S.join(s,"content-sync-invalidation.json"),{force:true}),await A.rm(r.candidateManifest,{force:true}),await Ut(r);}async function Kr(e=process.argv.slice(2)){let n=e.indexOf("--capture-baseline-cutoffs");if(n>=0){let a=String(e[n+1]||"").trim();if(!a)throw new Error("--capture-baseline-cutoffs requires a release job ID.");await Pa(a);return}let s=e.indexOf("--establish-baselines");if(s>=0){let a=String(e[s+1]||"").trim();if(!a)throw new Error("--establish-baselines requires a release job ID.");await Sa(a);return}let r=e.indexOf("--job-id"),i=r>=0?String(e[r+1]||"").trim():"";if(!i)throw new Error("Content-sync requires --job-id.");await Ia(i);}Kr().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1);});
@@ -1,3 +1,3 @@
1
- import {pathToFileURL}from'url';import P from'fs/promises';import {existsSync,createReadStream,createWriteStream}from'fs';import m from'path';import {spawn}from'child_process';import {randomUUID,createHash}from'crypto';import Je from'http';import me from'https';import {pipeline}from'stream/promises';import {createGzip}from'zlib';function le(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function N(e){return Array.isArray(e)?e.map(N):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,N(n)])):e}function Ee(e){return JSON.stringify(N(e))}function J(e){return createHash("sha256").update(Ee(e)).digest("hex")}function de(e){return J({schemaVersion:1,wordpressFingerprint:e.wordpressFingerprint,targetFingerprint:e.targetFingerprint,sourceOrigin:e.sourceOrigin,sitemapPaths:[...e.sitemapPaths].sort(),blockedPathPrefixes:[...e.blockedPathPrefixes].sort(),assetPathPrefixes:[...e.assetPathPrefixes].sort(),noJavaScriptRenderPathPrefixes:[...e.noJavaScriptRenderPathPrefixes].sort(),urlRewriteMode:e.urlRewriteMode})}function Fe(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Unsupported source origin protocol: ${t.protocol}`);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,""),t.toString().replace(/\/$/,"")}function M(e){let t=le((e.postTypes??[]).map(r=>String(r).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let n=le((e.listingPaths??[]).map(r=>{let i=String(r).trim();if(!i)return "";let a=new URL(i,"https://content-sync.invalid/");if(a.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(i))throw new Error("Content-sync listing routes must be same-site paths.");let s=`/${a.pathname.replace(/^\/+|\/+$/g,"")}`;return s==="/"?"/":`${s}/`}));return {postTypes:t,listingPaths:n,includeSubsites:e.includeSubsites===true,includePostTypeArchives:e.includePostTypeArchives!==false,includeTaxonomyArchives:e.includeTaxonomyArchives!==false,includeAuthorArchives:e.includeAuthorArchives===true,includeDateArchives:e.includeDateArchives===true,includePostsPage:e.includePostsPage!==false,includeSitemapChain:e.includeSitemapChain!==false}}function _(e,t,n){return J({schemaVersion:1,sourceOrigin:Fe(e),ruleId:t.trim(),scope:M(n)})}function K(e){return J({schemaVersion:1,...e})}function pe(e){return e.replace(/((?:x-static-publisher-token|authorization|proxy-authorization|x-api-key|aws-access-key-id|aws-secret-access-key|aws-session-token)\s*:\s*)[^\r\n]+/gi,"$1[REDACTED]").replace(/\b(Basic|Bearer)\s+[^\s]+/gi,"$1 [REDACTED]").replace(/([?&](?:token|access_token|refresh_token|api_key|key|nonce)=)[^&\s]+/gi,"$1[REDACTED]").replace(/((?:"|')?(?:runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken)(?:"|')?\s*[:=]\s*(?:"|'))[^"']+/gi,"$1[REDACTED]")}var ge=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";ge?m.join(ge,"current-progress.json"):"";Promise.resolve();var Le="wp-json/smartcloud-static-publisher/v1/content-sync/",Oe=25*1024*1024,k=class extends Error{status;code;constructor(t,n,r){super(r),this.name="ContentSyncApiError",this.status=t,this.code=n;}},U=class{options;constructor(t){if(!t.runtimeToken.trim())throw new Error("Content-sync requires a WordPress runtime token.");this.options={...t,timeoutMs:t.timeoutMs??6e4};}endpoint(t){let n=this.options.sourceOrigin.replace(/\/+$/,"")+"/";return new URL(`${Le}${t}`,n)}async post(t,n){let r=this.endpoint(t),i=Buffer.from(JSON.stringify(n),"utf8"),a=r.protocol==="https:"?me:Je,s=r.protocol==="https:"?new me.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((o,u)=>{let c=a.request(r,{method:"POST",agent:s,headers:{"content-type":"application/json","content-length":String(i.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},d=>{let g=[],p=0;d.on("data",h=>{if(p+=h.byteLength,p>Oe){d.destroy(new Error("Content-sync API response exceeded the size limit."));return}g.push(h);}),d.on("error",u),d.on("end",()=>{let h=Buffer.concat(g).toString("utf8"),y;try{y=h?JSON.parse(h):{};}catch{u(new k(d.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let l=d.statusCode??500;if(l<200||l>=300){u(new k(l,String(y.code??"request-failed"),String(y.message??`Content-sync API request failed (${l}).`)));return}o(y);});});c.on("timeout",()=>c.destroy(new Error(`Content-sync API request timed out: ${t}`))),c.on("error",u),c.end(i);})}async head(t){return this.post("head",t)}async unboundHead(t,n){return this.post("head",{postTypes:t,includeSubsites:n})}async events(t){let n=[],r=t.afterSequence,i=new Set(t.postTypes);for(;r<t.throughSequence;){let a=await this.post("events",{...t,afterSequence:r,limit:250});if(a.fromSequence!==r||a.throughSequence!==t.throughSequence||a.nextSequence<r||a.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(a.items))throw new Error("Content-sync API returned a malformed event page.");let s=r;for(let o of a.items){if(!Number.isSafeInteger(o.sequence)||o.sequence<=s||o.sequence>t.throughSequence||!Number.isSafeInteger(o.postId)||o.postId<=0||!Number.isSafeInteger(o.blogId)||o.blogId<=0||!i.has(o.postType)||typeof o.operation!="string"||!o.operation)throw new Error("Content-sync API returned an invalid or out-of-scope journal event.");s=o.sequence;}if(a.items.length>0&&a.nextSequence!==s)throw new Error("Content-sync API event cursor does not match the final returned event.");if(n.push(...a.items),!a.hasMore)break;if(a.nextSequence===r)throw new Error("Content-sync API event pagination did not advance.");r=a.nextSequence;}if(t.throughSequence>t.afterSequence&&n.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return n}async resolveImpactFamilies(t,n){let r=await this.post("impact",{families:t,includeSubsites:n});return Array.isArray(r.families)?r.families:[]}async releaseFingerprint(t=false){let n=await this.post("fingerprint",{includeSubsites:t}),r=String(n.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("WordPress returned an invalid release fingerprint.");return r}async establishBaseline(t){return this.post("baseline",t)}async acknowledge(t){return this.post("ack",t)}};function Be(e){return typeof e.subscriptionType=="string"&&e.subscriptionType.trim()!==""}function Me(e,t){return {...e,...t??{}}}function Ue(e,t){return {...e,...t??{},invalidationPaths:[...(t?.invalidationPaths??e.invalidationPaths)||[]]}}function z(e,t){let n=String(t??e.deploymentTargetOverride??"").trim();if(!Be(e)){if(n)throw new Error(`Deployment target "${n}" requires an active WPSuite subscription and remote publisher config.`);return {name:null,profile:null,config:e}}let r=String(n||e.defaultDeploymentProfile||"").trim();if(!r)return {name:null,profile:null,config:e};let i=e.deploymentProfiles?.[r];if(!i)throw new Error(`Unknown deployment profile "${r}". Check the linked WPSuite publisher configuration.`);return {name:r,profile:i,config:{...e,targetOrigin:i.targetOrigin??e.targetOrigin,s3:Me(e.s3,i.s3),cloudFront:Ue(e.cloudFront,i.cloudFront)}}}function fe(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function Ne(e){let t=String(e??"").trim();if(!t)return "";let n=t;if(/^https?:\/\//i.test(n))try{n=new URL(n).pathname;}catch{return ""}if(n=n.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!n)return "";let r=n.endsWith("/"),i=n.replace(/^\/+/,"").split("/").map(s=>s.replace(/[^A-Za-z0-9._-]/g,"")).filter(s=>s.length>0&&s!=="."&&s!=="..");if(i.length===0)return "";let a=`/${i.join("/")}`;return r&&m.extname(a)===""&&(a+="/"),a==="/"?"":a}function H(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function _e(e){if(!e||typeof e!="object")return {};let t={};for(let[n,r]of Object.entries(e)){let i=n.trim();if(!i||!r||typeof r!="object")continue;let a=r,s={};if(typeof a.targetOrigin=="string"){let u=fe(a.targetOrigin);u&&(s.targetOrigin=u);}let o=H(a.extraReplacements);if(Object.keys(o).length>0&&(s.extraReplacements=o),a.s3&&typeof a.s3=="object"){let u={},c=a.s3;typeof c.bucket=="string"&&(u.bucket=c.bucket.trim()),typeof c.prefix=="string"&&(u.prefix=c.prefix.trim()),typeof c.region=="string"&&(u.region=c.region.trim()),typeof c.htmlCacheControl=="string"&&(u.htmlCacheControl=c.htmlCacheControl.trim()),typeof c.assetCacheControl=="string"&&(u.assetCacheControl=c.assetCacheControl.trim()),Object.keys(u).length>0&&(s.s3=u);}if(a.cloudFront&&typeof a.cloudFront=="object"){let u={},c=a.cloudFront;typeof c.distributionId=="string"&&(u.distributionId=c.distributionId.trim()),Array.isArray(c.invalidationPaths)&&(u.invalidationPaths=c.invalidationPaths.map(d=>String(d??"").trim()).filter(d=>d.length>0)),Object.keys(u).length>0&&(s.cloudFront=u);}t[i]=s;}return t}function V(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function Ke(e,t){if(!e||typeof e!="object")return null;let n=e,r=n.command;if(r!=="publish"&&r!=="crawl"&&r!=="deploy"&&r!=="invalidate"&&r!=="retry-timeouts"&&r!=="url"&&r!=="content-sync")return null;let i=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(i)||i<1)return null;let a=String(n.id??`${r}-${t+1}`).trim();if(!a)return null;let s=String(n.deploymentProfile??"").trim(),o=String(n.url??"").trim(),u=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(d=>String(d??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],c=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(d=>String(d??"").trim()).filter(Boolean))]:[];return r==="content-sync"&&u.length===0?null:{id:a,enabled:n.enabled!==false,command:r,intervalMinutes:i,...r==="publish"||r==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(r==="publish"||r==="deploy"||r==="invalidate"||r==="content-sync")&&s?{deploymentProfile:s}:{},...o?{url:o}:{},...u.length>0?{postTypes:u}:{},...c.length>0?{listingPaths:c}:{},...typeof n.includeSubsites=="boolean"?{includeSubsites:n.includeSubsites}:{},...typeof n.includePostTypeArchives=="boolean"?{includePostTypeArchives:n.includePostTypeArchives}:{},...typeof n.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:n.includeTaxonomyArchives}:{},...typeof n.includeAuthorArchives=="boolean"?{includeAuthorArchives:n.includeAuthorArchives}:{},...typeof n.includeDateArchives=="boolean"?{includeDateArchives:n.includeDateArchives}:{},...typeof n.includePostsPage=="boolean"?{includePostsPage:n.includePostsPage}:{},...typeof n.includeSitemapChain=="boolean"?{includeSitemapChain:n.includeSitemapChain}:{}}}function ye(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((r,i)=>Ke(r,i)).filter(r=>!!r):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function ze(e){if(!e||typeof e!="object")return;let t=e,n={};for(let i of ["accountId","siteId"]){let a=t[i];typeof a=="string"&&a.trim()!==""&&(n[i]=a.trim());}let r=Number(t.lastUpdate??0);return Number.isFinite(r)&&r>0&&(n.lastUpdate=Math.floor(r)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function Y(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),r=String(t.siteId??"").trim(),i=t.subscriber===true,a=ze(t.siteSettings),s={...a??{},...n?{accountId:a?.accountId??n}:{},...r?{siteId:a?.siteId??r}:{},...a?.subscriber===true||i?{subscriber:true}:{}},o={},u=String(t.apiBase??"").trim();u&&(o.apiBase=u);let c=String(t.runtimeToken??t.nonce??"").trim();c&&(o.runtimeToken=c);let d=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();d&&(o.virtualAssetBaseUrl=d),Object.keys(s).length>0&&(o.siteSettings=s);let g=V(t.subscriptionType);return g&&(o.subscriptionType=g),o}function He(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function be(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function Ge(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[r,i]of new Headers(t.headers).entries())n.set(r,i);return n}async function Se(e,t,n=5){let r=new URL(be(e)),i=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),a=r.protocol==="http:"?Je:me,s=Ge(e,t);return await new Promise((o,u)=>{let c=a.request(r,{method:i,headers:Object.fromEntries(s.entries()),...r.protocol==="https:"?{rejectUnauthorized:false}:{}},d=>{let g=[];d.on("data",p=>{g.push(Buffer.isBuffer(p)?p:Buffer.from(p));}),d.on("error",u),d.on("end",()=>{let p=d.statusCode??0,h=d.headers.location;if(n>0&&h&&[301,302,303,307,308].includes(p)){o(Se(new URL(h,r),{method:p===303?"GET":i},n-1));return}let y=new Headers;for(let[l,b]of Object.entries(d.headers))Array.isArray(b)?y.set(l,b.join(", ")):typeof b=="string"&&y.set(l,b);o(new Response(Buffer.concat(g),{status:p,statusText:d.statusMessage??"",headers:y}));});});c.on("error",u),c.end();})}function Ve(e){let t=Y(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},r=String(n.accountId??"").trim(),i=String(n.siteId??"").trim(),a=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...a?{virtualAssetBaseUrl:a}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!r||!i||!a)return false;He(e.sourceOrigin);let s=globalThis,u={...s.WpSuite??{},siteSettings:n,uploadUrl:a};return t.apiBase&&(u.apiBase=t.apiBase),s.WpSuite=u,true}async function Ye(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!Ve(e)){let i=e.wpsuite?.siteSettings,a=[String(i?.accountId??"").trim()?"":"accountId",String(i?.siteId??"").trim()?"":"siteId",t?"":"virtualAssetBaseUrl"].filter(Boolean);return {remote:null,diagnostic:{status:"invalid-runtime",virtualAssetBaseUrl:t,subscriptionType:null,error:`Missing WP Suite runtime field(s): ${a.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,r=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(u,c)=>{let d=be(u);if(d.startsWith(t)){let g=(()=>{try{return new URL(d).pathname}catch{return d}})();try{let p=e.ignoreHttpsErrors&&d.startsWith("https://")?await Se(u,c):await n(u,c);return r.push({path:g,status:p.status,ok:p.ok,error:null}),p}catch(p){throw r.push({path:g,status:null,ok:!1,error:p instanceof Error?p.message:String(p)}),p}}return n(u,c)}));let{getConfig:i}=await import('@smart-cloud/wpsuite-core'),a=await i("publisher"),s=a&&typeof a=="object"?a:null,o=V(s?.subscriptionType);return {remote:s,diagnostic:{status:s?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:o??null,error:s?null:"WP Suite publisher config loader returned no configuration.",requests:r}}}catch(i){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:i instanceof Error?i.message:String(i),requests:r}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function Ze(e,t){let n=_e(t?.deploymentProfiles),r=String(t?.defaultDeploymentProfile??"").trim(),i=n[r]?r:"",a=V(t?.subscriptionType),s=Y(e.wpsuite);return {...e,scheduler:ye(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:i,...a?{subscriptionType:a}:{},wpsuite:{...s,...s.siteSettings||a?{siteSettings:{...s.siteSettings??{},...s.siteSettings?.subscriber===true||a==="PROFESSIONAL"||a==="AGENCY"?{subscriber:true}:{}}}:{},...a?{subscriptionType:a}:{}}}}function G(e,t){let r=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!r)return t;let i=r.split("/").map(a=>a.trim()).filter(a=>a.length>0&&a!=="."&&a!=="..");return i.length>0?i.join("/"):t}function Xe(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?m.resolve(e):""}function he(e,t,n){let r=String(t||"").trim();return r&&m.isAbsolute(r)?m.resolve(r):m.resolve(e,G(r,n))}async function Z(e,t={}){let n=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",r=await P.readFile(n,"utf8"),i=JSON.parse(r);i.sourceOrigin=i.sourceOrigin.replace(/\/$/,""),i.targetOrigin=fe(i.targetOrigin),i.ignoreHttpsErrors??=false,i.outputDir=String(i.outputDir||"export").trim()||"export",i.urlRewriteMode||=i.targetOrigin==="."?"relative":"absolute",i.noJavaScriptRenderPathPrefixes||=[],i.seedPaths||=[],i.generated404RequestPath=Ne(i.generated404RequestPath),i.sitemapPaths||=["/sitemap_index.xml","/sitemap.xml"],i.allowedAssetHosts||=[],i.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],i.blockedPathPrefixes||=[],i.blockedSearchFragments||=[],i.concurrency||=1,i.maxPages||=0,i.extraReplacements=H(i.extraReplacements),i.postCrawlCopyMap=H(i.postCrawlCopyMap),i.logDir=String(i.logDir||"logs").trim()||"logs",i.verbose??=false,i.logLevel||=i.verbose?"debug":"info",i.s3SyncMode||="sdk-upload-delete",i.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},i.readiness.timeoutMs??=1500,i.readiness.fallbackWaitMs??=1500,i.viewport||={width:1440,height:1200},i.navigationTimeoutMs||=3e4,i.assetDownloadConcurrency=Number(i.assetDownloadConcurrency)>0?Number(i.assetDownloadConcurrency):i.concurrency,i.rewriteConcurrency=Number(i.rewriteConcurrency)>0?Number(i.rewriteConcurrency):i.assetDownloadConcurrency,i.wpsuite=Y(i.wpsuite),i.scheduler=ye(void 0),i.deploymentProfiles={},i.defaultDeploymentProfile="",i.deploymentTargetOverride=String(i.deploymentTargetOverride??"").trim();let a=await Ye(i);t.onRemotePublisherConfigDiagnostic?.(a.diagnostic);let s=Ze(i,a.remote),o=Xe(),u=o?m.resolve(o,".."):"";return u?(s.outputDir=he(u,s.outputDir,"export"),s.logDir=he(u,s.logDir,"logs")):(m.isAbsolute(s.outputDir)||(s.outputDir=G(s.outputDir,"export")),m.isAbsolute(s.logDir)||(s.logDir=G(s.logDir,"logs"))),s}function Ce(e){let t=String(e.command??"").trim();return (t==="publish"||t==="crawl")&&e.crawlMode==="incremental"||t==="content-sync"}var X=new Map;async function we(e){let t=m.resolve(e),n=X.get(t);if(n!==void 0)return n;try{let r=JSON.parse(await P.readFile(t,"utf8")),i=String(r.version??"").trim();return X.set(t,i),i}catch{return X.set(t,""),""}}var B=class extends Error{request;step;constructor(t,n){super(`Stop requested during ${n}.`),this.name="StopRequestedError",this.request=t,this.step=n;}},st="queue-mutation.lock",ot=5e3,at=3e4;function ut(e){let t=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",n=process.env.STATIC_PUBLISHER_EXPORTER_DIR||process.cwd(),r=process.env.PUBLISHER_CONFIG||"",i=1;for(let o=0;o<e.length;o++){let u=e[o];u==="--runtime-dir"?t=e[++o]||"":u.startsWith("--runtime-dir=")?t=u.slice(14):u==="--exporter-dir"?n=e[++o]||n:u.startsWith("--exporter-dir=")?n=u.slice(15):u==="--config"?r=e[++o]||"":u.startsWith("--config=")?r=u.slice(9):u==="--max-jobs"?i=Number.parseInt(e[++o]||"1",10):u.startsWith("--max-jobs=")&&(i=Number.parseInt(u.slice(11),10));}if(!t)throw new Error("Missing runtime dir. Use --runtime-dir or STATIC_PUBLISHER_RUNTIME_DIR.");let a=m.resolve(t),s=r?m.resolve(r):m.join(a,"config.json");return {runtimeDir:a,exporterDir:m.resolve(n),configPath:s,maxJobs:Number.isFinite(i)&&i>0?i:1}}async function v(e,t){try{let n=await P.readFile(e,"utf8");return JSON.parse(n)}catch(n){if((n&&typeof n=="object"&&"code"in n?String(n.code||""):"")!=="ENOENT"){let i=n instanceof Error?n.message:String(n);console.warn(`[queue-runner] failed to read JSON ${e}: ${i}`);}return t}}async function w(e,t){await P.mkdir(m.dirname(e),{recursive:true}),await P.writeFile(e,JSON.stringify(t,null,2),"utf8");}function Ae(e){return m.join(e,st)}async function ct(e){await new Promise(t=>setTimeout(t,e));}async function lt(e){let t=Ae(e),n=Date.now()+ot;for(;;)try{await P.mkdir(m.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()},null,2),{encoding:"utf8",flag:"wx"});return}catch(r){if((r&&typeof r=="object"&&"code"in r?String(r.code||""):"")!=="EEXIST")throw r;let a=await P.stat(t).catch(()=>null);if(a&&Date.now()-a.mtimeMs>at){await P.unlink(t).catch(()=>{});continue}if(Date.now()>=n)throw new Error("Timed out acquiring queue mutation lock.",{cause:r});await ct(50);}}async function dt(e){await P.unlink(Ae(e)).catch(()=>{});}async function E(e,t){await lt(e);try{return await t()}finally{await dt(e);}}function Ie(e){return m.join(e,"queue-runner-heartbeat.json")}function ae(e){return m.join(e,"current-progress.json")}function ee(e){return m.join(e,"scheduler-state.json")}function gt(e,t){let r=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!r)return t;let i=r.split("/").map(a=>a.trim()).filter(a=>a.length>0&&a!=="."&&a!=="..");return i.length>0?i.join("/"):t}async function Re(e){let t=await v(e.configPath||"",null),n=m.resolve(e.runtimeDir,".."),i=(typeof t?.logDir=="string"?t.logDir:"").trim();return i&&m.isAbsolute(i)?m.resolve(i):m.resolve(n,gt(i,"logs"))}function te(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||t}function pt(e){let t=e?new Date(e):new Date;return (Number.isNaN(t.getTime())?new Date:t).toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function mt(e){return [pt(e.endedAt||e.startedAt),te(e.command||"job","job"),te(e.id||"job","job"),te(e.status||"finished","finished")].join("-")}function ht(e){return e.endsWith(".log.jsonl")||e.endsWith(".errors.jsonl")||e.endsWith(".rejected.jsonl")?true:["current-crawl-event.json","rejected.jsonl","ignored.jsonl","skipped-http.jsonl","errors.jsonl","timings.jsonl","rejected.json","ignored.json","skipped-http.json","errors.json","timings.json"].includes(e)}function ft(e){return e==="errors.json"||e==="errors.jsonl"||e.endsWith(".errors.jsonl")?"errors":e==="ignored.json"||e==="ignored.jsonl"?"ignored":e==="rejected.json"||e==="rejected.jsonl"||e.endsWith(".rejected.jsonl")?"rejected":e==="skipped-http.json"||e==="skipped-http.jsonl"?"skipped-http":e==="timings.json"||e==="timings.jsonl"?"timings":e==="current-progress.json"?"current-progress":e==="current-crawl-event.json"?"current-crawl-event":e.endsWith(".log.jsonl")?e.replace(/\.log\.jsonl$/i,"-log"):e.replace(/\.[^.]+$/u,"")||"artifact"}function yt(e){return e.endsWith(".gz")?"application/gzip":e.endsWith(".jsonl")?"application/x-ndjson":e.endsWith(".json")?"application/json":"text/plain"}async function ne(e,t,n){let r=`${n}.gz`,i=m.join(t,r);await pipeline(createReadStream(e),createGzip({level:9}),createWriteStream(i));let[a,s]=await Promise.all([P.stat(e),P.stat(i)]);return {role:ft(n),originalFileName:n,storedFileName:r,compressed:true,compression:"gzip",contentType:yt(r),originalSize:a.size,storedSize:s.size}}async function $(e,t){let n=await Re(t),r=new Date().toISOString(),i=mt(e),a=m.join(n,"archive",i),s=[],o=[];await P.mkdir(a,{recursive:true});try{let d=await P.readdir(n,{withFileTypes:!0});for(let g of d){if(!g.isFile()||!ht(g.name))continue;let p=await ne(m.join(n,g.name),a,g.name);o.push(p),s.push(p.storedFileName);}}catch(d){if((d&&typeof d=="object"&&"code"in d?String(d.code||""):"")!=="ENOENT")throw d}let u=ae(t.runtimeDir);if(existsSync(u)){let d=await ne(u,a,"current-progress.json");o.push(d),s.push(d.storedFileName);}if(e.command==="content-sync")for(let d of ["content-sync-current.json","content-sync-impact-plan.json","content-sync-checkpoint.json","content-sync-state.json","content-sync-invalidation.json","deploy-plan.json"]){let g=m.join(t.runtimeDir,d);if(!existsSync(g))continue;let p=await ne(g,a,d);o.push(p),s.push(p.storedFileName);}let c=[...s,"job.json"];return await w(m.join(a,"job.json"),{manifestVersion:1,archivedAt:r,archiveKey:i,archiveDir:a,logDir:n,runtimeDir:t.runtimeDir,exporterDir:t.exporterDir,configPath:t.configPath||"",archivedFiles:c,artifacts:o,job:e}),{archiveKey:i,archiveDir:a,archiveCreatedAt:r,archivedFiles:c,artifacts:o}}function bt(e){return m.join(e,"audit-events.jsonl")}function se(e){return m.join(e,"stop-request.json")}async function qe(e){try{let t=await P.readFile(se(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}async function ve(e,t){let n=await qe(e);if(!n)return null;let r=String(n.targetJobId||"").trim();return r&&r!==t?null:n}async function L(e,t){if(!t){await P.unlink(se(e)).catch(()=>{});return}let n=await qe(e);if(!n)return;let r=String(n.targetJobId||"").trim();(!r||r===t)&&await P.unlink(se(e)).catch(()=>{});}async function I(e,t){try{let n={occurredAt:t.occurredAt||new Date().toISOString(),status:t.status||"info",actorSource:t.actorSource||"queue-runner",...t};await P.mkdir(e,{recursive:!0}),await P.appendFile(bt(e),`${JSON.stringify(n)}
2
- `,"utf8");}catch{}}async function C(e,t,n){let[r,i]=await Promise.all([we(m.join(e.exporterDir,"package.json")),we(m.join(e.exporterDir,"node_modules","@smart-cloud","wpsuite-core","package.json"))]),a={checkedAt:new Date().toISOString(),status:t,pid:process.pid,nodePath:process.execPath,nodeVersion:process.version,exporterVersion:r,wpsuiteCoreVersion:i,runtimeDir:e.runtimeDir,exporterDir:e.exporterDir,...n??{}};try{await w(Ie(e.runtimeDir),a);}catch{}}async function O(e){try{await P.unlink(ae(e));}catch{}}function St(e,t){let n=e.command;if(n!=="publish"&&n!=="crawl"&&n!=="deploy"&&n!=="invalidate"&&n!=="retry-timeouts"&&n!=="url"&&n!=="content-sync")return null;let r=Number.parseInt(String(e.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let i=(e.id||`${n}-${t+1}`).trim();if(!i)return null;let a=e.enabled!==false,s=typeof e.url=="string"?e.url.trim():"",o=typeof e.deploymentProfile=="string"?e.deploymentProfile.trim():"",u=Array.isArray(e.postTypes)?[...new Set(e.postTypes.map(g=>String(g).trim()).filter(Boolean))]:[],c=Array.isArray(e.listingPaths)?[...new Set(e.listingPaths.map(g=>String(g).trim()).filter(Boolean))]:[],d=(n==="publish"||n==="crawl")&&e.crawlMode==="incremental"?"incremental":"full";return n==="url"&&!s||n==="content-sync"&&u.length===0?null:{id:i,enabled:a,command:n,intervalMinutes:r,...n==="publish"||n==="crawl"?{crawlMode:d}:{},...(n==="publish"||n==="deploy"||n==="invalidate"||n==="content-sync")&&o?{deploymentProfile:o}:{},...s?{url:s}:{},...u.length>0?{postTypes:u}:{},...c.length>0?{listingPaths:c}:{},...typeof e.includeSubsites=="boolean"?{includeSubsites:e.includeSubsites}:{},...typeof e.includePostTypeArchives=="boolean"?{includePostTypeArchives:e.includePostTypeArchives}:{},...typeof e.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:e.includeTaxonomyArchives}:{},...typeof e.includeAuthorArchives=="boolean"?{includeAuthorArchives:e.includeAuthorArchives}:{},...typeof e.includeDateArchives=="boolean"?{includeDateArchives:e.includeDateArchives}:{},...typeof e.includePostsPage=="boolean"?{includePostsPage:e.includePostsPage}:{},...typeof e.includeSitemapChain=="boolean"?{includeSitemapChain:e.includeSitemapChain}:{}}}async function wt(e){let t=await Z(e.configPath).catch(()=>null),n=t?.scheduler,r=Array.isArray(n?.rules)?n.rules.map((i,a)=>St(i,a)).filter(i=>!!i):[];return {enabled:!!n?.enabled,timezone:typeof n?.timezone=="string"&&n.timezone.trim()?n.timezone.trim():"UTC",rules:r,wpsuite:t?.wpsuite,publisherConfig:t}}function re(e,t){if(!t)throw new Error("Content-sync scheduler requires a valid publisher config.");let n=M({postTypes:e.postTypes??[],listingPaths:e.listingPaths??[],includeSubsites:e.includeSubsites,includePostTypeArchives:e.includePostTypeArchives,includeTaxonomyArchives:e.includeTaxonomyArchives,includeAuthorArchives:e.includeAuthorArchives,includeDateArchives:e.includeDateArchives,includePostsPage:e.includePostsPage,includeSitemapChain:e.includeSitemapChain}),r=_(t.sourceOrigin,e.id,n),i=z(t,e.deploymentProfile),a=K({sourceOrigin:t.sourceOrigin,targetOrigin:i.config.targetOrigin,deploymentProfile:i.name||"",s3Bucket:i.config.s3.bucket,s3Prefix:i.config.s3.prefix,cloudFrontDistributionId:i.config.cloudFront.distributionId,urlRewriteMode:i.config.urlRewriteMode,extraReplacements:i.profile?.extraReplacements??{}});return `content-sync:${e.id}:${J({scopeFingerprint:r,targetFingerprint:a}).slice(0,32)}`}async function vt(e,t,n,r,i){let s=(await v(m.join(e.runtimeDir,"content-sync-baseline.json"),{})).entries?.[r];if(!s?.consumerId||!s.scopeFingerprint||!s.baselineId)return {status:"baseline-required",reason:"No verified normal-release baseline exists for this rule scope."};try{let o=t.publisherConfig;if(!o)throw new Error("Publisher configuration is unavailable.");let u=M({postTypes:n.postTypes??[],listingPaths:n.listingPaths??[],includeSubsites:n.includeSubsites,includePostTypeArchives:n.includePostTypeArchives,includeTaxonomyArchives:n.includeTaxonomyArchives,includeAuthorArchives:n.includeAuthorArchives,includeDateArchives:n.includeDateArchives,includePostsPage:n.includePostsPage,includeSitemapChain:n.includeSitemapChain}),c=_(o.sourceOrigin,n.id,u),d=z(o,n.deploymentProfile),g=K({sourceOrigin:o.sourceOrigin,targetOrigin:d.config.targetOrigin,deploymentProfile:d.name||"",s3Bucket:d.config.s3.bucket,s3Prefix:d.config.s3.prefix,cloudFrontDistributionId:d.config.cloudFront.distributionId,urlRewriteMode:d.config.urlRewriteMode,extraReplacements:d.profile?.extraReplacements??{}});if(s.scopeFingerprint!==c||s.targetFingerprint!==g||!s.releaseFingerprint)return {status:"baseline-required",reason:"The verified content-sync baseline does not match the active scope or deployment target. Run a successful full or incremental publish to establish a new baseline."};let p=new U({sourceOrigin:o.sourceOrigin,runtimeToken:String(o.wpsuite?.runtimeToken||""),ignoreHttpsErrors:o.ignoreHttpsErrors}),h=await p.releaseFingerprint(u.includeSubsites),y=de({wordpressFingerprint:h,targetFingerprint:g,sourceOrigin:o.sourceOrigin,sitemapPaths:o.sitemapPaths,blockedPathPrefixes:o.blockedPathPrefixes,assetPathPrefixes:o.assetPathPrefixes,noJavaScriptRenderPathPrefixes:o.noJavaScriptRenderPathPrefixes,urlRewriteMode:o.urlRewriteMode});if(s.releaseFingerprint!==y)return {status:"baseline-required",reason:"The installed WordPress release changed after the last verified content-sync baseline. Run a successful full or incremental publish to establish a new baseline."};let l=await p.head({consumerId:s.consumerId,scopeFingerprint:s.scopeFingerprint,baselineId:s.baselineId,postTypes:u.postTypes,includeSubsites:u.includeSubsites}),b=l.committedSequence;if(i?.command==="content-sync"&&i.coalesceKey===r){let S=await v(m.join(e.runtimeDir,"content-sync-current.json"),null);S?.coalesceKey===r&&Number.isSafeInteger(S.toSequence)&&(b=Math.max(b,Number(S.toSequence)));}return {status:l.headSequence>b?"pending":"current",headSequence:l.headSequence,committedSequence:l.committedSequence}}catch(o){return o instanceof k&&o.code==="baseline-required"?{status:"baseline-required",reason:o.message}:{status:"unavailable",reason:o instanceof Error?o.message:String(o)}}}async function De(e,t,n,r,i,a){let s=m.join(e.runtimeDir,"content-sync-state.json"),u=(await v(s,{})).rules??{},c=u[n]??{};u[n]={...c,ruleId:t,coalesceKey:n,...Number.isSafeInteger(i)?{observedHeadSequence:i}:{},...Number.isSafeInteger(a)?{committedSequence:a}:{},retryAttempt:0,nextRetryAt:null,lastError:r,baselineStatus:"required",baselineReason:r,trailingWorkDetected:Number.isSafeInteger(i)&&Number.isSafeInteger(a)?Number(i)>Number(a):!!c.trailingWorkDetected},await w(s,{schemaVersion:1,updatedAt:new Date().toISOString(),rules:u});}function oe(e,t){let n=(t.url||"").trim(),r=t.crawlMode||"full",i=(t.deploymentProfile||"").trim(),a=(t.coalesceKey||"").trim();return e.some(s=>s.command===t.command&&(t.command!=="content-sync"||(s.coalesceKey||"").trim()===a)&&(s.url||"").trim()===n&&(s.crawlMode||"full")===r&&(s.deploymentProfile||"").trim()===i&&(s.status===void 0||s.status==="queued"||s.status==="retry-wait"||s.status==="running"))}async function Pt(e,t,n){if(!t.allowSchedulerAutoEnqueue)return 0;let r=await wt(e);if(!r.enabled||r.rules.length===0)return 0;if(t.assertActiveSubscriptionForIdentity)try{await t.assertActiveSubscriptionForIdentity(r.wpsuite??null);}catch(l){let b=l instanceof Error?l.message:String(l);return console.warn(`[queue-runner] scheduler auto-enqueue skipped: ${b}`),0}let i=m.join(e.runtimeDir,"queue.json"),a=m.join(e.runtimeDir,"current-run.json"),s=Date.now(),o=0,u=[],c=[],d=[],g=new Map,[p,h,y]=await Promise.all([v(i,[]),v(a,null),v(ee(e.runtimeDir),{lastEnqueuedBucketByRuleId:{},lastEvaluatedBucketByRuleId:{},lastCreatedBucketByRuleId:{},coalescedCountByRuleId:{}})]);for(let l of r.rules){if(!l.enabled||l.command!=="content-sync")continue;let b=Math.floor(s/(l.intervalMinutes*60*1e3)),S=y.lastEvaluatedBucketByRuleId?.[l.id]??y.lastEnqueuedBucketByRuleId?.[l.id]??-1;if(b<=S)continue;let D=re(l,r.publisherConfig);oe(p,{command:l.command,deploymentProfile:l.deploymentProfile,coalesceKey:D})||g.set(l.id,await vt(e,r,l,D,h));}await E(e.runtimeDir,async()=>{let l=await v(i,[]),b=await v(a,null),S=await v(ee(e.runtimeDir),{lastEnqueuedBucketByRuleId:{},lastEvaluatedBucketByRuleId:{},lastCreatedBucketByRuleId:{},coalescedCountByRuleId:{}});S.lastEnqueuedBucketByRuleId??={},S.lastEvaluatedBucketByRuleId??={...S.lastEnqueuedBucketByRuleId},S.lastCreatedBucketByRuleId??={...S.lastEnqueuedBucketByRuleId},S.coalescedCountByRuleId??={};let D=[...l];b&&b.status==="running"&&D.unshift(b);for(let f of r.rules){if(!f.enabled)continue;let A=f.intervalMinutes*60*1e3,q=Math.floor(s/A),F=S.lastEvaluatedBucketByRuleId[f.id]??S.lastEnqueuedBucketByRuleId[f.id]??-1;if(q<=F)continue;let j=f.command==="content-sync"?re(f,r.publisherConfig):"";S.lastEvaluatedBucketByRuleId[f.id]=q;let T=f.command==="content-sync"?l:D;if(oe(T,{command:f.command,url:f.url,crawlMode:f.crawlMode,deploymentProfile:f.deploymentProfile,coalesceKey:j})){S.coalescedCountByRuleId[f.id]=(S.coalescedCountByRuleId[f.id]??0)+1,c.push(f);continue}if(f.command==="content-sync"){let W=g.get(f.id);if(!W||W.status!=="pending"){let ce=W??{status:"unavailable",reason:"Content-sync demand was not checked."};ce.status!=="current"&&d.push({rule:f,check:ce});continue}}let Q={id:randomUUID(),command:f.command,...f.command==="content-sync"?{ruleId:f.id,coalesceKey:j,attempt:0}:{},...(f.command==="publish"||f.command==="crawl")&&f.crawlMode?{crawlMode:f.crawlMode}:{},...(f.command==="publish"||f.command==="deploy"||f.command==="invalidate"||f.command==="content-sync")&&f.deploymentProfile?{deploymentProfile:f.deploymentProfile}:{},...f.url?{url:f.url}:{},enqueueSource:"scheduler",...r.wpsuite?{wpsuite:r.wpsuite}:{},status:"queued",createdAt:new Date().toISOString(),createdBy:0};l.push(Q),D.push(Q),u.push({job:Q,rule:f}),S.lastEnqueuedBucketByRuleId[f.id]=q,S.lastCreatedBucketByRuleId[f.id]=q,o+=1;}o>0&&await w(i,l),await w(ee(e.runtimeDir),S);});for(let l of u){if(l.rule.command==="content-sync"){let b=g.get(l.rule.id);await I(e.runtimeDir,{eventType:"content-sync-demand-detected",status:"queued",actorSource:"queue-runner-scheduler",jobId:l.job.id,command:l.job.command,message:"Pending journal changes require a content-sync job.",details:{ruleId:l.rule.id,headSequence:b?.headSequence??0,committedSequence:b?.committedSequence??0}});}await I(e.runtimeDir,{eventType:"job-created",status:"queued",actorSource:"queue-runner-scheduler",jobId:l.job.id,command:l.job.command,message:"Scheduler auto-enqueued a job.",details:{ruleId:l.rule.id,intervalMinutes:l.rule.intervalMinutes,timezone:r.timezone,deploymentProfile:l.rule.deploymentProfile||"",url:l.rule.url||""}});}for(let l of c)await I(e.runtimeDir,{eventType:"content-sync-coalesced",status:"queued",actorSource:"queue-runner-scheduler",command:l.command,message:"Scheduler demand was coalesced into an existing content-sync job.",details:{ruleId:l.id}});for(let l of d){if(l.check.status==="baseline-required"){let b=re(l.rule,r.publisherConfig);await De(e,l.rule.id,b,l.check.reason||"A successful full or incremental publish must establish a new content-sync baseline.",l.check.headSequence,l.check.committedSequence);}await I(e.runtimeDir,{eventType:l.check.status==="baseline-required"?"content-sync-baseline-required":"content-sync-demand-check-failed",status:l.check.status==="unavailable"?"failed":"info",actorSource:"queue-runner-scheduler",command:"content-sync",message:l.check.reason||"The content-sync consumer is already at the current journal head.",details:{ruleId:l.rule.id,headSequence:l.check.headSequence??0,committedSequence:l.check.committedSequence??0}});}return o}async function Ct(e){let t={pid:process.pid,startedAt:new Date().toISOString()};await P.writeFile(e,JSON.stringify(t,null,2),{encoding:"utf8",flag:"wx"});}async function At(e){try{await P.unlink(e);}catch{}}function It(e,t){let n=[m.join(e,"dist",`${t}.js`),m.join(e,`${t}.js`)];for(let r of n)if(existsSync(r))return r;throw new Error(`Cannot find ${t}.js in ${m.join(e,"dist")} or ${e}`)}async function R(e,t,n,r,i,a,s){if(s){let c=await ve(t,s);if(c)throw new B(c,n)}let o=It(e,n),u={...process.env,...a??{}};return u.STATIC_PUBLISHER_RUNTIME_DIR=t,i&&(u.PUBLISHER_CONFIG=i),await new Promise((c,d)=>{let g=null,p=null,h=null,y=null,l=false,b="",S=spawn(process.execPath,[o,...r],{cwd:e,env:u,stdio:["inherit","inherit","pipe"]});S.stderr?.on("data",A=>{b+=A.toString("utf8");});let D=()=>{p&&clearInterval(p),h&&clearInterval(h),y&&clearTimeout(y);},f=async()=>{if(!(!s||g||l)){l=true;try{let A=await ve(t,s);if(!A)return;g=A,S.kill("SIGTERM"),y=setTimeout(()=>{S.kill("SIGKILL");},1e4);}finally{l=false;}}};s&&(p=setInterval(()=>{f();},1e3),h=setInterval(()=>{(async()=>{let A=Ie(t),q=await v(A,{});await w(A,{...q,checkedAt:new Date().toISOString(),status:"running",currentJobId:s||q.currentJobId||"",currentStep:n});})().catch(()=>{});},15e3)),S.on("error",A=>{D(),d(A);}),S.on("close",(A,q)=>{D();let F=pe(b).trim();if(F&&process.stderr.write(`${F}
3
- `),g){d(new B(g,n));return}if(A===0)c();else {let j=F.split(/\r?\n/).map(T=>T.trim()).find(T=>T&&!T.startsWith("at "));d(new Error(`${n} exited with code ${A??-1}${q?` (signal ${q})`:""}${j?`: ${j}`:""}`));}});}),0}function Rt(e){let t=e.awsTempCreds;if(!t)return {};let n={};return typeof t.accessKeyId=="string"&&t.accessKeyId.trim()!==""&&(n.AWS_ACCESS_KEY_ID=t.accessKeyId.trim()),typeof t.secretAccessKey=="string"&&t.secretAccessKey.trim()!==""&&(n.AWS_SECRET_ACCESS_KEY=t.secretAccessKey.trim()),typeof t.sessionToken=="string"&&t.sessionToken.trim()!==""&&(n.AWS_SESSION_TOKEN=t.sessionToken.trim()),n}async function qt(e,t){let n=s=>{if(!s||typeof s!="object")return null;let o=s,u={...o.siteSettings??{},...String(o.accountId??"").trim()&&!o.siteSettings?.accountId?{accountId:String(o.accountId).trim()}:{},...String(o.siteId??"").trim()&&!o.siteSettings?.siteId?{siteId:String(o.siteId).trim()}:{},...o.siteSettings?.subscriber===true||o.subscriber===true?{subscriber:true}:{}},c={...String(o.apiBase??"").trim()?{apiBase:String(o.apiBase).trim()}:{},...String(o.runtimeToken??o.nonce??"").trim()?{runtimeToken:String(o.runtimeToken??o.nonce).trim()}:{},...String(o.virtualAssetBaseUrl??o.uploadUrl??"").trim()?{virtualAssetBaseUrl:String(o.virtualAssetBaseUrl??o.uploadUrl).trim()}:{},...Object.keys(u).length>0?{siteSettings:u}:{},...o.subscriptionType?{subscriptionType:o.subscriptionType}:{}};return Object.keys(c).length>0?c:null},r=await Z(t.configPath).catch(()=>null),i=n(r?.wpsuite);if(i)return i;let a=n(e.wpsuite);return a||null}async function Dt(e,t){return await qt(e,t)}function ue(e){let t={...e,status:"queued"};return delete t.startedAt,delete t.endedAt,delete t.exitCode,delete t.error,delete t.stopRequestedAt,delete t.stopRequestedByUserId,delete t.stopRequestedByLogin,delete t.stopMode,delete t.stoppedStep,t}async function xt(e,t){let n=await v(ae(e.runtimeDir),null),r=n&&n.details&&typeof n.details.phase=="string"?n.details.phase.trim():"";if(r)return r;let i=n&&typeof n.currentStep=="string"?n.currentStep.trim():"";if(i)return i;let a=await Re(e).catch(()=>"");if(a){let s=await v(m.join(a,"current-crawl-event.json"),null),o=s&&typeof s.currentStep=="string"?s.currentStep.trim():"";if(o)return o}return t}function Tt(e,t){if((e.command==="publish"||e.command==="crawl")&&t==="rewrite-text")return "rewrite-text"}async function kt(e){let t=m.join(e.runtimeDir,"queue.json"),n=m.join(e.runtimeDir,"current-run.json"),r=await E(e.runtimeDir,async()=>{let i=await v(n,null);if(!i||i.status!=="running"&&i.status!=="queued")return null;let a=await v(t,[]),s=Array.isArray(a)?a.filter(u=>u?.id!==i.id):[],o=ue(i);return await w(t,[o,...s]),await w(n,null),o});r&&(await L(e.runtimeDir,r.id),await I(e.runtimeDir,{eventType:"job-recovered",status:"queued",actorSource:"queue-runner",jobId:r.id,command:r.command,message:"Recovered stale current-run entry back into queue."}));}async function Et(e,t,n){try{if((n.shouldEnforceSubscriptionOnJobExecution?.(e)??n.enforceSubscriptionOnJobExecution)&&n.assertActiveSubscriptionForIdentity){let o=await Dt(e,t);await n.assertActiveSubscriptionForIdentity(o);}let i=Rt(e),a=e.resumeFromStep==="rewrite-text"?["--resume-rewrite"]:e.crawlMode==="incremental"?["--crawl-mode","incremental"]:[],s=e.deploymentProfile?["--profile",e.deploymentProfile]:[];if(e.command==="publish")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync-release-cutoff"}),await R(t.exporterDir,t.runtimeDir,"content-sync",["--capture-baseline-cutoffs",e.id],t.configPath,i,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await R(t.exporterDir,t.runtimeDir,"crawl",a,t.configPath,i,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await R(t.exporterDir,t.runtimeDir,"deploy",s,t.configPath,i,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await R(t.exporterDir,t.runtimeDir,"invalidate",s,t.configPath,i,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync-baseline"}),await R(t.exporterDir,t.runtimeDir,"content-sync",["--establish-baselines",e.id],t.configPath,i,e.id),{exitCode:0};if(e.command==="crawl")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await R(t.exporterDir,t.runtimeDir,"crawl",a,t.configPath,i,e.id),{exitCode:0};if(e.command==="deploy")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await R(t.exporterDir,t.runtimeDir,"deploy",s,t.configPath,i,e.id),{exitCode:0};if(e.command==="invalidate")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await R(t.exporterDir,t.runtimeDir,"invalidate",s,t.configPath,i,e.id),{exitCode:0};if(e.command==="retry-timeouts")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"retry-timeouts"}),await R(t.exporterDir,t.runtimeDir,"crawl",["--retry-timeouts"],t.configPath,i,e.id),{exitCode:0};if(e.command==="url"){let o=(e.url||"").trim();return o?(await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"url"}),await R(t.exporterDir,t.runtimeDir,"crawl",["--url",o],t.configPath,i,e.id),{exitCode:0}):{exitCode:2,error:"Missing url for command 'url'"}}return e.command==="content-sync"?!e.ruleId||!e.coalesceKey?{exitCode:2,error:"Content-sync queue jobs require ruleId and coalesceKey."}:(await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync"}),await R(t.exporterDir,t.runtimeDir,"content-sync",["--job-id",e.id],t.configPath,i,e.id),{exitCode:0}):{exitCode:2,error:`Unsupported command: ${e.command}`}}catch(r){return r instanceof B?{exitCode:130,error:"Job stop requested.",stopped:true,stopRequest:r.request,stoppedStep:r.step}:{exitCode:1,error:r instanceof Error?r.message:String(r)}}}function xe(e){return async function(n=process.argv.slice(2)){let r=ut(n),i=m.join(r.runtimeDir,"export.lock"),a=m.join(r.runtimeDir,"last-run.json");await O(r.runtimeDir),await C(r,"starting",{message:"queue-runner starting"});try{await Ct(i);}catch(s){if((s&&typeof s=="object"&&"code"in s?String(s.code||""):"")!=="EEXIST")throw s;console.log("[queue-runner] lock active, skipping"),await C(r,"lock-active",{message:"lock active, skipped this cron tick"});return}try{await kt(r);let s=await Pt(r,e),o=0;for(let u=0;u<r.maxJobs;u++){let c=await Lt(r,e);if(c==="none"||(o+=1,c==="stopped"))break}if(o===0)await O(r.runtimeDir),await C(r,"idle",{processedJobs:o,schedulerEnqueued:s,message:"no queued jobs"});else {await O(r.runtimeDir);let u=await v(a,null),c=String(u?.status||"").trim();await C(r,c==="success"?"job-success":c==="stopped"?"job-stopped":"job-failed",{processedJobs:o,schedulerEnqueued:s,lastJobId:u?.id,lastJobCommand:u?.command,lastJobStatus:u?.status,lastJobExitCode:u?.exitCode,lastJobError:u?.error,...c==="stopped"?{currentStep:u?.stoppedStep,stopRequestedAt:u?.stopRequestedAt,stopRequestedByLogin:u?.stopRequestedByLogin,stopRequestedMode:u?.stopMode,lastStoppedStep:u?.stoppedStep,message:u?.stopMode==="requeue"?`Job stopped during ${u?.stoppedStep||u?.command||"active step"} and requeued.`:`Job stopped during ${u?.stoppedStep||u?.command||"active step"} and left out of queue.`}:{}});}}catch(s){let o=s instanceof Error?s.message:String(s);throw await C(r,"error",{message:o}),await I(r.runtimeDir,{eventType:"queue-runner-error",status:"failed",actorSource:"queue-runner",message:"Unhandled queue-runner error.",details:{error:o}}),s}finally{await At(i);}}}async function Ft(e,t,n){let r=m.join(e.runtimeDir,"queue.json"),i=m.join(e.runtimeDir,"current-run.json");await E(e.runtimeDir,async()=>{let a=await v(r,[]),s=Array.isArray(a)?a.filter(c=>c?.id!==t.id):[],o=ue(t),u=Tt(t,n);u?o.resumeFromStep=u:delete o.resumeFromStep,await w(r,[o,...s]),await w(i,null);});}async function jt(e,t,n){let r=Math.max(0,t.attempt??0)+1,i=Math.min(3600*1e3,6e4*2**(r-1)),a=Math.floor(i*.2*Math.random()),s=new Date(Date.now()+i+a).toISOString(),o={...ue(t),status:"retry-wait",attempt:r,nextAttemptAt:s,error:n};if(await E(e.runtimeDir,async()=>{let u=m.join(e.runtimeDir,"queue.json"),c=m.join(e.runtimeDir,"current-run.json"),g=(await v(u,[])).filter(p=>p.id!==t.id);await w(u,[o,...g]),await w(c,null);}),t.coalesceKey){let u=m.join(e.runtimeDir,"content-sync-state.json"),d=(await v(u,{})).rules??{};d[t.coalesceKey]={...d[t.coalesceKey]??{},ruleId:t.ruleId||"",coalesceKey:t.coalesceKey,retryAttempt:r,nextRetryAt:s,lastError:n,trailingWorkDetected:true},await w(u,{schemaVersion:1,updatedAt:new Date().toISOString(),rules:d});}return o}async function Jt(e,t){if(!t.coalesceKey||!t.ruleId||!(await v(m.join(e.runtimeDir,"content-sync-state.json"),null))?.rules?.[t.coalesceKey]?.trailingWorkDetected)return null;let r=null;await E(e.runtimeDir,async()=>{let a=m.join(e.runtimeDir,"queue.json"),s=await v(a,[]);oe(s,{command:"content-sync",coalesceKey:t.coalesceKey,deploymentProfile:t.deploymentProfile})||(r={id:randomUUID(),command:"content-sync",ruleId:t.ruleId,coalesceKey:t.coalesceKey,deploymentProfile:t.deploymentProfile,enqueueSource:"scheduler",wpsuite:t.wpsuite,status:"queued",attempt:0,createdAt:new Date().toISOString(),createdBy:0},await w(a,[...s,r]));});let i=r;return i&&await I(e.runtimeDir,{eventType:"content-sync-trailing-job-created",status:"queued",actorSource:"queue-runner",jobId:i.id,command:i.command,message:"Content changes after the stable cutoff created one trailing job.",details:{predecessorJobId:t.id,ruleId:t.ruleId,coalesceKey:t.coalesceKey}}),i}async function Lt(e,t){let n=m.join(e.runtimeDir,"queue.json"),r=m.join(e.runtimeDir,"current-run.json"),i=m.join(e.runtimeDir,"last-run.json"),a=new Date().toISOString(),s=await E(e.runtimeDir,async()=>{let g=await v(n,[]);if(!Array.isArray(g)||g.length===0)return null;let p=Date.parse(String(g[0]?.nextAttemptAt||""));if(Number.isFinite(p)&&p>Date.now())return null;let h={...g[0],status:"running",startedAt:a};return delete h.nextAttemptAt,await w(n,g.slice(1)),await w(r,h),h});if(!s)return "none";await O(e.runtimeDir),await I(e.runtimeDir,{eventType:"job-run-started",status:"running",actorSource:"queue-runner",jobId:s.id,command:s.command,message:"Job execution started.",details:{createdAt:s.createdAt||"",startedAt:a,createdBy:s.createdBy??null,deploymentProfile:s.deploymentProfile||"",queuedWithTempAwsCreds:!!s.awsTempCreds}}),await C(e,"running",{currentJobId:s.id,currentJobCommand:s.command,currentStep:s.command});let o=await Et(s,e,t),u=new Date().toISOString();if(o.stopped){let g=await xt(e,o.stoppedStep||s.command),p=o.stopRequest?.mode==="requeue"?"requeue":"stop",h={...s,status:"stopped",endedAt:u,exitCode:o.exitCode,...o.error?{error:o.error}:{},stopRequestedAt:o.stopRequest?.requestedAt||"",stopRequestedByUserId:typeof o.stopRequest?.requestedByUserId=="number"?o.stopRequest.requestedByUserId:null,stopRequestedByLogin:o.stopRequest?.requestedByLogin||"",stopMode:p,stoppedStep:g};p==="requeue"?await Ft(e,s,g):await w(r,null);try{let y=await $(h,e);h.logArchiveDir=y.archiveDir,h.logArchiveCreatedAt=y.archiveCreatedAt,h.logArchiveFileCount=y.archivedFiles.length;}catch(y){h.logArchiveError=y instanceof Error?y.message:String(y);}return await w(i,h),await L(e.runtimeDir,s.id),await O(e.runtimeDir),await I(e.runtimeDir,{eventType:"job-run-stopped",status:"stopped",actorSource:"queue-runner",jobId:s.id,command:s.command,message:p==="requeue"?"Job stop requested and requeued.":"Job stop requested and removed from active execution without requeue.",details:{startedAt:s.startedAt||"",endedAt:u,deploymentProfile:s.deploymentProfile||"",stopMode:p,stopRequestedAt:o.stopRequest?.requestedAt||"",stopRequestedByLogin:o.stopRequest?.requestedByLogin||"",stopRequestedByUserId:typeof o.stopRequest?.requestedByUserId=="number"?o.stopRequest.requestedByUserId:null,stoppedStep:g,logArchiveKey:h.logArchiveError||!h.logArchiveDir?"":m.basename(h.logArchiveDir),logArchiveDir:h.logArchiveDir||"",logArchiveCreatedAt:h.logArchiveCreatedAt||"",logArchiveFileCount:h.logArchiveFileCount??0,logArchiveError:h.logArchiveError||""}}),"stopped"}if(s.command==="content-sync"&&o.exitCode!==0){if(/baseline (?:is missing or stale|required)|verified content-sync baseline|new baseline/i.test(o.error||"")){let y="The installed release no longer matches the verified content-sync baseline. Run a successful full or incremental publish to establish a new baseline.";s.ruleId&&s.coalesceKey&&await De(e,s.ruleId,s.coalesceKey,y);let l={...s,status:"failed",endedAt:u,exitCode:o.exitCode,error:y};try{let b=await $(l,e);l.logArchiveDir=b.archiveDir,l.logArchiveCreatedAt=b.archiveCreatedAt,l.logArchiveFileCount=b.archivedFiles.length;}catch(b){l.logArchiveError=b instanceof Error?b.message:String(b);}return await w(i,l),await L(e.runtimeDir,s.id),await I(e.runtimeDir,{eventType:"content-sync-baseline-required",status:"failed",actorSource:"queue-runner",jobId:s.id,command:s.command,message:y,details:{ruleId:s.ruleId||"",retryScheduled:false}}),"processed"}await I(e.runtimeDir,{eventType:"content-sync-failed",status:"failed",actorSource:"queue-runner",jobId:s.id,command:s.command,message:"Content-sync execution failed before cursor acknowledgement.",details:{attempt:s.attempt??0,error:o.error||"Content-sync execution failed."}});let p=await jt(e,s,o.error||"Content-sync execution failed."),h={...s,status:"retry-wait",endedAt:u,exitCode:o.exitCode,error:p.error,attempt:p.attempt,nextAttemptAt:p.nextAttemptAt};try{let y=await $(h,e);h.logArchiveDir=y.archiveDir,h.logArchiveCreatedAt=y.archiveCreatedAt,h.logArchiveFileCount=y.archivedFiles.length;}catch(y){h.logArchiveError=y instanceof Error?y.message:String(y);}return await w(i,h),await L(e.runtimeDir,s.id),await I(e.runtimeDir,{eventType:"content-sync-retry-scheduled",status:"retry-wait",actorSource:"queue-runner",jobId:s.id,command:s.command,message:"Content-sync retry was scheduled with bounded backoff.",details:{attempt:p.attempt??0,nextAttemptAt:p.nextAttemptAt||"",error:p.error||""}}),"processed"}let c={...s,status:o.exitCode===0?"success":"failed",endedAt:u,exitCode:o.exitCode,...o.error?{error:o.error}:{}};await w(r,null),c.status==="success"&&c.command==="content-sync"&&await Jt(e,c),await L(e.runtimeDir,s.id);try{let g=await $(c,e);c.logArchiveDir=g.archiveDir,c.logArchiveCreatedAt=g.archiveCreatedAt,c.logArchiveFileCount=g.archivedFiles.length;}catch(g){c.logArchiveError=g instanceof Error?g.message:String(g);}await w(i,c);let d=s.startedAt&&c.endedAt?Math.max(0,Math.round((new Date(c.endedAt).getTime()-new Date(s.startedAt).getTime())/1e3)):void 0;return await I(e.runtimeDir,{eventType:"job-run-finished",status:c.status==="success"?"success":"failed",actorSource:"queue-runner",jobId:c.id,command:c.command,message:c.status==="success"?"Job execution finished successfully.":"Job execution finished with failure.",details:{startedAt:s.startedAt||"",endedAt:c.endedAt||"",durationSec:d,deploymentProfile:c.deploymentProfile||"",exitCode:c.exitCode??null,error:c.error||"",logArchiveKey:c.logArchiveError||!c.logArchiveDir?"":m.basename(c.logArchiveDir),logArchiveDir:c.logArchiveDir||"",logArchiveCreatedAt:c.logArchiveCreatedAt||"",logArchiveFileCount:c.logArchiveFileCount??0,logArchiveError:c.logArchiveError||""}}),"processed"}async function Bt(){throw new Error("Incremental and content-sync jobs require the premium Publisher runtime with an active Professional or Agency subscription.")}var Mt={allowSchedulerAutoEnqueue:false,enforceSubscriptionOnJobExecution:false,shouldEnforceSubscriptionOnJobExecution:e=>Ce(e),assertActiveSubscriptionForIdentity:Bt},Te=xe(Mt),Ut=Te,wn=Te;process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href&&Ut().catch(e=>{console.error(e),process.exit(1);});export{wn as default,Ut as main,Te as runQueueRunner};
1
+ import {pathToFileURL}from'url';import P from'fs/promises';import {existsSync,createReadStream,createWriteStream}from'fs';import m from'path';import {spawn}from'child_process';import {randomUUID,createHash}from'crypto';import Je from'http';import me from'https';import {pipeline}from'stream/promises';import {createGzip}from'zlib';function le(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function N(e){return Array.isArray(e)?e.map(N):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,N(n)])):e}function Ee(e){return JSON.stringify(N(e))}function J(e){return createHash("sha256").update(Ee(e)).digest("hex")}function de(e){return J({schemaVersion:1,wordpressFingerprint:e.wordpressFingerprint,targetFingerprint:e.targetFingerprint,sourceOrigin:e.sourceOrigin,sitemapPaths:[...e.sitemapPaths].sort(),blockedPathPrefixes:[...e.blockedPathPrefixes].sort(),assetPathPrefixes:[...e.assetPathPrefixes].sort(),noJavaScriptRenderPathPrefixes:[...e.noJavaScriptRenderPathPrefixes].sort(),urlRewriteMode:e.urlRewriteMode})}function Fe(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Unsupported source origin protocol: ${t.protocol}`);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,""),t.toString().replace(/\/$/,"")}function M(e){let t=le((e.postTypes??[]).map(r=>String(r).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let n=le((e.listingPaths??[]).map(r=>{let i=String(r).trim();if(!i)return "";let a=new URL(i,"https://content-sync.invalid/");if(a.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(i))throw new Error("Content-sync listing routes must be same-site paths.");let s=`/${a.pathname.replace(/^\/+|\/+$/g,"")}`;return s==="/"?"/":`${s}/`}));return {postTypes:t,listingPaths:n,includeSubsites:e.includeSubsites===true,includePostTypeArchives:e.includePostTypeArchives!==false,includeTaxonomyArchives:e.includeTaxonomyArchives!==false,includeAuthorArchives:e.includeAuthorArchives===true,includeDateArchives:e.includeDateArchives===true,includePostsPage:e.includePostsPage!==false,includeSitemapChain:e.includeSitemapChain!==false}}function _(e,t,n){return J({schemaVersion:1,sourceOrigin:Fe(e),ruleId:t.trim(),scope:M(n)})}function K(e){return J({schemaVersion:1,...e})}function pe(e){return e.replace(/((?:x-static-publisher-token|authorization|proxy-authorization|x-api-key|aws-access-key-id|aws-secret-access-key|aws-session-token)\s*:\s*)[^\r\n]+/gi,"$1[REDACTED]").replace(/\b(Basic|Bearer)\s+[^\s]+/gi,"$1 [REDACTED]").replace(/([?&](?:token|access_token|refresh_token|api_key|key|nonce)=)[^&\s]+/gi,"$1[REDACTED]").replace(/((?:"|')?(?:runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken)(?:"|')?\s*[:=]\s*(?:"|'))[^"']+/gi,"$1[REDACTED]")}var ge=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";ge?m.join(ge,"current-progress.json"):"";Promise.resolve();var Oe="wp-json/smartcloud-static-publisher/v1/content-sync/",Le=25*1024*1024,k=class extends Error{status;code;constructor(t,n,r){super(r),this.name="ContentSyncApiError",this.status=t,this.code=n;}},U=class{options;constructor(t){if(!t.runtimeToken.trim())throw new Error("Content-sync requires a WordPress runtime token.");this.options={...t,timeoutMs:t.timeoutMs??6e4};}endpoint(t){let n=this.options.sourceOrigin.replace(/\/+$/,"")+"/";return new URL(`${Oe}${t}`,n)}async post(t,n){let r=this.endpoint(t),i=Buffer.from(JSON.stringify(n),"utf8"),a=r.protocol==="https:"?me:Je,s=r.protocol==="https:"?new me.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((o,u)=>{let c=a.request(r,{method:"POST",agent:s,headers:{"content-type":"application/json","content-length":String(i.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},d=>{let g=[],p=0;d.on("data",h=>{if(p+=h.byteLength,p>Le){d.destroy(new Error("Content-sync API response exceeded the size limit."));return}g.push(h);}),d.on("error",u),d.on("end",()=>{let h=Buffer.concat(g).toString("utf8"),y;try{y=h?JSON.parse(h):{};}catch{u(new k(d.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let l=d.statusCode??500;if(l<200||l>=300){u(new k(l,String(y.code??"request-failed"),String(y.message??`Content-sync API request failed (${l}).`)));return}o(y);});});c.on("timeout",()=>c.destroy(new Error(`Content-sync API request timed out: ${t}`))),c.on("error",u),c.end(i);})}async head(t){return this.post("head",t)}async unboundHead(t,n){return this.post("head",{postTypes:t,includeSubsites:n})}async events(t){let n=[],r=t.afterSequence,i=new Set(t.postTypes);for(;r<t.throughSequence;){let a=await this.post("events",{...t,afterSequence:r,limit:250});if(a.fromSequence!==r||a.throughSequence!==t.throughSequence||a.nextSequence<r||a.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(a.items))throw new Error("Content-sync API returned a malformed event page.");let s=r;for(let o of a.items){if(!Number.isSafeInteger(o.sequence)||o.sequence<=s||o.sequence>t.throughSequence||!Number.isSafeInteger(o.postId)||o.postId<=0||!Number.isSafeInteger(o.blogId)||o.blogId<=0||!i.has(o.postType)||typeof o.operation!="string"||!o.operation)throw new Error("Content-sync API returned an invalid or out-of-scope journal event.");s=o.sequence;}if(a.items.length>0&&a.nextSequence!==s)throw new Error("Content-sync API event cursor does not match the final returned event.");if(n.push(...a.items),!a.hasMore)break;if(a.nextSequence===r)throw new Error("Content-sync API event pagination did not advance.");r=a.nextSequence;}if(t.throughSequence>t.afterSequence&&n.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return n}async resolveImpactFamilies(t,n){let r=await this.post("impact",{families:t,includeSubsites:n});return Array.isArray(r.families)?r.families:[]}async releaseFingerprint(t=false){let n=await this.post("fingerprint",{includeSubsites:t}),r=String(n.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("WordPress returned an invalid release fingerprint.");return r}async establishBaseline(t){return this.post("baseline",t)}async acknowledge(t){return this.post("ack",t)}};function Be(e){return typeof e.subscriptionType=="string"&&e.subscriptionType.trim()!==""}function Me(e,t){return {...e,...t??{}}}function Ue(e,t){return {...e,...t??{},invalidationPaths:[...(t?.invalidationPaths??e.invalidationPaths)||[]]}}function z(e,t){let n=String(t??e.deploymentTargetOverride??"").trim();if(!Be(e)){if(n)throw new Error(`Deployment target "${n}" requires an active WPSuite subscription and remote publisher config.`);return {name:null,profile:null,config:e}}let r=String(n||e.defaultDeploymentProfile||"").trim();if(!r)return {name:null,profile:null,config:e};let i=e.deploymentProfiles?.[r];if(!i)throw new Error(`Unknown deployment profile "${r}". Check the linked WPSuite publisher configuration.`);return {name:r,profile:i,config:{...e,targetOrigin:i.targetOrigin??e.targetOrigin,s3:Me(e.s3,i.s3),cloudFront:Ue(e.cloudFront,i.cloudFront)}}}function fe(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function Ne(e){let t=String(e??"").trim();if(!t)return "";let n=t;if(/^https?:\/\//i.test(n))try{n=new URL(n).pathname;}catch{return ""}if(n=n.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!n)return "";let r=n.endsWith("/"),i=n.replace(/^\/+/,"").split("/").map(s=>s.replace(/[^A-Za-z0-9._-]/g,"")).filter(s=>s.length>0&&s!=="."&&s!=="..");if(i.length===0)return "";let a=`/${i.join("/")}`;return r&&m.extname(a)===""&&(a+="/"),a==="/"?"":a}function H(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function _e(e){if(!e||typeof e!="object")return {};let t={};for(let[n,r]of Object.entries(e)){let i=n.trim();if(!i||!r||typeof r!="object")continue;let a=r,s={};if(typeof a.targetOrigin=="string"){let u=fe(a.targetOrigin);u&&(s.targetOrigin=u);}let o=H(a.extraReplacements);if(Object.keys(o).length>0&&(s.extraReplacements=o),a.s3&&typeof a.s3=="object"){let u={},c=a.s3;typeof c.bucket=="string"&&(u.bucket=c.bucket.trim()),typeof c.prefix=="string"&&(u.prefix=c.prefix.trim()),typeof c.region=="string"&&(u.region=c.region.trim()),typeof c.htmlCacheControl=="string"&&(u.htmlCacheControl=c.htmlCacheControl.trim()),typeof c.assetCacheControl=="string"&&(u.assetCacheControl=c.assetCacheControl.trim()),Object.keys(u).length>0&&(s.s3=u);}if(a.cloudFront&&typeof a.cloudFront=="object"){let u={},c=a.cloudFront;typeof c.distributionId=="string"&&(u.distributionId=c.distributionId.trim()),Array.isArray(c.invalidationPaths)&&(u.invalidationPaths=c.invalidationPaths.map(d=>String(d??"").trim()).filter(d=>d.length>0)),Object.keys(u).length>0&&(s.cloudFront=u);}t[i]=s;}return t}function V(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function Ke(e,t){if(!e||typeof e!="object")return null;let n=e,r=n.command;if(r!=="publish"&&r!=="crawl"&&r!=="deploy"&&r!=="invalidate"&&r!=="retry-timeouts"&&r!=="url"&&r!=="content-sync")return null;let i=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(i)||i<1)return null;let a=String(n.id??`${r}-${t+1}`).trim();if(!a)return null;let s=String(n.deploymentProfile??"").trim(),o=String(n.url??"").trim(),u=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(d=>String(d??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],c=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(d=>String(d??"").trim()).filter(Boolean))]:[];return r==="content-sync"&&u.length===0?null:{id:a,enabled:n.enabled!==false,command:r,intervalMinutes:i,...r==="publish"||r==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(r==="publish"||r==="deploy"||r==="invalidate"||r==="content-sync")&&s?{deploymentProfile:s}:{},...o?{url:o}:{},...u.length>0?{postTypes:u}:{},...c.length>0?{listingPaths:c}:{},...typeof n.includeSubsites=="boolean"?{includeSubsites:n.includeSubsites}:{},...typeof n.includePostTypeArchives=="boolean"?{includePostTypeArchives:n.includePostTypeArchives}:{},...typeof n.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:n.includeTaxonomyArchives}:{},...typeof n.includeAuthorArchives=="boolean"?{includeAuthorArchives:n.includeAuthorArchives}:{},...typeof n.includeDateArchives=="boolean"?{includeDateArchives:n.includeDateArchives}:{},...typeof n.includePostsPage=="boolean"?{includePostsPage:n.includePostsPage}:{},...typeof n.includeSitemapChain=="boolean"?{includeSitemapChain:n.includeSitemapChain}:{}}}function ye(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((r,i)=>Ke(r,i)).filter(r=>!!r):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function ze(e){if(!e||typeof e!="object")return;let t=e,n={};for(let i of ["accountId","siteId"]){let a=t[i];typeof a=="string"&&a.trim()!==""&&(n[i]=a.trim());}let r=Number(t.lastUpdate??0);return Number.isFinite(r)&&r>0&&(n.lastUpdate=Math.floor(r)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function Y(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),r=String(t.siteId??"").trim(),i=t.subscriber===true,a=ze(t.siteSettings),s={...a??{},...n?{accountId:a?.accountId??n}:{},...r?{siteId:a?.siteId??r}:{},...a?.subscriber===true||i?{subscriber:true}:{}},o={},u=String(t.apiBase??"").trim();u&&(o.apiBase=u);let c=String(t.runtimeToken??t.nonce??"").trim();c&&(o.runtimeToken=c);let d=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();d&&(o.virtualAssetBaseUrl=d),Object.keys(s).length>0&&(o.siteSettings=s);let g=V(t.subscriptionType);return g&&(o.subscriptionType=g),o}function He(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function be(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function Ge(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[r,i]of new Headers(t.headers).entries())n.set(r,i);return n}async function Se(e,t,n=5){let r=new URL(be(e)),i=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),a=r.protocol==="http:"?Je:me,s=Ge(e,t);return await new Promise((o,u)=>{let c=a.request(r,{method:i,headers:Object.fromEntries(s.entries()),...r.protocol==="https:"?{rejectUnauthorized:false}:{}},d=>{let g=[];d.on("data",p=>{g.push(Buffer.isBuffer(p)?p:Buffer.from(p));}),d.on("error",u),d.on("end",()=>{let p=d.statusCode??0,h=d.headers.location;if(n>0&&h&&[301,302,303,307,308].includes(p)){o(Se(new URL(h,r),{method:p===303?"GET":i},n-1));return}let y=new Headers;for(let[l,b]of Object.entries(d.headers))Array.isArray(b)?y.set(l,b.join(", ")):typeof b=="string"&&y.set(l,b);o(new Response(Buffer.concat(g),{status:p,statusText:d.statusMessage??"",headers:y}));});});c.on("error",u),c.end();})}function Ve(e){let t=Y(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},r=String(n.accountId??"").trim(),i=String(n.siteId??"").trim(),a=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...a?{virtualAssetBaseUrl:a}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!r||!i||!a)return false;He(e.sourceOrigin);let s=globalThis,u={...s.WpSuite??{},siteSettings:n,uploadUrl:a};return t.apiBase&&(u.apiBase=t.apiBase),s.WpSuite=u,true}async function Ye(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!Ve(e)){let i=e.wpsuite?.siteSettings,a=[String(i?.accountId??"").trim()?"":"accountId",String(i?.siteId??"").trim()?"":"siteId",t?"":"virtualAssetBaseUrl"].filter(Boolean);return {remote:null,diagnostic:{status:"invalid-runtime",virtualAssetBaseUrl:t,subscriptionType:null,error:`Missing WP Suite runtime field(s): ${a.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,r=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(u,c)=>{let d=be(u);if(d.startsWith(t)){let g=(()=>{try{return new URL(d).pathname}catch{return d}})();try{let p=e.ignoreHttpsErrors&&d.startsWith("https://")?await Se(u,c):await n(u,c);return r.push({path:g,status:p.status,ok:p.ok,error:null}),p}catch(p){throw r.push({path:g,status:null,ok:!1,error:p instanceof Error?p.message:String(p)}),p}}return n(u,c)}));let{getConfig:i}=await import('@smart-cloud/wpsuite-core'),a=await i("publisher"),s=a&&typeof a=="object"?a:null,o=V(s?.subscriptionType);return {remote:s,diagnostic:{status:s?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:o??null,error:s?null:"WP Suite publisher config loader returned no configuration.",requests:r}}}catch(i){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:i instanceof Error?i.message:String(i),requests:r}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function Ze(e,t){let n=_e(t?.deploymentProfiles),r=String(t?.defaultDeploymentProfile??"").trim(),i=n[r]?r:"",a=V(t?.subscriptionType),s=Y(e.wpsuite);return {...e,scheduler:ye(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:i,...a?{subscriptionType:a}:{},wpsuite:{...s,...s.siteSettings||a?{siteSettings:{...s.siteSettings??{},...s.siteSettings?.subscriber===true||a==="PROFESSIONAL"||a==="AGENCY"?{subscriber:true}:{}}}:{},...a?{subscriptionType:a}:{}}}}function G(e,t){let r=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!r)return t;let i=r.split("/").map(a=>a.trim()).filter(a=>a.length>0&&a!=="."&&a!=="..");return i.length>0?i.join("/"):t}function Xe(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?m.resolve(e):""}function he(e,t,n){let r=String(t||"").trim();return r&&m.isAbsolute(r)?m.resolve(r):m.resolve(e,G(r,n))}async function Z(e,t={}){let n=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",r=await P.readFile(n,"utf8"),i=JSON.parse(r);i.sourceOrigin=i.sourceOrigin.replace(/\/$/,""),i.targetOrigin=fe(i.targetOrigin),i.ignoreHttpsErrors??=false,i.outputDir=String(i.outputDir||"export").trim()||"export",i.urlRewriteMode||=i.targetOrigin==="."?"relative":"absolute",i.noJavaScriptRenderPathPrefixes||=[],i.seedPaths||=[],i.generated404RequestPath=Ne(i.generated404RequestPath),i.sitemapPaths||=["/sitemap_index.xml","/sitemap.xml"],i.allowedAssetHosts||=[],i.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],i.blockedPathPrefixes||=[],i.blockedSearchFragments||=[],i.concurrency||=1,i.maxPages||=0,i.extraReplacements=H(i.extraReplacements),i.postCrawlCopyMap=H(i.postCrawlCopyMap),i.logDir=String(i.logDir||"logs").trim()||"logs",i.verbose??=false,i.logLevel||=i.verbose?"debug":"info",i.s3SyncMode||="sdk-upload-delete",i.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},i.readiness.timeoutMs??=1500,i.readiness.fallbackWaitMs??=1500,i.viewport||={width:1440,height:1200},i.navigationTimeoutMs||=3e4,i.assetDownloadConcurrency=Number(i.assetDownloadConcurrency)>0?Number(i.assetDownloadConcurrency):i.concurrency,i.rewriteConcurrency=Number(i.rewriteConcurrency)>0?Number(i.rewriteConcurrency):i.assetDownloadConcurrency,i.wpsuite=Y(i.wpsuite),i.scheduler=ye(void 0),i.deploymentProfiles={},i.defaultDeploymentProfile="",i.deploymentTargetOverride=String(i.deploymentTargetOverride??"").trim();let a=await Ye(i);t.onRemotePublisherConfigDiagnostic?.(a.diagnostic);let s=Ze(i,a.remote),o=Xe(),u=o?m.resolve(o,".."):"";return u?(s.outputDir=he(u,s.outputDir,"export"),s.logDir=he(u,s.logDir,"logs")):(m.isAbsolute(s.outputDir)||(s.outputDir=G(s.outputDir,"export")),m.isAbsolute(s.logDir)||(s.logDir=G(s.logDir,"logs"))),s}function Ce(e){let t=String(e.command??"").trim();return (t==="publish"||t==="crawl")&&e.crawlMode==="incremental"||t==="content-sync"}var X=new Map;async function we(e){let t=m.resolve(e),n=X.get(t);if(n!==void 0)return n;try{let r=JSON.parse(await P.readFile(t,"utf8")),i=String(r.version??"").trim();return X.set(t,i),i}catch{return X.set(t,""),""}}var B=class extends Error{request;step;constructor(t,n){super(`Stop requested during ${n}.`),this.name="StopRequestedError",this.request=t,this.step=n;}},st="queue-mutation.lock",ot=5e3,at=3e4;function ut(e){let t=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",n=process.env.STATIC_PUBLISHER_EXPORTER_DIR||process.cwd(),r=process.env.PUBLISHER_CONFIG||"",i=1;for(let o=0;o<e.length;o++){let u=e[o];u==="--runtime-dir"?t=e[++o]||"":u.startsWith("--runtime-dir=")?t=u.slice(14):u==="--exporter-dir"?n=e[++o]||n:u.startsWith("--exporter-dir=")?n=u.slice(15):u==="--config"?r=e[++o]||"":u.startsWith("--config=")?r=u.slice(9):u==="--max-jobs"?i=Number.parseInt(e[++o]||"1",10):u.startsWith("--max-jobs=")&&(i=Number.parseInt(u.slice(11),10));}if(!t)throw new Error("Missing runtime dir. Use --runtime-dir or STATIC_PUBLISHER_RUNTIME_DIR.");let a=m.resolve(t),s=r?m.resolve(r):m.join(a,"config.json");return {runtimeDir:a,exporterDir:m.resolve(n),configPath:s,maxJobs:Number.isFinite(i)&&i>0?i:1}}async function v(e,t){try{let n=await P.readFile(e,"utf8");return JSON.parse(n)}catch(n){if((n&&typeof n=="object"&&"code"in n?String(n.code||""):"")!=="ENOENT"){let i=n instanceof Error?n.message:String(n);console.warn(`[queue-runner] failed to read JSON ${e}: ${i}`);}return t}}async function w(e,t){await P.mkdir(m.dirname(e),{recursive:true}),await P.writeFile(e,JSON.stringify(t,null,2),"utf8");}function Ae(e){return m.join(e,st)}async function ct(e){await new Promise(t=>setTimeout(t,e));}async function lt(e){let t=Ae(e),n=Date.now()+ot;for(;;)try{await P.mkdir(m.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()},null,2),{encoding:"utf8",flag:"wx"});return}catch(r){if((r&&typeof r=="object"&&"code"in r?String(r.code||""):"")!=="EEXIST")throw r;let a=await P.stat(t).catch(()=>null);if(a&&Date.now()-a.mtimeMs>at){await P.unlink(t).catch(()=>{});continue}if(Date.now()>=n)throw new Error("Timed out acquiring queue mutation lock.",{cause:r});await ct(50);}}async function dt(e){await P.unlink(Ae(e)).catch(()=>{});}async function E(e,t){await lt(e);try{return await t()}finally{await dt(e);}}function Ie(e){return m.join(e,"queue-runner-heartbeat.json")}function ae(e){return m.join(e,"current-progress.json")}function ee(e){return m.join(e,"scheduler-state.json")}function gt(e,t){let r=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!r)return t;let i=r.split("/").map(a=>a.trim()).filter(a=>a.length>0&&a!=="."&&a!=="..");return i.length>0?i.join("/"):t}async function Re(e){let t=await v(e.configPath||"",null),n=m.resolve(e.runtimeDir,".."),i=(typeof t?.logDir=="string"?t.logDir:"").trim();return i&&m.isAbsolute(i)?m.resolve(i):m.resolve(n,gt(i,"logs"))}function te(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||t}function pt(e){let t=e?new Date(e):new Date;return (Number.isNaN(t.getTime())?new Date:t).toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function mt(e){return [pt(e.endedAt||e.startedAt),te(e.command||"job","job"),te(e.id||"job","job"),te(e.status||"finished","finished")].join("-")}function ht(e){return e.endsWith(".log.jsonl")||e.endsWith(".errors.jsonl")||e.endsWith(".rejected.jsonl")?true:["current-crawl-event.json","rejected.jsonl","ignored.jsonl","skipped-http.jsonl","errors.jsonl","timings.jsonl","rejected.json","ignored.json","skipped-http.json","errors.json","timings.json"].includes(e)}function ft(e){return e==="errors.json"||e==="errors.jsonl"||e.endsWith(".errors.jsonl")?"errors":e==="ignored.json"||e==="ignored.jsonl"?"ignored":e==="rejected.json"||e==="rejected.jsonl"||e.endsWith(".rejected.jsonl")?"rejected":e==="skipped-http.json"||e==="skipped-http.jsonl"?"skipped-http":e==="timings.json"||e==="timings.jsonl"?"timings":e==="current-progress.json"?"current-progress":e==="current-crawl-event.json"?"current-crawl-event":e.endsWith(".log.jsonl")?e.replace(/\.log\.jsonl$/i,"-log"):e.replace(/\.[^.]+$/u,"")||"artifact"}function yt(e){return e.endsWith(".gz")?"application/gzip":e.endsWith(".jsonl")?"application/x-ndjson":e.endsWith(".json")?"application/json":"text/plain"}async function ne(e,t,n){let r=`${n}.gz`,i=m.join(t,r);await pipeline(createReadStream(e),createGzip({level:9}),createWriteStream(i));let[a,s]=await Promise.all([P.stat(e),P.stat(i)]);return {role:ft(n),originalFileName:n,storedFileName:r,compressed:true,compression:"gzip",contentType:yt(r),originalSize:a.size,storedSize:s.size}}async function $(e,t){let n=await Re(t),r=new Date().toISOString(),i=mt(e),a=m.join(n,"archive",i),s=[],o=[];await P.mkdir(a,{recursive:true});try{let d=await P.readdir(n,{withFileTypes:!0});for(let g of d){if(!g.isFile()||!ht(g.name))continue;let p=await ne(m.join(n,g.name),a,g.name);o.push(p),s.push(p.storedFileName);}}catch(d){if((d&&typeof d=="object"&&"code"in d?String(d.code||""):"")!=="ENOENT")throw d}let u=ae(t.runtimeDir);if(existsSync(u)){let d=await ne(u,a,"current-progress.json");o.push(d),s.push(d.storedFileName);}if(e.command==="content-sync")for(let d of ["content-sync-current.json","content-sync-impact-plan.json","content-sync-checkpoint.json","content-sync-state.json","content-sync-invalidation.json","deploy-plan.json"]){let g=m.join(t.runtimeDir,d);if(!existsSync(g))continue;let p=await ne(g,a,d);o.push(p),s.push(p.storedFileName);}let c=[...s,"job.json"];return await w(m.join(a,"job.json"),{manifestVersion:1,archivedAt:r,archiveKey:i,archiveDir:a,logDir:n,runtimeDir:t.runtimeDir,exporterDir:t.exporterDir,configPath:t.configPath||"",archivedFiles:c,artifacts:o,job:e}),{archiveKey:i,archiveDir:a,archiveCreatedAt:r,archivedFiles:c,artifacts:o}}function bt(e){return m.join(e,"audit-events.jsonl")}function se(e){return m.join(e,"stop-request.json")}async function qe(e){try{let t=await P.readFile(se(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}async function ve(e,t){let n=await qe(e);if(!n)return null;let r=String(n.targetJobId||"").trim();return r&&r!==t?null:n}async function O(e,t){if(!t){await P.unlink(se(e)).catch(()=>{});return}let n=await qe(e);if(!n)return;let r=String(n.targetJobId||"").trim();(!r||r===t)&&await P.unlink(se(e)).catch(()=>{});}async function I(e,t){try{let n={occurredAt:t.occurredAt||new Date().toISOString(),status:t.status||"info",actorSource:t.actorSource||"queue-runner",...t};await P.mkdir(e,{recursive:!0}),await P.appendFile(bt(e),`${JSON.stringify(n)}
2
+ `,"utf8");}catch{}}async function C(e,t,n){let[r,i]=await Promise.all([we(m.join(e.exporterDir,"package.json")),we(m.join(e.exporterDir,"node_modules","@smart-cloud","wpsuite-core","package.json"))]),a={checkedAt:new Date().toISOString(),status:t,pid:process.pid,nodePath:process.execPath,nodeVersion:process.version,exporterVersion:r,wpsuiteCoreVersion:i,runtimeDir:e.runtimeDir,exporterDir:e.exporterDir,...n??{}};try{await w(Ie(e.runtimeDir),a);}catch{}}async function L(e){try{await P.unlink(ae(e));}catch{}}function St(e,t){let n=e.command;if(n!=="publish"&&n!=="crawl"&&n!=="deploy"&&n!=="invalidate"&&n!=="retry-timeouts"&&n!=="url"&&n!=="content-sync")return null;let r=Number.parseInt(String(e.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let i=(e.id||`${n}-${t+1}`).trim();if(!i)return null;let a=e.enabled!==false,s=typeof e.url=="string"?e.url.trim():"",o=typeof e.deploymentProfile=="string"?e.deploymentProfile.trim():"",u=Array.isArray(e.postTypes)?[...new Set(e.postTypes.map(g=>String(g).trim()).filter(Boolean))]:[],c=Array.isArray(e.listingPaths)?[...new Set(e.listingPaths.map(g=>String(g).trim()).filter(Boolean))]:[],d=(n==="publish"||n==="crawl")&&e.crawlMode==="incremental"?"incremental":"full";return n==="url"&&!s||n==="content-sync"&&u.length===0?null:{id:i,enabled:a,command:n,intervalMinutes:r,...n==="publish"||n==="crawl"?{crawlMode:d}:{},...(n==="publish"||n==="deploy"||n==="invalidate"||n==="content-sync")&&o?{deploymentProfile:o}:{},...s?{url:s}:{},...u.length>0?{postTypes:u}:{},...c.length>0?{listingPaths:c}:{},...typeof e.includeSubsites=="boolean"?{includeSubsites:e.includeSubsites}:{},...typeof e.includePostTypeArchives=="boolean"?{includePostTypeArchives:e.includePostTypeArchives}:{},...typeof e.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:e.includeTaxonomyArchives}:{},...typeof e.includeAuthorArchives=="boolean"?{includeAuthorArchives:e.includeAuthorArchives}:{},...typeof e.includeDateArchives=="boolean"?{includeDateArchives:e.includeDateArchives}:{},...typeof e.includePostsPage=="boolean"?{includePostsPage:e.includePostsPage}:{},...typeof e.includeSitemapChain=="boolean"?{includeSitemapChain:e.includeSitemapChain}:{}}}async function wt(e){let t=await Z(e.configPath).catch(()=>null),n=t?.scheduler,r=Array.isArray(n?.rules)?n.rules.map((i,a)=>St(i,a)).filter(i=>!!i):[];return {enabled:!!n?.enabled,timezone:typeof n?.timezone=="string"&&n.timezone.trim()?n.timezone.trim():"UTC",rules:r,wpsuite:t?.wpsuite,publisherConfig:t}}function re(e,t){if(!t)throw new Error("Content-sync scheduler requires a valid publisher config.");let n=M({postTypes:e.postTypes??[],listingPaths:e.listingPaths??[],includeSubsites:e.includeSubsites,includePostTypeArchives:e.includePostTypeArchives,includeTaxonomyArchives:e.includeTaxonomyArchives,includeAuthorArchives:e.includeAuthorArchives,includeDateArchives:e.includeDateArchives,includePostsPage:e.includePostsPage,includeSitemapChain:e.includeSitemapChain}),r=_(t.sourceOrigin,e.id,n),i=z(t,e.deploymentProfile),a=K({sourceOrigin:t.sourceOrigin,targetOrigin:i.config.targetOrigin,deploymentProfile:i.name||"",s3Bucket:i.config.s3.bucket,s3Prefix:i.config.s3.prefix,cloudFrontDistributionId:i.config.cloudFront.distributionId,urlRewriteMode:i.config.urlRewriteMode,extraReplacements:i.profile?.extraReplacements??{}});return `content-sync:${e.id}:${J({scopeFingerprint:r,targetFingerprint:a}).slice(0,32)}`}async function vt(e,t,n,r,i){let s=(await v(m.join(e.runtimeDir,"content-sync-baseline.json"),{})).entries?.[r];if(!s?.consumerId||!s.scopeFingerprint||!s.baselineId)return {status:"baseline-required",reason:"No verified normal-release baseline exists for this rule scope."};try{let o=t.publisherConfig;if(!o)throw new Error("Publisher configuration is unavailable.");let u=M({postTypes:n.postTypes??[],listingPaths:n.listingPaths??[],includeSubsites:n.includeSubsites,includePostTypeArchives:n.includePostTypeArchives,includeTaxonomyArchives:n.includeTaxonomyArchives,includeAuthorArchives:n.includeAuthorArchives,includeDateArchives:n.includeDateArchives,includePostsPage:n.includePostsPage,includeSitemapChain:n.includeSitemapChain}),c=_(o.sourceOrigin,n.id,u),d=z(o,n.deploymentProfile),g=K({sourceOrigin:o.sourceOrigin,targetOrigin:d.config.targetOrigin,deploymentProfile:d.name||"",s3Bucket:d.config.s3.bucket,s3Prefix:d.config.s3.prefix,cloudFrontDistributionId:d.config.cloudFront.distributionId,urlRewriteMode:d.config.urlRewriteMode,extraReplacements:d.profile?.extraReplacements??{}});if(s.scopeFingerprint!==c||s.targetFingerprint!==g||!s.releaseFingerprint)return {status:"baseline-required",reason:"The verified content-sync baseline does not match the active scope or deployment target. Run a successful full or incremental publish to establish a new baseline."};let p=new U({sourceOrigin:o.sourceOrigin,runtimeToken:String(o.wpsuite?.runtimeToken||""),ignoreHttpsErrors:o.ignoreHttpsErrors}),h=await p.releaseFingerprint(u.includeSubsites),y=de({wordpressFingerprint:h,targetFingerprint:g,sourceOrigin:o.sourceOrigin,sitemapPaths:o.sitemapPaths,blockedPathPrefixes:o.blockedPathPrefixes,assetPathPrefixes:o.assetPathPrefixes,noJavaScriptRenderPathPrefixes:o.noJavaScriptRenderPathPrefixes,urlRewriteMode:o.urlRewriteMode});if(s.releaseFingerprint!==y)return {status:"baseline-required",reason:"The installed WordPress release changed after the last verified content-sync baseline. Run a successful full or incremental publish to establish a new baseline."};let l=await p.head({consumerId:s.consumerId,scopeFingerprint:s.scopeFingerprint,baselineId:s.baselineId,postTypes:u.postTypes,includeSubsites:u.includeSubsites}),b=l.committedSequence;if(i?.command==="content-sync"&&i.coalesceKey===r){let S=await v(m.join(e.runtimeDir,"content-sync-current.json"),null);S?.coalesceKey===r&&Number.isSafeInteger(S.toSequence)&&(b=Math.max(b,Number(S.toSequence)));}return {status:l.headSequence>b?"pending":"current",headSequence:l.headSequence,committedSequence:l.committedSequence}}catch(o){return o instanceof k&&o.code==="baseline-required"?{status:"baseline-required",reason:o.message}:{status:"unavailable",reason:o instanceof Error?o.message:String(o)}}}async function De(e,t,n,r,i,a){let s=m.join(e.runtimeDir,"content-sync-state.json"),u=(await v(s,{})).rules??{},c=u[n]??{};u[n]={...c,ruleId:t,coalesceKey:n,...Number.isSafeInteger(i)?{observedHeadSequence:i}:{},...Number.isSafeInteger(a)?{committedSequence:a}:{},retryAttempt:0,nextRetryAt:null,lastError:r,baselineStatus:"required",baselineReason:r,trailingWorkDetected:Number.isSafeInteger(i)&&Number.isSafeInteger(a)?Number(i)>Number(a):!!c.trailingWorkDetected},await w(s,{schemaVersion:1,updatedAt:new Date().toISOString(),rules:u});}function oe(e,t){let n=(t.url||"").trim(),r=t.crawlMode||"full",i=(t.deploymentProfile||"").trim(),a=(t.coalesceKey||"").trim();return e.some(s=>s.command===t.command&&(t.command!=="content-sync"||(s.coalesceKey||"").trim()===a)&&(s.url||"").trim()===n&&(s.crawlMode||"full")===r&&(s.deploymentProfile||"").trim()===i&&(s.status===void 0||s.status==="queued"||s.status==="retry-wait"||s.status==="running"))}async function Pt(e,t,n){if(!t.allowSchedulerAutoEnqueue)return 0;let r=await wt(e);if(!r.enabled||r.rules.length===0)return 0;if(t.assertActiveSubscriptionForIdentity)try{await t.assertActiveSubscriptionForIdentity(r.wpsuite??null);}catch(l){let b=l instanceof Error?l.message:String(l);return console.warn(`[queue-runner] scheduler auto-enqueue skipped: ${b}`),0}let i=m.join(e.runtimeDir,"queue.json"),a=m.join(e.runtimeDir,"current-run.json"),s=Date.now(),o=0,u=[],c=[],d=[],g=new Map,[p,h,y]=await Promise.all([v(i,[]),v(a,null),v(ee(e.runtimeDir),{lastEnqueuedBucketByRuleId:{},lastEvaluatedBucketByRuleId:{},lastCreatedBucketByRuleId:{},coalescedCountByRuleId:{}})]);for(let l of r.rules){if(!l.enabled||l.command!=="content-sync")continue;let b=Math.floor(s/(l.intervalMinutes*60*1e3)),S=y.lastEvaluatedBucketByRuleId?.[l.id]??y.lastEnqueuedBucketByRuleId?.[l.id]??-1;if(b<=S)continue;let D=re(l,r.publisherConfig);oe(p,{command:l.command,deploymentProfile:l.deploymentProfile,coalesceKey:D})||g.set(l.id,await vt(e,r,l,D,h));}await E(e.runtimeDir,async()=>{let l=await v(i,[]),b=await v(a,null),S=await v(ee(e.runtimeDir),{lastEnqueuedBucketByRuleId:{},lastEvaluatedBucketByRuleId:{},lastCreatedBucketByRuleId:{},coalescedCountByRuleId:{}});S.lastEnqueuedBucketByRuleId??={},S.lastEvaluatedBucketByRuleId??={...S.lastEnqueuedBucketByRuleId},S.lastCreatedBucketByRuleId??={...S.lastEnqueuedBucketByRuleId},S.coalescedCountByRuleId??={};let D=[...l];b&&b.status==="running"&&D.unshift(b);for(let f of r.rules){if(!f.enabled)continue;let A=f.intervalMinutes*60*1e3,q=Math.floor(s/A),F=S.lastEvaluatedBucketByRuleId[f.id]??S.lastEnqueuedBucketByRuleId[f.id]??-1;if(q<=F)continue;let j=f.command==="content-sync"?re(f,r.publisherConfig):"";S.lastEvaluatedBucketByRuleId[f.id]=q;let T=f.command==="content-sync"?l:D;if(oe(T,{command:f.command,url:f.url,crawlMode:f.crawlMode,deploymentProfile:f.deploymentProfile,coalesceKey:j})){S.coalescedCountByRuleId[f.id]=(S.coalescedCountByRuleId[f.id]??0)+1,c.push(f);continue}if(f.command==="content-sync"){let W=g.get(f.id);if(!W||W.status!=="pending"){let ce=W??{status:"unavailable",reason:"Content-sync demand was not checked."};ce.status!=="current"&&d.push({rule:f,check:ce});continue}}let Q={id:randomUUID(),command:f.command,...f.command==="content-sync"?{ruleId:f.id,coalesceKey:j,attempt:0}:{},...(f.command==="publish"||f.command==="crawl")&&f.crawlMode?{crawlMode:f.crawlMode}:{},...(f.command==="publish"||f.command==="deploy"||f.command==="invalidate"||f.command==="content-sync")&&f.deploymentProfile?{deploymentProfile:f.deploymentProfile}:{},...f.url?{url:f.url}:{},enqueueSource:"scheduler",...r.wpsuite?{wpsuite:r.wpsuite}:{},status:"queued",createdAt:new Date().toISOString(),createdBy:0};l.push(Q),D.push(Q),u.push({job:Q,rule:f}),S.lastEnqueuedBucketByRuleId[f.id]=q,S.lastCreatedBucketByRuleId[f.id]=q,o+=1;}o>0&&await w(i,l),await w(ee(e.runtimeDir),S);});for(let l of u){if(l.rule.command==="content-sync"){let b=g.get(l.rule.id);await I(e.runtimeDir,{eventType:"content-sync-demand-detected",status:"queued",actorSource:"queue-runner-scheduler",jobId:l.job.id,command:l.job.command,message:"Pending journal changes require a content-sync job.",details:{ruleId:l.rule.id,headSequence:b?.headSequence??0,committedSequence:b?.committedSequence??0}});}await I(e.runtimeDir,{eventType:"job-created",status:"queued",actorSource:"queue-runner-scheduler",jobId:l.job.id,command:l.job.command,message:"Scheduler auto-enqueued a job.",details:{ruleId:l.rule.id,intervalMinutes:l.rule.intervalMinutes,timezone:r.timezone,deploymentProfile:l.rule.deploymentProfile||"",url:l.rule.url||""}});}for(let l of c)await I(e.runtimeDir,{eventType:"content-sync-coalesced",status:"queued",actorSource:"queue-runner-scheduler",command:l.command,message:"Scheduler demand was coalesced into an existing content-sync job.",details:{ruleId:l.id}});for(let l of d){if(l.check.status==="baseline-required"){let b=re(l.rule,r.publisherConfig);await De(e,l.rule.id,b,l.check.reason||"A successful full or incremental publish must establish a new content-sync baseline.",l.check.headSequence,l.check.committedSequence);}await I(e.runtimeDir,{eventType:l.check.status==="baseline-required"?"content-sync-baseline-required":"content-sync-demand-check-failed",status:l.check.status==="unavailable"?"failed":"info",actorSource:"queue-runner-scheduler",command:"content-sync",message:l.check.reason||"The content-sync consumer is already at the current journal head.",details:{ruleId:l.rule.id,headSequence:l.check.headSequence??0,committedSequence:l.check.committedSequence??0}});}return o}async function Ct(e){let t={pid:process.pid,startedAt:new Date().toISOString()};await P.writeFile(e,JSON.stringify(t,null,2),{encoding:"utf8",flag:"wx"});}async function At(e){try{await P.unlink(e);}catch{}}function It(e,t){let n=[m.join(e,"dist",`${t}.js`),m.join(e,`${t}.js`)];for(let r of n)if(existsSync(r))return r;throw new Error(`Cannot find ${t}.js in ${m.join(e,"dist")} or ${e}`)}async function R(e,t,n,r,i,a,s){if(s){let c=await ve(t,s);if(c)throw new B(c,n)}let o=It(e,n),u={...process.env,...a??{}};return u.STATIC_PUBLISHER_RUNTIME_DIR=t,i&&(u.PUBLISHER_CONFIG=i),await new Promise((c,d)=>{let g=null,p=null,h=null,y=null,l=false,b="",S=spawn(process.execPath,[o,...r],{cwd:e,env:u,stdio:["inherit","inherit","pipe"]});S.stderr?.on("data",A=>{b+=A.toString("utf8");});let D=()=>{p&&clearInterval(p),h&&clearInterval(h),y&&clearTimeout(y);},f=async()=>{if(!(!s||g||l)){l=true;try{let A=await ve(t,s);if(!A)return;g=A,S.kill("SIGTERM"),y=setTimeout(()=>{S.kill("SIGKILL");},1e4);}finally{l=false;}}};s&&(p=setInterval(()=>{f();},1e3),h=setInterval(()=>{(async()=>{let A=Ie(t),q=await v(A,{});await w(A,{...q,checkedAt:new Date().toISOString(),status:"running",currentJobId:s||q.currentJobId||"",currentStep:n});})().catch(()=>{});},15e3)),S.on("error",A=>{D(),d(A);}),S.on("close",(A,q)=>{D();let F=pe(b).trim();if(F&&process.stderr.write(`${F}
3
+ `),g){d(new B(g,n));return}if(A===0)c();else {let j=F.split(/\r?\n/).map(T=>T.trim()).find(T=>T&&!T.startsWith("at "));d(new Error(`${n} exited with code ${A??-1}${q?` (signal ${q})`:""}${j?`: ${j}`:""}`));}});}),0}function Rt(e){let t=e.awsTempCreds;if(!t)return {};let n={};return typeof t.accessKeyId=="string"&&t.accessKeyId.trim()!==""&&(n.AWS_ACCESS_KEY_ID=t.accessKeyId.trim()),typeof t.secretAccessKey=="string"&&t.secretAccessKey.trim()!==""&&(n.AWS_SECRET_ACCESS_KEY=t.secretAccessKey.trim()),typeof t.sessionToken=="string"&&t.sessionToken.trim()!==""&&(n.AWS_SESSION_TOKEN=t.sessionToken.trim()),n}async function qt(e,t){let n=s=>{if(!s||typeof s!="object")return null;let o=s,u={...o.siteSettings??{},...String(o.accountId??"").trim()&&!o.siteSettings?.accountId?{accountId:String(o.accountId).trim()}:{},...String(o.siteId??"").trim()&&!o.siteSettings?.siteId?{siteId:String(o.siteId).trim()}:{},...o.siteSettings?.subscriber===true||o.subscriber===true?{subscriber:true}:{}},c={...String(o.apiBase??"").trim()?{apiBase:String(o.apiBase).trim()}:{},...String(o.runtimeToken??o.nonce??"").trim()?{runtimeToken:String(o.runtimeToken??o.nonce).trim()}:{},...String(o.virtualAssetBaseUrl??o.uploadUrl??"").trim()?{virtualAssetBaseUrl:String(o.virtualAssetBaseUrl??o.uploadUrl).trim()}:{},...Object.keys(u).length>0?{siteSettings:u}:{},...o.subscriptionType?{subscriptionType:o.subscriptionType}:{}};return Object.keys(c).length>0?c:null},r=await Z(t.configPath).catch(()=>null),i=n(r?.wpsuite);if(i)return i;let a=n(e.wpsuite);return a||null}async function Dt(e,t){return await qt(e,t)}function ue(e){let t={...e,status:"queued"};return delete t.startedAt,delete t.endedAt,delete t.exitCode,delete t.error,delete t.stopRequestedAt,delete t.stopRequestedByUserId,delete t.stopRequestedByLogin,delete t.stopMode,delete t.stoppedStep,t}async function xt(e,t){let n=await v(ae(e.runtimeDir),null),r=n&&n.details&&typeof n.details.phase=="string"?n.details.phase.trim():"";if(r)return r;let i=n&&typeof n.currentStep=="string"?n.currentStep.trim():"";if(i)return i;let a=await Re(e).catch(()=>"");if(a){let s=await v(m.join(a,"current-crawl-event.json"),null),o=s&&typeof s.currentStep=="string"?s.currentStep.trim():"";if(o)return o}return t}function Tt(e,t){if((e.command==="publish"||e.command==="crawl")&&t==="rewrite-text")return "rewrite-text"}async function kt(e){let t=m.join(e.runtimeDir,"queue.json"),n=m.join(e.runtimeDir,"current-run.json"),r=await E(e.runtimeDir,async()=>{let i=await v(n,null);if(!i||i.status!=="running"&&i.status!=="queued")return null;let a=await v(t,[]),s=Array.isArray(a)?a.filter(u=>u?.id!==i.id):[],o=ue(i);return await w(t,[o,...s]),await w(n,null),o});r&&(await O(e.runtimeDir,r.id),await I(e.runtimeDir,{eventType:"job-recovered",status:"queued",actorSource:"queue-runner",jobId:r.id,command:r.command,message:"Recovered stale current-run entry back into queue."}));}async function Et(e,t,n){try{if((n.shouldEnforceSubscriptionOnJobExecution?.(e)??n.enforceSubscriptionOnJobExecution)&&n.assertActiveSubscriptionForIdentity){let o=await Dt(e,t);await n.assertActiveSubscriptionForIdentity(o);}let i=Rt(e),a=e.resumeFromStep==="rewrite-text"?["--resume-rewrite"]:e.crawlMode==="incremental"?["--crawl-mode","incremental"]:[],s=e.deploymentProfile?["--profile",e.deploymentProfile]:[];if(e.command==="publish")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync-release-cutoff"}),await R(t.exporterDir,t.runtimeDir,"content-sync",["--capture-baseline-cutoffs",e.id],t.configPath,i,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await R(t.exporterDir,t.runtimeDir,"crawl",a,t.configPath,i,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await R(t.exporterDir,t.runtimeDir,"deploy",s,t.configPath,i,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await R(t.exporterDir,t.runtimeDir,"invalidate",s,t.configPath,i,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync-baseline"}),await R(t.exporterDir,t.runtimeDir,"content-sync",["--establish-baselines",e.id],t.configPath,i,e.id),{exitCode:0};if(e.command==="crawl")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await R(t.exporterDir,t.runtimeDir,"crawl",a,t.configPath,i,e.id),{exitCode:0};if(e.command==="deploy")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await R(t.exporterDir,t.runtimeDir,"deploy",s,t.configPath,i,e.id),{exitCode:0};if(e.command==="invalidate")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await R(t.exporterDir,t.runtimeDir,"invalidate",s,t.configPath,i,e.id),{exitCode:0};if(e.command==="retry-timeouts")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"retry-timeouts"}),await R(t.exporterDir,t.runtimeDir,"crawl",["--retry-timeouts"],t.configPath,i,e.id),{exitCode:0};if(e.command==="url"){let o=(e.url||"").trim();return o?(await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"url"}),await R(t.exporterDir,t.runtimeDir,"crawl",["--url",o],t.configPath,i,e.id),{exitCode:0}):{exitCode:2,error:"Missing url for command 'url'"}}return e.command==="content-sync"?!e.ruleId||!e.coalesceKey?{exitCode:2,error:"Content-sync queue jobs require ruleId and coalesceKey."}:(await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync"}),await R(t.exporterDir,t.runtimeDir,"content-sync",["--job-id",e.id],t.configPath,i,e.id),{exitCode:0}):{exitCode:2,error:`Unsupported command: ${e.command}`}}catch(r){return r instanceof B?{exitCode:130,error:"Job stop requested.",stopped:true,stopRequest:r.request,stoppedStep:r.step}:{exitCode:1,error:r instanceof Error?r.message:String(r)}}}function xe(e){return async function(n=process.argv.slice(2)){let r=ut(n),i=m.join(r.runtimeDir,"export.lock"),a=m.join(r.runtimeDir,"last-run.json");await L(r.runtimeDir),await C(r,"starting",{message:"queue-runner starting"});try{await Ct(i);}catch(s){if((s&&typeof s=="object"&&"code"in s?String(s.code||""):"")!=="EEXIST")throw s;console.log("[queue-runner] lock active, skipping"),await C(r,"lock-active",{message:"lock active, skipped this cron tick"});return}try{await kt(r);let s=await Pt(r,e),o=0;for(let u=0;u<r.maxJobs;u++){let c=await Ot(r,e);if(c==="none"||(o+=1,c==="stopped"))break}if(o===0)await L(r.runtimeDir),await C(r,"idle",{processedJobs:o,schedulerEnqueued:s,message:"no queued jobs"});else {await L(r.runtimeDir);let u=await v(a,null),c=String(u?.status||"").trim();await C(r,c==="success"?"job-success":c==="stopped"?"job-stopped":"job-failed",{processedJobs:o,schedulerEnqueued:s,lastJobId:u?.id,lastJobCommand:u?.command,lastJobStatus:u?.status,lastJobExitCode:u?.exitCode,lastJobError:u?.error,...c==="stopped"?{currentStep:u?.stoppedStep,stopRequestedAt:u?.stopRequestedAt,stopRequestedByLogin:u?.stopRequestedByLogin,stopRequestedMode:u?.stopMode,lastStoppedStep:u?.stoppedStep,message:u?.stopMode==="requeue"?`Job stopped during ${u?.stoppedStep||u?.command||"active step"} and requeued.`:`Job stopped during ${u?.stoppedStep||u?.command||"active step"} and left out of queue.`}:{}});}}catch(s){let o=s instanceof Error?s.message:String(s);throw await C(r,"error",{message:o}),await I(r.runtimeDir,{eventType:"queue-runner-error",status:"failed",actorSource:"queue-runner",message:"Unhandled queue-runner error.",details:{error:o}}),s}finally{await At(i);}}}async function Ft(e,t,n){let r=m.join(e.runtimeDir,"queue.json"),i=m.join(e.runtimeDir,"current-run.json");await E(e.runtimeDir,async()=>{let a=await v(r,[]),s=Array.isArray(a)?a.filter(c=>c?.id!==t.id):[],o=ue(t),u=Tt(t,n);u?o.resumeFromStep=u:delete o.resumeFromStep,await w(r,[o,...s]),await w(i,null);});}async function jt(e,t,n){let r=Math.max(0,t.attempt??0)+1,i=Math.min(3600*1e3,6e4*2**(r-1)),a=Math.floor(i*.2*Math.random()),s=new Date(Date.now()+i+a).toISOString(),o={...ue(t),status:"retry-wait",attempt:r,nextAttemptAt:s,error:n};if(await E(e.runtimeDir,async()=>{let u=m.join(e.runtimeDir,"queue.json"),c=m.join(e.runtimeDir,"current-run.json"),g=(await v(u,[])).filter(p=>p.id!==t.id);await w(u,[o,...g]),await w(c,null);}),t.coalesceKey){let u=m.join(e.runtimeDir,"content-sync-state.json"),d=(await v(u,{})).rules??{};d[t.coalesceKey]={...d[t.coalesceKey]??{},ruleId:t.ruleId||"",coalesceKey:t.coalesceKey,retryAttempt:r,nextRetryAt:s,lastError:n,trailingWorkDetected:true},await w(u,{schemaVersion:1,updatedAt:new Date().toISOString(),rules:d});}return o}async function Jt(e,t){if(!t.coalesceKey||!t.ruleId||!(await v(m.join(e.runtimeDir,"content-sync-state.json"),null))?.rules?.[t.coalesceKey]?.trailingWorkDetected)return null;let r=null;await E(e.runtimeDir,async()=>{let a=m.join(e.runtimeDir,"queue.json"),s=await v(a,[]);oe(s,{command:"content-sync",coalesceKey:t.coalesceKey,deploymentProfile:t.deploymentProfile})||(r={id:randomUUID(),command:"content-sync",ruleId:t.ruleId,coalesceKey:t.coalesceKey,deploymentProfile:t.deploymentProfile,enqueueSource:"scheduler",wpsuite:t.wpsuite,status:"queued",attempt:0,createdAt:new Date().toISOString(),createdBy:0},await w(a,[...s,r]));});let i=r;return i&&await I(e.runtimeDir,{eventType:"content-sync-trailing-job-created",status:"queued",actorSource:"queue-runner",jobId:i.id,command:i.command,message:"Content changes after the stable cutoff created one trailing job.",details:{predecessorJobId:t.id,ruleId:t.ruleId,coalesceKey:t.coalesceKey}}),i}async function Ot(e,t){let n=m.join(e.runtimeDir,"queue.json"),r=m.join(e.runtimeDir,"current-run.json"),i=m.join(e.runtimeDir,"last-run.json"),a=new Date().toISOString(),s=await E(e.runtimeDir,async()=>{let g=await v(n,[]);if(!Array.isArray(g)||g.length===0)return null;let p=Date.parse(String(g[0]?.nextAttemptAt||""));if(Number.isFinite(p)&&p>Date.now())return null;let h={...g[0],status:"running",startedAt:a};return delete h.nextAttemptAt,await w(n,g.slice(1)),await w(r,h),h});if(!s)return "none";await L(e.runtimeDir),await I(e.runtimeDir,{eventType:"job-run-started",status:"running",actorSource:"queue-runner",jobId:s.id,command:s.command,message:"Job execution started.",details:{createdAt:s.createdAt||"",startedAt:a,createdBy:s.createdBy??null,deploymentProfile:s.deploymentProfile||"",queuedWithTempAwsCreds:!!s.awsTempCreds}}),await C(e,"running",{currentJobId:s.id,currentJobCommand:s.command,currentStep:s.command});let o=await Et(s,e,t),u=new Date().toISOString();if(o.stopped){let g=await xt(e,o.stoppedStep||s.command),p=o.stopRequest?.mode==="requeue"?"requeue":"stop",h={...s,status:"stopped",endedAt:u,exitCode:o.exitCode,...o.error?{error:o.error}:{},stopRequestedAt:o.stopRequest?.requestedAt||"",stopRequestedByUserId:typeof o.stopRequest?.requestedByUserId=="number"?o.stopRequest.requestedByUserId:null,stopRequestedByLogin:o.stopRequest?.requestedByLogin||"",stopMode:p,stoppedStep:g};p==="requeue"?await Ft(e,s,g):await w(r,null);try{let y=await $(h,e);h.logArchiveDir=y.archiveDir,h.logArchiveCreatedAt=y.archiveCreatedAt,h.logArchiveFileCount=y.archivedFiles.length;}catch(y){h.logArchiveError=y instanceof Error?y.message:String(y);}return await w(i,h),await O(e.runtimeDir,s.id),await L(e.runtimeDir),await I(e.runtimeDir,{eventType:"job-run-stopped",status:"stopped",actorSource:"queue-runner",jobId:s.id,command:s.command,message:p==="requeue"?"Job stop requested and requeued.":"Job stop requested and removed from active execution without requeue.",details:{startedAt:s.startedAt||"",endedAt:u,deploymentProfile:s.deploymentProfile||"",stopMode:p,stopRequestedAt:o.stopRequest?.requestedAt||"",stopRequestedByLogin:o.stopRequest?.requestedByLogin||"",stopRequestedByUserId:typeof o.stopRequest?.requestedByUserId=="number"?o.stopRequest.requestedByUserId:null,stoppedStep:g,logArchiveKey:h.logArchiveError||!h.logArchiveDir?"":m.basename(h.logArchiveDir),logArchiveDir:h.logArchiveDir||"",logArchiveCreatedAt:h.logArchiveCreatedAt||"",logArchiveFileCount:h.logArchiveFileCount??0,logArchiveError:h.logArchiveError||""}}),"stopped"}if(s.command==="content-sync"&&o.exitCode!==0){if(/baseline (?:is missing or stale|required)|verified content-sync baseline|new baseline/i.test(o.error||"")){let y="The installed release no longer matches the verified content-sync baseline. Run a successful full or incremental publish to establish a new baseline.";s.ruleId&&s.coalesceKey&&await De(e,s.ruleId,s.coalesceKey,y);let l={...s,status:"failed",endedAt:u,exitCode:o.exitCode,error:y};try{let b=await $(l,e);l.logArchiveDir=b.archiveDir,l.logArchiveCreatedAt=b.archiveCreatedAt,l.logArchiveFileCount=b.archivedFiles.length;}catch(b){l.logArchiveError=b instanceof Error?b.message:String(b);}return await w(i,l),await O(e.runtimeDir,s.id),await I(e.runtimeDir,{eventType:"content-sync-baseline-required",status:"failed",actorSource:"queue-runner",jobId:s.id,command:s.command,message:y,details:{ruleId:s.ruleId||"",retryScheduled:false}}),"processed"}await I(e.runtimeDir,{eventType:"content-sync-failed",status:"failed",actorSource:"queue-runner",jobId:s.id,command:s.command,message:"Content-sync execution failed before cursor acknowledgement.",details:{attempt:s.attempt??0,error:o.error||"Content-sync execution failed."}});let p=await jt(e,s,o.error||"Content-sync execution failed."),h={...s,status:"retry-wait",endedAt:u,exitCode:o.exitCode,error:p.error,attempt:p.attempt,nextAttemptAt:p.nextAttemptAt};try{let y=await $(h,e);h.logArchiveDir=y.archiveDir,h.logArchiveCreatedAt=y.archiveCreatedAt,h.logArchiveFileCount=y.archivedFiles.length;}catch(y){h.logArchiveError=y instanceof Error?y.message:String(y);}return await w(i,h),await O(e.runtimeDir,s.id),await I(e.runtimeDir,{eventType:"content-sync-retry-scheduled",status:"retry-wait",actorSource:"queue-runner",jobId:s.id,command:s.command,message:"Content-sync retry was scheduled with bounded backoff.",details:{attempt:p.attempt??0,nextAttemptAt:p.nextAttemptAt||"",error:p.error||""}}),"processed"}let c={...s,status:o.exitCode===0?"success":"failed",endedAt:u,exitCode:o.exitCode,...o.error?{error:o.error}:{}};await w(r,null),c.status==="success"&&c.command==="content-sync"&&await Jt(e,c),await O(e.runtimeDir,s.id);try{let g=await $(c,e);c.logArchiveDir=g.archiveDir,c.logArchiveCreatedAt=g.archiveCreatedAt,c.logArchiveFileCount=g.archivedFiles.length;}catch(g){c.logArchiveError=g instanceof Error?g.message:String(g);}await w(i,c);let d=s.startedAt&&c.endedAt?Math.max(0,Math.round((new Date(c.endedAt).getTime()-new Date(s.startedAt).getTime())/1e3)):void 0;return await I(e.runtimeDir,{eventType:"job-run-finished",status:c.status==="success"?"success":"failed",actorSource:"queue-runner",jobId:c.id,command:c.command,message:c.status==="success"?"Job execution finished successfully.":"Job execution finished with failure.",details:{startedAt:s.startedAt||"",endedAt:c.endedAt||"",durationSec:d,deploymentProfile:c.deploymentProfile||"",exitCode:c.exitCode??null,error:c.error||"",logArchiveKey:c.logArchiveError||!c.logArchiveDir?"":m.basename(c.logArchiveDir),logArchiveDir:c.logArchiveDir||"",logArchiveCreatedAt:c.logArchiveCreatedAt||"",logArchiveFileCount:c.logArchiveFileCount??0,logArchiveError:c.logArchiveError||""}}),"processed"}async function Bt(e){if(!e)throw new Error("Missing remote WPSuite publisher state. Refresh the runtime config before running subscription-gated jobs.");if(e.subscriptionType!=="PROFESSIONAL"&&e.subscriptionType!=="AGENCY")throw new Error("This job requires an active WPSuite publisher subscription in the remote site configuration.")}var Mt={allowSchedulerAutoEnqueue:true,enforceSubscriptionOnJobExecution:false,shouldEnforceSubscriptionOnJobExecution:e=>Ce(e)||e.enqueueSource==="scheduler"||e.createdBy===0,assertActiveSubscriptionForIdentity:Bt},Te=xe(Mt),Ut=Te,wn=Te;process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href&&Ut().catch(e=>{console.error(e),process.exit(1);});export{wn as default,Ut as main,Te as runQueueRunner};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/publisher-exporter",
3
- "version": "1.1.46",
3
+ "version": "1.1.48",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Headless Playwright static publisher for WordPress/Elementor sites with sitemap-only page discovery, strict asset capture, escaped URL rewrite, structured logs, and targeted retry modes.",
@@ -23,6 +23,8 @@
23
23
  "scripts": {
24
24
  "prune": "npm ci --omit=dev",
25
25
  "build": "tsup --config tsup.config.ts",
26
+ "build:premium": "node scripts/build-premium.mjs",
27
+ "verify:premium": "node scripts/verify-premium-build.mjs",
26
28
  "check": "tsc -p tsconfig.json --noEmit",
27
29
  "lint": "eslint 'src/**/*.ts' --report-unused-disable-directives --max-warnings 0",
28
30
  "test": "node --test tests/*.test.mjs",
@@ -37,40 +39,44 @@
37
39
  "queue:drain": "node dist/queue-runner.js --max-jobs=100",
38
40
  "publish:site": "npm run build && npm run crawl && npm run deploy && npm run invalidate",
39
41
  "install:browsers": "playwright install chromium",
40
- "release:npm": "WPSUITE_PREMIUM=true npm run lint && npm run check && npm run build && npm publish --access=public --registry=https://registry.npmjs.org/"
42
+ "prepack": "npm run build:premium && npm run verify:premium",
43
+ "release:npm": "npm run lint && npm run check && npm test && npm publish --access=public --registry=https://registry.npmjs.org/"
41
44
  },
42
45
  "dependencies": {
43
- "@aws-sdk/client-cloudfront": "^3.1100.0",
44
- "@aws-sdk/client-s3": "^3.1100.0",
45
- "@aws-sdk/lib-storage": "^3.1100.0",
46
- "@smart-cloud/publisher-core": "^1.1.8",
47
- "@smart-cloud/wpsuite-core": "^2.3.2",
48
- "baseline-browser-mapping": "^2.11.12",
49
- "caniuse-lite": "^1.0.30001809",
46
+ "@aws-sdk/client-cloudfront": "^3.1127.0",
47
+ "@aws-sdk/client-s3": "^3.1127.0",
48
+ "@aws-sdk/lib-storage": "^3.1127.0",
49
+ "@smart-cloud/publisher-core": "^1.1.9",
50
+ "@smart-cloud/wpsuite-core": "^2.4.0",
51
+ "@wordpress/data": "^10.54.0",
52
+ "baseline-browser-mapping": "^2.11.21",
53
+ "caniuse-lite": "^1.0.30001810",
50
54
  "fast-glob": "^3.3.3",
51
- "jose": "^6.2.8",
55
+ "jose": "^6.2.12",
52
56
  "mime-types": "^3.0.2",
53
- "playwright": "^1.62.1"
57
+ "playwright": "^1.63.0",
58
+ "react": "18.3.1",
59
+ "react-dom": "18.3.1"
54
60
  },
55
61
  "devDependencies": {
56
62
  "@eslint/js": "^10.0.1",
57
63
  "@types/mime-types": "^3.0.1",
58
- "@types/node": "^26.1.2",
59
- "@typescript-eslint/eslint-plugin": "^8.65.0",
60
- "@typescript-eslint/parser": "^8.65.0",
61
- "esbuild": "^0.28.1",
62
- "eslint": "^10.8.0",
63
- "globals": "^17.8.0",
64
+ "@types/node": "^26.4.1",
65
+ "@typescript-eslint/eslint-plugin": "^8.69.0",
66
+ "@typescript-eslint/parser": "^8.69.0",
67
+ "esbuild": "^0.28.2",
68
+ "eslint": "^10.10.0",
69
+ "globals": "^17.12.0",
64
70
  "tsup": "^8.5.1",
65
71
  "typescript": "^6.0.3",
66
- "typescript-eslint": "^8.65.0"
72
+ "typescript-eslint": "^8.69.0"
67
73
  },
68
74
  "overrides": {
69
- "brace-expansion": "^5.0.8",
70
- "esbuild": "^0.28.1"
75
+ "brace-expansion": "^5.0.9",
76
+ "esbuild": "^0.28.2"
71
77
  },
72
78
  "resolutions": {
73
- "brace-expansion": "^5.0.8",
74
- "esbuild": "^0.28.1"
79
+ "brace-expansion": "^5.0.9",
80
+ "esbuild": "^0.28.2"
75
81
  }
76
82
  }