@smart-cloud/publisher-exporter 1.1.79 → 1.1.80

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.
package/README.md CHANGED
@@ -6,6 +6,14 @@ It is designed to run outside WordPress. The WordPress plugin only manages runti
6
6
 
7
7
  ## Release notes
8
8
 
9
+ ### 1.1.80
10
+
11
+ - Remove client-created top-level provider, portal, and overlay roots before serializing rendered HTML, including roots mounted through a bundled direct `react-dom/client` import that is not observable through `window.ReactDOM`.
12
+ - Ensure published pages run their parser-authored bootstrap and create fresh client providers instead of mistaking serialized, listener-free DOM for a live mount.
13
+ - Add a real headless Chromium regression test that reproduces the provider marker, captures the page, reloads the serialized HTML, and verifies successful provider reinitialization.
14
+
15
+ Upgrade both the external coordinator and delegated render-worker image to `1.1.80`, then rerender affected HTML pages. This is an exporter-only fix; no WordPress plugin update is required.
16
+
9
17
  ### 1.1.79
10
18
 
11
19
  - Let targeted content-sync trust pages already recorded in the verified baseline manifest even when the prior local render workspace has been cleaned up after a successful publish.
@@ -1,4 +1,4 @@
1
- import F,{readFile}from'fs/promises';import Xo from'http';import Nn from'https';import k from'path';import us,{createHash}from'crypto';import {request,chromium}from'playwright';import {gunzipSync}from'zlib';import {setTimeout as setTimeout$1}from'timers/promises';import Ci from'fast-glob';import js from'mime-types';import {availableParallelism}from'os';import {Worker}from'worker_threads';import {LambdaClient,InvokeCommand}from'@aws-sdk/client-lambda';import {DynamoDBClient,GetItemCommand}from'@aws-sdk/client-dynamodb';import {S3Client,GetObjectCommand,PutObjectCommand,CopyObjectCommand,ListObjectsV2Command,HeadObjectCommand,DeleteObjectsCommand}from'@aws-sdk/client-s3';import {fromTemporaryCredentials}from'@aws-sdk/credential-providers';import {Upload}from'@aws-sdk/lib-storage';import {CloudFrontClient,waitUntilInvalidationCompleted,CreateInvalidationCommand}from'@aws-sdk/client-cloudfront';var zo=new Set(["post-type","taxonomy","author","date","posts-page","listing"]);function Je(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Jo(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))]}function Qo(e){return new URL(e).pathname.split("/").filter(Boolean).some(r=>{try{return decodeURIComponent(r).endsWith("__trashed")}catch{return r.endsWith("__trashed")}})}function Mr(e){return Array.isArray(e)?e.map(Mr):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Mr(r)])):e}function Go(e){return JSON.stringify(Mr(e))}function We(e){return createHash("sha256").update(Go(e)).digest("hex")}function Dn(e){return We({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 jr(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 Ie(e,t){Zo(t);let r=new URL(jr(e)),n=new URL(t,`${r.toString().replace(/\/$/,"")}/`);if(n.origin!==r.origin)throw new Error(`Content-sync URL is outside the source origin: ${t}`);let s=r.pathname.replace(/\/+$/,"");if(s&&n.pathname!==s&&!n.pathname.startsWith(`${s}/`))throw new Error(`Content-sync URL is outside the source site path: ${t}`);return n.hash="",n.toString()}function Zo(e){let r=String(e).split(/[?#]/,1)[0];for(let s=0;s<3;s+=1)try{let o=decodeURIComponent(r);if(o===r)break;r=o;}catch{throw new Error(`Content-sync URL has malformed encoding: ${e}`)}if(r.includes("\0")||r.includes("\\"))throw new Error(`Content-sync URL has an unsafe path: ${e}`);if(r.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i,"").split("/").some(s=>s==="."||s===".."))throw new Error(`Content-sync URL has an unsafe path: ${e}`)}function Rt(e){let t=Je((e.postTypes??[]).map(n=>String(n).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let r=Je((e.listingPaths??[]).map(n=>{let s=String(n).trim();if(!s)return "";let o=new URL(s,"https://content-sync.invalid/");if(o.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(s))throw new Error("Content-sync listing routes must be same-site paths.");let a=`/${o.pathname.replace(/^\/+|\/+$/g,"")}`;return a==="/"?"/":`${a}/`}));return {postTypes:t,listingPaths:r,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 Un(e,t,r){return We({schemaVersion:1,sourceOrigin:jr(e),ruleId:t.trim(),scope:Rt(r)})}function Ln(e){return We({schemaVersion:1,...e})}function Wn(e){let t=String(e.siteId??"").trim()||String(e.accountId??"").trim()||jr(e.sourceOrigin);return `content-sync:${We({siteIdentity:t,ruleId:e.ruleId.trim(),targetFingerprint:e.targetFingerprint}).slice(0,48)}`}function qn(e){let t=[...e].sort((s,o)=>s.sequence-o.sequence),r=new Map,n=-1;for(let s of t){if(!Number.isSafeInteger(s.sequence)||s.sequence<=n)throw new Error("Content-sync journal events are not strictly ordered.");if(n=s.sequence,!Number.isSafeInteger(s.blogId)||s.blogId<1)throw new Error("Content-sync journal event has an invalid multisite identity.");let o=`${s.blogId}:${s.postType}:${s.postId}`,a=r.get(o);if(!a){r.set(o,{postId:s.postId,blogId:s.blogId,postType:s.postType,fromSequence:s.sequence,toSequence:s.sequence,before:s.before,after:s.after,operations:[s.operation],correlationIds:s.correlationId?[s.correlationId]:[]});continue}a.toSequence=s.sequence,a.after=s.after,a.operations.push(s.operation),s.correlationId&&!a.correlationIds.includes(s.correlationId)&&a.correlationIds.push(s.correlationId);}return [...r.values()].sort((s,o)=>s.fromSequence-o.fromSequence)}function Fn(e){return e?.status==="publish"&&!!e.url}function Yo(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 Fr(e){let t=Rt(e.scope),r=new Map;qn(e.events);for(let n of e.events)for(let s of [n.before,n.after])for(let o of s?.archiveFamilies??[]){if(!zo.has(o.kind)||!Yo(o.kind,t))continue;let a={...o,url:Ie(e.sourceOrigin,o.url)};r.set(`${a.kind}|${a.url}`,a);}for(let n of t.listingPaths){let s=Ie(e.sourceOrigin,n);r.set(`listing|${s}`,{kind:"listing",url:s});}return [...r.values()].sort((n,s)=>n.url.localeCompare(s.url))}function _n(e){let t=Rt(e.scope),r=qn(e.events),n=new Set,s=new Set,o=new Map,a=new Map(Fr({events:e.events,scope:t,sourceOrigin:e.sourceOrigin}).map(f=>[`${f.kind}|${f.url}`,f]));for(let f of r){let w=f.before,m=f.after,h=Fn(w),y=Fn(m);y&&m.url&&n.add(Ie(e.sourceOrigin,m.url)),h&&w.url&&(!y||w.url!==m.url)&&s.add(Ie(e.sourceOrigin,w.url));}for(let f of [...e.events].sort((w,m)=>w.sequence-m.sequence)){for(let w of [f.before,f.after])for(let m of w?.resourceDeleteUrls??[])o.set(Ie(e.sourceOrigin,m),"delete");for(let w of f.after?.resourceRenderUrls??[])o.set(Ie(e.sourceOrigin,w),"render");}let c=[...o].filter(([,f])=>f==="render").map(([f])=>f),i=[...o].filter(([,f])=>f==="delete").map(([f])=>f),d=new Map(e.resolvedArchiveFamilies.map(f=>[`${f.kind}|${Ie(e.sourceOrigin,f.url)}`,{...f,url:Ie(e.sourceOrigin,f.url),pageUrls:Je(f.pageUrls.map(w=>Ie(e.sourceOrigin,w)))}])),u=[...a.entries()].map(([f,w])=>{let m=d.get(f);if(!m)throw new Error(`WordPress did not resolve archive family ${f}.`);return {...w,...m}}).sort((f,w)=>f.url.localeCompare(w.url)),l=Je(u.flatMap(f=>f.pageUrls)),g=t.includeSitemapChain?Jo(e.sitemapUrls.map(f=>Ie(e.sourceOrigin,f))):[],p={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:r.length,directRenderUrls:Je([...n]),archiveFamilyUrls:l,sitemapUrls:g,deleteUrls:Je([...s]),resourceRenderUrls:Je(c),resourceDeleteUrls:Je(i),archiveFamilies:u};return {...p,impactHash:We(p)}}function vt(e){let{impactHash:t,...r}=e;if(e.schemaVersion!==1||!t)throw new Error("Invalid content-sync impact plan schema.");if(!Array.isArray(e.resourceRenderUrls)||!Array.isArray(e.resourceDeleteUrls))throw new Error("Invalid content-sync resource impact contract.");if(We(r)!==t)throw new Error("Content-sync impact plan hash mismatch.");for(let n of [...e.directRenderUrls,...e.deleteUrls,...e.resourceRenderUrls,...e.resourceDeleteUrls])if(Qo(n))throw new Error(`Content-sync impact contains a WordPress trash alias instead of the last public URL: ${n}`)}var ei="wp-json/smartcloud-static-publisher/v1/content-sync/",ti=25*1024*1024,_t=class extends Error{status;code;constructor(t,r,n){super(n),this.name="ContentSyncApiError",this.status=t,this.code=r;}},Nt=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,r="content-sync"){let n=this.options.sourceOrigin.replace(/\/+$/,"")+"/",s=r==="content-sync"?ei:`wp-json/smartcloud-static-publisher/v1/${r}/`;return new URL(`${s}${t}`,n)}async post(t,r,n="content-sync"){let s=this.endpoint(t,n),o=Buffer.from(JSON.stringify(r),"utf8"),a=s.protocol==="https:"?Nn:Xo,c=s.protocol==="https:"?new Nn.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((i,d)=>{let u=a.request(s,{method:"POST",agent:c,headers:{"content-type":"application/json","content-length":String(o.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},l=>{let g=[],p=0;l.on("data",f=>{if(p+=f.byteLength,p>ti){l.destroy(new Error("Content-sync API response exceeded the size limit."));return}g.push(f);}),l.on("error",d),l.on("end",()=>{let f=Buffer.concat(g).toString("utf8"),w;try{w=f?JSON.parse(f):{};}catch{d(new _t(l.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let m=l.statusCode??500;if(m<200||m>=300){d(new _t(m,String(w.code??"request-failed"),String(w.message??`Content-sync API request failed (${m}).`)));return}i(w);});});u.on("timeout",()=>u.destroy(new Error(`Content-sync API request timed out: ${t}`))),u.on("error",d),u.end(o);})}async head(t){return this.post("head",t)}async unboundHead(t,r){return this.post("head",{postTypes:t,includeSubsites:r})}async events(t){let r=[],n=t.afterSequence,s=new Set(t.postTypes);for(;n<t.throughSequence;){let o=await this.post("events",{...t,afterSequence:n,limit:250});if(o.fromSequence!==n||o.throughSequence!==t.throughSequence||o.nextSequence<n||o.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(o.items))throw new Error("Content-sync API returned a malformed event page.");let a=n;for(let c of o.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||!s.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(o.items.length>0&&o.nextSequence!==a)throw new Error("Content-sync API event cursor does not match the final returned event.");if(r.push(...o.items),!o.hasMore)break;if(o.nextSequence===n)throw new Error("Content-sync API event pagination did not advance.");n=o.nextSequence;}if(t.throughSequence>t.afterSequence&&r.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return r}async resolveImpactFamilies(t,r){let n=await this.post("impact",{families:t,includeSubsites:r});return Array.isArray(n.families)?n.families:[]}async releaseFingerprint(t=false){let r=await this.post("fingerprint",{includeSubsites:t}),n=String(r.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(n))throw new Error("WordPress returned an invalid release fingerprint.");return n}async establishBaseline(t){return this.post("baseline",t)}async acknowledge(t){return this.post("ack",t)}async importCookieObservations(t){return this.post("cookie-observations",t,"privacy")}};function Bt(e){let t=k.resolve(e);return {state:k.join(t,"content-sync-state.json"),current:k.join(t,"content-sync-current.json"),impact:k.join(t,"content-sync-impact-plan.json"),checkpoint:k.join(t,"content-sync-checkpoint.json"),baseline:k.join(t,"content-sync-baseline.json"),activeRules:k.join(t,"content-sync-active-rules.json"),releaseCutoff:k.join(t,"content-sync-release-cutoff.json"),candidateManifest:k.join(t,"content-sync-candidate-manifest.json"),trustedManifest:k.join(t,"crawl-manifest.json"),invalidation:k.join(t,"content-sync-invalidation.json"),deployPlan:k.join(t,"deploy-plan.json")}}async function Dr(e){let t=await Ct(e.releaseCutoff);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let r=t;if(r.schemaVersion!==1||typeof r.updatedAt!="string"||!r.entries||typeof r.entries!="object"||Array.isArray(r.entries))throw new Error("Invalid content-sync release-cutoff store.");return r}async function Bn(e,t){await ct(e.releaseCutoff,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function ct(e,t){await F.mkdir(k.dirname(e),{recursive:true});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await F.writeFile(r,JSON.stringify(t,null,2),"utf8"),await F.rename(r,e);}async function Ct(e){try{return JSON.parse(await F.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 Ur(e){let t=await Ct(e.baseline);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let r=t;if(r.schemaVersion!==1||typeof r.updatedAt!="string"||!r.entries||typeof r.entries!="object"||Array.isArray(r.entries))throw new Error("Invalid content-sync baseline store.");return r}async function Hn(e,t){await ct(e.baseline,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Lr(e){let t=await Ct(e.current);if(t===null)return null;let r=t;if(r.schemaVersion!==1||typeof r.jobId!="string"||typeof r.phase!="string"||!Number.isSafeInteger(r.fromSequence)||!Number.isSafeInteger(r.toSequence))throw new Error("Invalid content-sync current-range state.");return r}async function Vn(e,t){await ct(e.current,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Kn(e){let t=await Ct(e.impact);if(t===null)return null;let r=t;return vt(r),r}async function zn(e,t){vt(t),await ct(e.impact,t);}async function Jn(e,t){await ct(e.checkpoint,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Ht(e){let t=await Ct(e.state);if(t===null)return {schemaVersion:1,updatedAt:"",rules:{}};let r=t;if(r.schemaVersion!==1||typeof r.updatedAt!="string"||!r.rules||typeof r.rules!="object"||Array.isArray(r.rules))throw new Error("Invalid content-sync state store.");return r}async function Vt(e,t){await ct(e.state,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Wr(e){await Promise.all([e.current,e.checkpoint].map(async t=>{try{await F.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}));}async function Qn(e,t){let r=await Lr(e);return !r||r.coalesceKey!==t?false:(await Promise.all([e.current,e.checkpoint,e.impact,e.candidateManifest,e.invalidation,e.deployPlan].map(async n=>{try{await F.unlink(n);}catch(s){if(s.code!=="ENOENT")throw s}})),true)}var qr=["/sitemap_index.xml","/wp-sitemap.xml","/sitemap.xml"];function kt(e){let t=new Set;for(let r of [...e,...qr]){let n=String(r||"").trim();n&&t.add(n);}return [...t]}function _r(e){let t=e.pathname.toLowerCase();return t.endsWith(".xml")&&(t.includes("sitemap")||t.endsWith("/sitemap.xml"))}function Gn(e){if(!e||!/^https?:\/\//i.test(e))return false;try{return _r(new URL(e))}catch{return false}}function Yn(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function oi(e){let t=String(e??"").trim();if(!t)return "";let r=t;if(/^https?:\/\//i.test(r))try{r=new URL(r).pathname;}catch{return ""}if(r=r.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!r)return "";let n=r.endsWith("/"),s=r.replace(/^\/+/,"").split("/").map(a=>a.replace(/[^A-Za-z0-9._-]/g,"")).filter(a=>a.length>0&&a!=="."&&a!=="..");if(s.length===0)return "";let o=`/${s.join("/")}`;return n&&k.extname(o)===""&&(o+="/"),o==="/"?"":o}function Nr(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t.trim(),String(r??"")]).filter(([t])=>t.length>0))}function ii(e){if(!e||typeof e!="object")return {};let t={};for(let[r,n]of Object.entries(e)){let s=r.trim();if(!s||!n||typeof n!="object")continue;let o=n,a={};if(typeof o.targetOrigin=="string"){let i=Yn(o.targetOrigin);i&&(a.targetOrigin=i);}let c=Nr(o.extraReplacements);if(Object.keys(c).length>0&&(a.extraReplacements=c),o.s3&&typeof o.s3=="object"){let i={},d=o.s3;typeof d.bucket=="string"&&(i.bucket=d.bucket.trim()),typeof d.prefix=="string"&&(i.prefix=d.prefix.trim()),typeof d.region=="string"&&(i.region=d.region.trim()),typeof d.htmlCacheControl=="string"&&(i.htmlCacheControl=d.htmlCacheControl.trim()),typeof d.assetCacheControl=="string"&&(i.assetCacheControl=d.assetCacheControl.trim()),Object.keys(i).length>0&&(a.s3=i);}if(o.cloudFront&&typeof o.cloudFront=="object"){let i={},d=o.cloudFront;typeof d.distributionId=="string"&&(i.distributionId=d.distributionId.trim()),Array.isArray(d.invalidationPaths)&&(i.invalidationPaths=d.invalidationPaths.map(u=>String(u??"").trim()).filter(u=>u.length>0)),Object.keys(i).length>0&&(a.cloudFront=i);}t[s]=a;}return t}function Hr(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function ai(e,t){if(!e||typeof e!="object")return null;let r=e,n=r.command;if(n!=="publish"&&n!=="crawl"&&n!=="deploy"&&n!=="invalidate"&&n!=="retry-timeouts"&&n!=="url"&&n!=="content-sync")return null;let s=Number.parseInt(String(r.intervalMinutes??"0"),10);if(!Number.isFinite(s)||s<1)return null;let o=String(r.id??`${n}-${t+1}`).trim();if(!o)return null;let a=String(r.deploymentProfile??"").trim(),c=String(r.url??"").trim(),i=Array.isArray(r.postTypes)?[...new Set(r.postTypes.map(u=>String(u??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],d=Array.isArray(r.listingPaths)?[...new Set(r.listingPaths.map(u=>String(u??"").trim()).filter(Boolean))]:[];return n==="content-sync"&&i.length===0?null:{id:o,enabled:r.enabled!==false,command:n,intervalMinutes:s,...n==="publish"||n==="crawl"?{crawlMode:r.crawlMode==="incremental"?"incremental":"full"}:{},...(n==="publish"||n==="deploy"||n==="invalidate"||n==="content-sync")&&a?{deploymentProfile:a}:{},...c?{url:c}:{},...i.length>0?{postTypes:i}:{},...d.length>0?{listingPaths:d}:{},...typeof r.includeSubsites=="boolean"?{includeSubsites:r.includeSubsites}:{},...typeof r.includePostTypeArchives=="boolean"?{includePostTypeArchives:r.includePostTypeArchives}:{},...typeof r.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:r.includeTaxonomyArchives}:{},...typeof r.includeAuthorArchives=="boolean"?{includeAuthorArchives:r.includeAuthorArchives}:{},...typeof r.includeDateArchives=="boolean"?{includeDateArchives:r.includeDateArchives}:{},...typeof r.includePostsPage=="boolean"?{includePostsPage:r.includePostsPage}:{},...typeof r.includeSitemapChain=="boolean"?{includeSitemapChain:r.includeSitemapChain}:{}}}function Xn(e){let t=e&&typeof e=="object"?e:{},r=Array.isArray(t.rules)?t.rules.map((n,s)=>ai(n,s)).filter(n=>!!n):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:r}}function ci(e){let t=e&&typeof e=="object"?e:{},r=t.render&&typeof t.render=="object"?t.render:{},n=Number(r.concurrency??0),s=Number(r.batchSize??0),o=Number(r.maxAttempts??0),a=t.rewrite&&typeof t.rewrite=="object"?t.rewrite:{},c=t.deploy&&typeof t.deploy=="object"?t.deploy:{},i=(d,u)=>({enabled:typeof d.enabled=="boolean"?d.enabled:r.enabled===true,concurrency:Math.min(100,Math.max(1,Number(d.concurrency||u.concurrency))),batchSize:Math.min(500,Math.max(1,Number(d.batchSize||u.batchSize))),maxAttempts:Math.min(5,Math.max(1,Number(d.maxAttempts||2)))});return {render:{enabled:r.enabled===true,...Number.isInteger(n)&&n>0?{concurrency:n}:{},batchSize:Number.isInteger(s)&&s>0?Math.min(20,s):5,...Number.isInteger(o)&&o>0?{maxAttempts:Math.min(5,o)}:{}},rewrite:i(a,{concurrency:8,batchSize:25}),deploy:i(c,{concurrency:8,batchSize:50})}}function li(e){if(!e||typeof e!="object")return;let t=e,r={};for(let s of ["accountId","siteId"]){let o=t[s];typeof o=="string"&&o.trim()!==""&&(r[s]=o.trim());}let n=Number(t.lastUpdate??0);return Number.isFinite(n)&&n>0&&(r.lastUpdate=Math.floor(n)),t.subscriber===true&&(r.subscriber=true),Object.keys(r).length>0?r:void 0}function Vr(e){let t=e&&typeof e=="object"?e:{},r=String(t.accountId??"").trim(),n=String(t.siteId??"").trim(),s=t.subscriber===true,o=li(t.siteSettings),a={...o??{},...r?{accountId:o?.accountId??r}:{},...n?{siteId:o?.siteId??n}:{},...o?.subscriber===true||s?{subscriber:true}:{}},c={},i=String(t.apiBase??"").trim();i&&(c.apiBase=i);let d=String(t.runtimeToken??t.nonce??"").trim();d&&(c.runtimeToken=d);let u=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();u&&(c.virtualAssetBaseUrl=u),Object.keys(a).length>0&&(c.siteSettings=a);let l=Hr(t.subscriptionType);return l&&(c.subscriptionType=l),c}function ui(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function es(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function di(e,t){let r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[n,s]of new Headers(t.headers).entries())r.set(n,s);return r}async function ts(e,t,r=5){let n=new URL(es(e)),s=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),o=n.protocol==="http:"?Xo:Nn,a=di(e,t);return await new Promise((c,i)=>{let d=o.request(n,{method:s,headers:Object.fromEntries(a.entries()),...n.protocol==="https:"?{rejectUnauthorized:false}:{}},u=>{let l=[];u.on("data",g=>{l.push(Buffer.isBuffer(g)?g:Buffer.from(g));}),u.on("error",i),u.on("end",()=>{let g=u.statusCode??0,p=u.headers.location;if(r>0&&p&&[301,302,303,307,308].includes(g)){c(ts(new URL(p,n),{method:g===303?"GET":s},r-1));return}let f=new Headers;for(let[w,m]of Object.entries(u.headers))Array.isArray(m)?f.set(w,m.join(", ")):typeof m=="string"&&f.set(w,m);c(new Response(Buffer.concat(l),{status:g,statusText:u.statusMessage??"",headers:f}));});});d.on("error",i),d.end();})}function pi(e){let t=Vr(e.wpsuite),r={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},n=String(r.accountId??"").trim(),s=String(r.siteId??"").trim(),o=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...o?{virtualAssetBaseUrl:o}:{},...Object.keys(r).length>0?{siteSettings:r}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!n||!s||!o)return false;ui(e.sourceOrigin);let a=globalThis,i={...a.WpSuite??{},siteSettings:r,uploadUrl:o};return t.apiBase&&(i.apiBase=t.apiBase),a.WpSuite=i,true}async function mi(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!pi(e)){let s=e.wpsuite?.siteSettings,o=[String(s?.accountId??"").trim()?"":"accountId",String(s?.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): ${o.join(", ")}.`,requests:[]}}}let r=globalThis.fetch,n=[];try{typeof r=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(i,d)=>{let u=es(i);if(u.startsWith(t)){let l=(()=>{try{return new URL(u).pathname}catch{return u}})();try{let g=e.ignoreHttpsErrors&&u.startsWith("https://")?await ts(i,d):await r(i,d);return n.push({path:l,status:g.status,ok:g.ok,error:null}),g}catch(g){throw n.push({path:l,status:null,ok:!1,error:g instanceof Error?g.message:String(g)}),g}}return r(i,d)}));let{getConfig:s}=await import('@smart-cloud/wpsuite-core'),o=await s("publisher"),a=o&&typeof o=="object"?o:null,c=Hr(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:n}}}catch(s){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:s instanceof Error?s.message:String(s),requests:n}}}finally{typeof r=="function"&&(globalThis.fetch=r);}}function gi(e,t){let r=ii(t?.deploymentProfiles),n=String(t?.defaultDeploymentProfile??"").trim(),s=r[n]?n:"",o=Hr(t?.subscriptionType),a=Vr(e.wpsuite);return {...e,scheduler:Xn(t?.scheduler),deploymentProfiles:r,defaultDeploymentProfile:s,...o?{subscriptionType:o}:{},wpsuite:{...a,...a.siteSettings||o?{siteSettings:{...a.siteSettings??{},...a.siteSettings?.subscriber===true||o==="PROFESSIONAL"||o==="AGENCY"?{subscriber:true}:{}}}:{},...o?{subscriptionType:o}:{}}}}function Br(e,t){let n=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!n)return t;let s=n.split("/").map(o=>o.trim()).filter(o=>o.length>0&&o!=="."&&o!=="..");return s.length>0?s.join("/"):t}function fi(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?k.resolve(e):""}function Zn(e,t,r){let n=String(t||"").trim();return n&&k.isAbsolute(n)?k.resolve(n):k.resolve(e,Br(n,r))}async function Te(e,t={}){let r=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",n=await F.readFile(r,"utf8"),s=JSON.parse(n);s.sourceOrigin=s.sourceOrigin.replace(/\/$/,""),s.targetOrigin=Yn(s.targetOrigin),s.ignoreHttpsErrors??=false,s.outputDir=String(s.outputDir||"export").trim()||"export",s.urlRewriteMode||=s.targetOrigin==="."?"relative":"absolute",s.noJavaScriptRenderPathPrefixes||=[],s.seedPaths||=[],s.generated404RequestPath=oi(s.generated404RequestPath),s.sitemapPaths||=[...qr],s.allowedAssetHosts||=[],s.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],s.blockedPathPrefixes||=[],s.blockedSearchFragments||=[],s.pageCache={purgeBeforeCrawl:s.pageCache?.purgeBeforeCrawl===true};let o=Number(s.processingConcurrency)>0?Math.min(100,Math.max(1,Number(s.processingConcurrency))):null;s.concurrency=o??s.concurrency??1,s.maxPages||=0,s.extraReplacements=Nr(s.extraReplacements),s.postCrawlCopyMap=Nr(s.postCrawlCopyMap),s.logDir=String(s.logDir||"logs").trim()||"logs",s.verbose??=false,s.logLevel||=s.verbose?"debug":"info",s.s3SyncMode||="sdk-upload-delete",s.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},s.readiness.timeoutMs??=1500,s.readiness.fallbackWaitMs??=1500,s.viewport||={width:1440,height:1200},s.navigationTimeoutMs||=3e4,s.assetDownloadConcurrency=o??(Number(s.assetDownloadConcurrency)>0?Number(s.assetDownloadConcurrency):s.concurrency),s.rewriteConcurrency=o??(Number(s.rewriteConcurrency)>0?Number(s.rewriteConcurrency):s.assetDownloadConcurrency),s.wpsuite=Vr(s.wpsuite),s.scheduler=Xn(void 0),s.remoteWorkers=ci(s.remoteWorkers),typeof s.lambdaDelegationEnabled=="boolean"&&(s.remoteWorkers.render??={},s.remoteWorkers.rewrite??={},s.remoteWorkers.deploy??={},s.remoteWorkers.render.enabled=s.lambdaDelegationEnabled,s.remoteWorkers.rewrite.enabled=s.lambdaDelegationEnabled,s.remoteWorkers.deploy.enabled=s.lambdaDelegationEnabled),o!==null&&(s.processingConcurrency=o,s.remoteWorkers.render??={},s.remoteWorkers.rewrite??={},s.remoteWorkers.deploy??={},s.remoteWorkers.render.concurrency=o,s.remoteWorkers.rewrite.concurrency=o,s.remoteWorkers.deploy.concurrency=o),s.deploymentProfiles={},s.defaultDeploymentProfile="",s.deploymentTargetOverride=String(s.deploymentTargetOverride??"").trim();let a=await mi(s);t.onRemotePublisherConfigDiagnostic?.(a.diagnostic);let c=gi(s,a.remote),i=fi(),d=i?k.resolve(i,".."):"";return d?(c.outputDir=Zn(d,c.outputDir,"export"),c.logDir=Zn(d,c.logDir,"logs")):(k.isAbsolute(c.outputDir)||(c.outputDir=Br(c.outputDir,"export")),k.isAbsolute(c.logDir)||(c.logDir=Br(c.logDir,"logs"))),c}async function rs(e){await e.addInitScript(()=>{let t=window,r=[],n=new WeakSet,s=new WeakSet;Object.defineProperty(t,"__WPSUITE_STATIC_SERIALIZATION_STATE__",{value:{snapshots:r,runtimeCreatedElements:s},configurable:true});let o=Document.prototype.createElement;Document.prototype.createElement=function(g,p){let f=o.call(this,g,p);return s.add(f),f};let a=l=>{!(l instanceof Element)||n.has(l)||(n.add(l),r.push({host:l,pristine:l.cloneNode(true),sourceOwned:!s.has(l)}));},c=Element.prototype.attachShadow;Element.prototype.attachShadow=function(g){return a(this),c.call(this,g)};let i=new WeakSet,d=l=>{if(typeof l!="object"&&typeof l!="function"||l===null||i.has(l))return l;let g=l;if(typeof g.createRoot!="function")return l;let p=g.createRoot,f=function(w,...m){return a(w),Reflect.apply(p,this,[w,...m])};try{Object.defineProperty(g,"createRoot",{...Object.getOwnPropertyDescriptor(g,"createRoot"),value:f}),i.add(l);}catch{}return l},u=l=>{let g=d(t[l]);try{Object.defineProperty(t,l,{configurable:!0,enumerable:!0,get:()=>g,set:p=>{g=d(p);}});}catch{d(t[l]);}};u("ReactDOM"),u("ReactDOMClient");});}async function Kr(e){return e.evaluate(()=>{let t=window.__WPSUITE_STATIC_SERIALIZATION_STATE__,r=/^data-(?:[a-z0-9]+-)*(?:bound|initialized|mounted|hydrated)$/i;document.querySelectorAll("*").forEach(s=>{for(let o of [...s.attributes])r.test(o.name)&&s.removeAttribute(o.name);}),document.querySelectorAll("script, style, link, iframe").forEach(s=>{t?.runtimeCreatedElements.has(s)&&s.remove();});for(let s of t?.snapshots??[])s.host.isConnected&&(s.sourceOwned?s.host.replaceWith(s.pristine.cloneNode(true)):s.host.remove());return document.querySelectorAll("#wpsuite-consent-root, .grecaptcha-badge, iframe[src*='/recaptcha/']").forEach(s=>s.remove()),document.documentElement.classList.remove("wpsuite-consent-scroll-locked"),document.body.classList.remove("wpsuite-consent-scroll-locked"),`${document.doctype?new XMLSerializer().serializeToString(document.doctype):""}${document.documentElement.outerHTML}`})}var hi=".deploy-plan.json",wi="deploy-plan.json",yi=".crawl-incomplete.json",bi="crawl-incomplete.json";function ns(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?k.resolve(e):""}function ss(e){let t=String(e||"").replace(/\\/g,"/").replace(/^\/+/,"").trim(),r=k.posix.normalize(t);return !t||!r||r==="."||/^[a-zA-Z]:/.test(r)||r.startsWith("../")||r===".."?null:r}function Si(e){let t=String(e||"").trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("*")||t.includes("#"))return null;try{let r=new URL(t,"https://content-sync.invalid");return r.origin!=="https://content-sync.invalid"?null:`${k.posix.normalize(r.pathname)}${r.search}`}catch{return null}}function Ae(e){return [...new Set(e.map(ss).filter(t=>t!==null))]}function os(e,t){let r={generatedAt:String(t.generatedAt||new Date().toISOString()),outputDir:k.resolve(e.outputDir),runMode:t.runMode,crawlMode:t.crawlMode,fullSyncRequired:!!t.fullSyncRequired,changedFiles:Ae(t.changedFiles||[]),deletedFiles:Ae(t.deletedFiles||[]),rewriteTargets:Ae(t.rewriteTargets||[]),revalidateFiles:Ae(t.revalidateFiles||[])};return t.schemaVersion===2?{...r,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(),resolvedSitemapUrls:[...new Set((t.resolvedSitemapUrls||[]).map(n=>String(n||"").trim()).filter(n=>{try{let s=new URL(n);return s.protocol==="http:"||s.protocol==="https:"}catch{return false}}))],uploadGroups:{assets:Ae(t.uploadGroups?.assets||[]),content:Ae(t.uploadGroups?.content||[]),listings:Ae(t.uploadGroups?.listings||[]),resources:Ae(t.uploadGroups?.resources||[]),sitemapLeaves:Ae(t.uploadGroups?.sitemapLeaves||[]),sitemapIndexes:Ae(t.uploadGroups?.sitemapIndexes||[])},invalidationPaths:[...new Set((t.invalidationPaths||[]).map(Si).filter(n=>n!==null))].sort()}:{schemaVersion:1,...r,runMode:t.runMode}}function Pi(e){if(!e||typeof e!="object")return false;let t=e;if(t.schemaVersion===2){let r=t;return r.runMode==="content-sync"&&r.crawlMode==="incremental"&&r.fullSyncRequired===false&&typeof r.generatedAt=="string"&&typeof r.outputDir=="string"&&typeof r.consumerId=="string"&&r.consumerId.trim()!==""&&Number.isSafeInteger(r.fromSequence)&&Number.isSafeInteger(r.toSequence)&&Number(r.toSequence)>=Number(r.fromSequence)&&typeof r.impactHash=="string"&&/^[a-f0-9]{64}$/.test(r.impactHash)&&Array.isArray(r.resolvedSitemapUrls)&&Array.isArray(r.changedFiles)&&Array.isArray(r.deletedFiles)&&Array.isArray(r.rewriteTargets)&&(r.revalidateFiles===void 0||Array.isArray(r.revalidateFiles))&&!!r.uploadGroups&&Array.isArray(r.uploadGroups.assets)&&Array.isArray(r.uploadGroups.content)&&Array.isArray(r.uploadGroups.listings)&&Array.isArray(r.uploadGroups.resources)&&Array.isArray(r.uploadGroups.sitemapLeaves)&&Array.isArray(r.uploadGroups.sitemapIndexes)&&Array.isArray(r.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)&&(t.revalidateFiles===void 0||Array.isArray(t.revalidateFiles))}function zr(e){let t=k.join(k.resolve(e.outputDir),hi),r=ns();return r?[k.join(r,wi),t]:[t]}function Jr(e){let t=k.join(k.resolve(e.outputDir),yi),r=ns();return r?[k.join(r,bi),t]:[t]}function ge(e,t){let r=k.resolve(e),n=k.resolve(t),s=k.relative(r,n).replace(/\\/g,"/");return ss(s)}async function lt(e){let t=k.resolve(e.outputDir);for(let r of zr(e))try{let n=await F.readFile(r,"utf8"),s=JSON.parse(n);if(!Pi(s)||k.resolve(s.outputDir)!==t)continue;return os(e,s)}catch{}return null}async function Qr(e,t){let r=os(e,t);for(let n of zr(e)){await F.mkdir(k.dirname(n),{recursive:true});let s=`${n}.${process.pid}.${Date.now()}.tmp`;await F.writeFile(s,JSON.stringify(r,null,2),"utf8"),await F.rename(s,n);}}async function Ge(e){for(let t of zr(e))try{await F.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}async function Gr(e,t){let r={schemaVersion:1,startedAt:String(t.startedAt||new Date().toISOString()),outputDir:k.resolve(e.outputDir)};for(let n of Jr(e)){await F.mkdir(k.dirname(n),{recursive:true});let s=`${n}.${process.pid}.tmp`;await F.writeFile(s,JSON.stringify(r,null,2),"utf8"),await F.rename(s,n);}}async function is(e){let t=k.resolve(e.outputDir);for(let r of Jr(e)){let n;try{n=await F.readFile(r,"utf8");}catch(o){if(o.code==="ENOENT")continue;throw o}let s;try{s=JSON.parse(n);}catch{throw new Error(`Invalid incomplete crawl marker: ${r}`)}if(s.schemaVersion!==1||typeof s.startedAt!="string"||typeof s.outputDir!="string"||k.resolve(s.outputDir)!==t)throw new Error(`Invalid incomplete crawl marker: ${r}`);return {schemaVersion:1,startedAt:s.startedAt,outputDir:t}}return null}async function as(e){for(let t of Jr(e))try{await F.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}function $e(e,t=10){return us.createHash("sha1").update(e).digest("hex").slice(0,t)}async function Ri(e){await F.mkdir(k.dirname(e),{recursive:true});}async function _e(e,t,r){await Ri(e);let n=k.join(k.dirname(e),`.${k.basename(e)}.${process.pid}.${Date.now()}.${us.randomBytes(6).toString("hex")}.tmp`);try{typeof t=="string"?await F.writeFile(n,t,r??"utf8"):await F.writeFile(n,t),await F.rename(n,e);}catch(s){throw await F.unlink(n).catch(()=>{}),s}}function Oe(e){return [".html",".htm",".css",".js",".mjs",".json",".xml",".xsl",".txt",".svg",".map",".enc",".jws"].includes(k.extname(e).toLowerCase())}function Ne(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 ut(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Kt(e){return e.replace(/\//g,"\\/")}function cs(e){return e.replace(/\//g,"\\\\/")}function vi(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let r=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${r}`}catch{return null}}function ls(e,t,r){if(!t)return;e[t]=r;let n=Kt(t),s=Kt(r);e[n]=s;let o=cs(t),a=cs(r);e[o]=a;let c=ut(t),i=ut(r);e[c]=i;let d=ut(n),u=ut(s);e[d]=u;let l=ut(o),g=ut(a);e[l]=g;}function zt(e,t,r){ls(e,t,r);let n=vi(t);n&&n!==t&&ls(e,n,r);}function Zr(e,t){let r=t.startsWith("/")?t:`/${t}`,n=(e||"").replace(/\/$/,"");return !n||n==="."||n==="/"?r:`${n}${r}`}function ds(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function ps(e,t,r){if(!t)return r;let n=k.dirname(k.resolve(t)),s=k.resolve(e,r.replace(/^\/+/,"")),o=k.relative(n,s).replace(/\\/g,"/");return o?(o.startsWith(".")||(o=`./${o}`),o):"."}async function en(e,t){return (t?[...new Set(t)].map(n=>k.resolve(n)).filter(n=>n.startsWith(k.resolve(e.outputDir))).map(n=>k.relative(e.outputDir,n).replace(/\\/g,"/")).filter(n=>n.length>0):await Ci(["**/*"],{cwd:e.outputDir,onlyFiles:true,dot:true})).filter(n=>n!=="asset-map.json"&&Oe(n))}var Ti=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],Ai=new Set([".html",".htm"]),ms="WPSuite.io Static Publisher",Ei=ms.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function $i(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oi(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function Mi(e,t,r){return Oi(t)?e.replace(new RegExp(`(?<!:)${$i(t)}`,"g"),r):e.split(t).join(r)}function ji(e,t,r){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!r)return false;let s=k.extname(r).toLowerCase();return Ai.has(s)?/<head\b|<html\b|<!doctype html/i.test(t):false}function Fi(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${Ei}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${ms}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let n=e.includes(`\r
1
+ import F,{readFile}from'fs/promises';import Xo from'http';import Nn from'https';import k from'path';import us,{createHash}from'crypto';import {request,chromium}from'playwright';import {gunzipSync}from'zlib';import {setTimeout as setTimeout$1}from'timers/promises';import Ci from'fast-glob';import js from'mime-types';import {availableParallelism}from'os';import {Worker}from'worker_threads';import {LambdaClient,InvokeCommand}from'@aws-sdk/client-lambda';import {DynamoDBClient,GetItemCommand}from'@aws-sdk/client-dynamodb';import {S3Client,GetObjectCommand,PutObjectCommand,CopyObjectCommand,ListObjectsV2Command,HeadObjectCommand,DeleteObjectsCommand}from'@aws-sdk/client-s3';import {fromTemporaryCredentials}from'@aws-sdk/credential-providers';import {Upload}from'@aws-sdk/lib-storage';import {CloudFrontClient,waitUntilInvalidationCompleted,CreateInvalidationCommand}from'@aws-sdk/client-cloudfront';var zo=new Set(["post-type","taxonomy","author","date","posts-page","listing"]);function Je(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Jo(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))]}function Qo(e){return new URL(e).pathname.split("/").filter(Boolean).some(r=>{try{return decodeURIComponent(r).endsWith("__trashed")}catch{return r.endsWith("__trashed")}})}function Mr(e){return Array.isArray(e)?e.map(Mr):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Mr(r)])):e}function Go(e){return JSON.stringify(Mr(e))}function We(e){return createHash("sha256").update(Go(e)).digest("hex")}function Dn(e){return We({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 jr(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 Ie(e,t){Zo(t);let r=new URL(jr(e)),n=new URL(t,`${r.toString().replace(/\/$/,"")}/`);if(n.origin!==r.origin)throw new Error(`Content-sync URL is outside the source origin: ${t}`);let s=r.pathname.replace(/\/+$/,"");if(s&&n.pathname!==s&&!n.pathname.startsWith(`${s}/`))throw new Error(`Content-sync URL is outside the source site path: ${t}`);return n.hash="",n.toString()}function Zo(e){let r=String(e).split(/[?#]/,1)[0];for(let s=0;s<3;s+=1)try{let o=decodeURIComponent(r);if(o===r)break;r=o;}catch{throw new Error(`Content-sync URL has malformed encoding: ${e}`)}if(r.includes("\0")||r.includes("\\"))throw new Error(`Content-sync URL has an unsafe path: ${e}`);if(r.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i,"").split("/").some(s=>s==="."||s===".."))throw new Error(`Content-sync URL has an unsafe path: ${e}`)}function Rt(e){let t=Je((e.postTypes??[]).map(n=>String(n).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let r=Je((e.listingPaths??[]).map(n=>{let s=String(n).trim();if(!s)return "";let o=new URL(s,"https://content-sync.invalid/");if(o.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(s))throw new Error("Content-sync listing routes must be same-site paths.");let a=`/${o.pathname.replace(/^\/+|\/+$/g,"")}`;return a==="/"?"/":`${a}/`}));return {postTypes:t,listingPaths:r,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 Un(e,t,r){return We({schemaVersion:1,sourceOrigin:jr(e),ruleId:t.trim(),scope:Rt(r)})}function Ln(e){return We({schemaVersion:1,...e})}function Wn(e){let t=String(e.siteId??"").trim()||String(e.accountId??"").trim()||jr(e.sourceOrigin);return `content-sync:${We({siteIdentity:t,ruleId:e.ruleId.trim(),targetFingerprint:e.targetFingerprint}).slice(0,48)}`}function qn(e){let t=[...e].sort((s,o)=>s.sequence-o.sequence),r=new Map,n=-1;for(let s of t){if(!Number.isSafeInteger(s.sequence)||s.sequence<=n)throw new Error("Content-sync journal events are not strictly ordered.");if(n=s.sequence,!Number.isSafeInteger(s.blogId)||s.blogId<1)throw new Error("Content-sync journal event has an invalid multisite identity.");let o=`${s.blogId}:${s.postType}:${s.postId}`,a=r.get(o);if(!a){r.set(o,{postId:s.postId,blogId:s.blogId,postType:s.postType,fromSequence:s.sequence,toSequence:s.sequence,before:s.before,after:s.after,operations:[s.operation],correlationIds:s.correlationId?[s.correlationId]:[]});continue}a.toSequence=s.sequence,a.after=s.after,a.operations.push(s.operation),s.correlationId&&!a.correlationIds.includes(s.correlationId)&&a.correlationIds.push(s.correlationId);}return [...r.values()].sort((s,o)=>s.fromSequence-o.fromSequence)}function Fn(e){return e?.status==="publish"&&!!e.url}function Yo(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 Fr(e){let t=Rt(e.scope),r=new Map;qn(e.events);for(let n of e.events)for(let s of [n.before,n.after])for(let o of s?.archiveFamilies??[]){if(!zo.has(o.kind)||!Yo(o.kind,t))continue;let a={...o,url:Ie(e.sourceOrigin,o.url)};r.set(`${a.kind}|${a.url}`,a);}for(let n of t.listingPaths){let s=Ie(e.sourceOrigin,n);r.set(`listing|${s}`,{kind:"listing",url:s});}return [...r.values()].sort((n,s)=>n.url.localeCompare(s.url))}function _n(e){let t=Rt(e.scope),r=qn(e.events),n=new Set,s=new Set,o=new Map,a=new Map(Fr({events:e.events,scope:t,sourceOrigin:e.sourceOrigin}).map(f=>[`${f.kind}|${f.url}`,f]));for(let f of r){let w=f.before,m=f.after,h=Fn(w),y=Fn(m);y&&m.url&&n.add(Ie(e.sourceOrigin,m.url)),h&&w.url&&(!y||w.url!==m.url)&&s.add(Ie(e.sourceOrigin,w.url));}for(let f of [...e.events].sort((w,m)=>w.sequence-m.sequence)){for(let w of [f.before,f.after])for(let m of w?.resourceDeleteUrls??[])o.set(Ie(e.sourceOrigin,m),"delete");for(let w of f.after?.resourceRenderUrls??[])o.set(Ie(e.sourceOrigin,w),"render");}let c=[...o].filter(([,f])=>f==="render").map(([f])=>f),i=[...o].filter(([,f])=>f==="delete").map(([f])=>f),d=new Map(e.resolvedArchiveFamilies.map(f=>[`${f.kind}|${Ie(e.sourceOrigin,f.url)}`,{...f,url:Ie(e.sourceOrigin,f.url),pageUrls:Je(f.pageUrls.map(w=>Ie(e.sourceOrigin,w)))}])),u=[...a.entries()].map(([f,w])=>{let m=d.get(f);if(!m)throw new Error(`WordPress did not resolve archive family ${f}.`);return {...w,...m}}).sort((f,w)=>f.url.localeCompare(w.url)),l=Je(u.flatMap(f=>f.pageUrls)),g=t.includeSitemapChain?Jo(e.sitemapUrls.map(f=>Ie(e.sourceOrigin,f))):[],p={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:r.length,directRenderUrls:Je([...n]),archiveFamilyUrls:l,sitemapUrls:g,deleteUrls:Je([...s]),resourceRenderUrls:Je(c),resourceDeleteUrls:Je(i),archiveFamilies:u};return {...p,impactHash:We(p)}}function vt(e){let{impactHash:t,...r}=e;if(e.schemaVersion!==1||!t)throw new Error("Invalid content-sync impact plan schema.");if(!Array.isArray(e.resourceRenderUrls)||!Array.isArray(e.resourceDeleteUrls))throw new Error("Invalid content-sync resource impact contract.");if(We(r)!==t)throw new Error("Content-sync impact plan hash mismatch.");for(let n of [...e.directRenderUrls,...e.deleteUrls,...e.resourceRenderUrls,...e.resourceDeleteUrls])if(Qo(n))throw new Error(`Content-sync impact contains a WordPress trash alias instead of the last public URL: ${n}`)}var ei="wp-json/smartcloud-static-publisher/v1/content-sync/",ti=25*1024*1024,_t=class extends Error{status;code;constructor(t,r,n){super(n),this.name="ContentSyncApiError",this.status=t,this.code=r;}},Nt=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,r="content-sync"){let n=this.options.sourceOrigin.replace(/\/+$/,"")+"/",s=r==="content-sync"?ei:`wp-json/smartcloud-static-publisher/v1/${r}/`;return new URL(`${s}${t}`,n)}async post(t,r,n="content-sync"){let s=this.endpoint(t,n),o=Buffer.from(JSON.stringify(r),"utf8"),a=s.protocol==="https:"?Nn:Xo,c=s.protocol==="https:"?new Nn.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((i,d)=>{let u=a.request(s,{method:"POST",agent:c,headers:{"content-type":"application/json","content-length":String(o.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},l=>{let g=[],p=0;l.on("data",f=>{if(p+=f.byteLength,p>ti){l.destroy(new Error("Content-sync API response exceeded the size limit."));return}g.push(f);}),l.on("error",d),l.on("end",()=>{let f=Buffer.concat(g).toString("utf8"),w;try{w=f?JSON.parse(f):{};}catch{d(new _t(l.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let m=l.statusCode??500;if(m<200||m>=300){d(new _t(m,String(w.code??"request-failed"),String(w.message??`Content-sync API request failed (${m}).`)));return}i(w);});});u.on("timeout",()=>u.destroy(new Error(`Content-sync API request timed out: ${t}`))),u.on("error",d),u.end(o);})}async head(t){return this.post("head",t)}async unboundHead(t,r){return this.post("head",{postTypes:t,includeSubsites:r})}async events(t){let r=[],n=t.afterSequence,s=new Set(t.postTypes);for(;n<t.throughSequence;){let o=await this.post("events",{...t,afterSequence:n,limit:250});if(o.fromSequence!==n||o.throughSequence!==t.throughSequence||o.nextSequence<n||o.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(o.items))throw new Error("Content-sync API returned a malformed event page.");let a=n;for(let c of o.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||!s.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(o.items.length>0&&o.nextSequence!==a)throw new Error("Content-sync API event cursor does not match the final returned event.");if(r.push(...o.items),!o.hasMore)break;if(o.nextSequence===n)throw new Error("Content-sync API event pagination did not advance.");n=o.nextSequence;}if(t.throughSequence>t.afterSequence&&r.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return r}async resolveImpactFamilies(t,r){let n=await this.post("impact",{families:t,includeSubsites:r});return Array.isArray(n.families)?n.families:[]}async releaseFingerprint(t=false){let r=await this.post("fingerprint",{includeSubsites:t}),n=String(r.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(n))throw new Error("WordPress returned an invalid release fingerprint.");return n}async establishBaseline(t){return this.post("baseline",t)}async acknowledge(t){return this.post("ack",t)}async importCookieObservations(t){return this.post("cookie-observations",t,"privacy")}};function Bt(e){let t=k.resolve(e);return {state:k.join(t,"content-sync-state.json"),current:k.join(t,"content-sync-current.json"),impact:k.join(t,"content-sync-impact-plan.json"),checkpoint:k.join(t,"content-sync-checkpoint.json"),baseline:k.join(t,"content-sync-baseline.json"),activeRules:k.join(t,"content-sync-active-rules.json"),releaseCutoff:k.join(t,"content-sync-release-cutoff.json"),candidateManifest:k.join(t,"content-sync-candidate-manifest.json"),trustedManifest:k.join(t,"crawl-manifest.json"),invalidation:k.join(t,"content-sync-invalidation.json"),deployPlan:k.join(t,"deploy-plan.json")}}async function Dr(e){let t=await Ct(e.releaseCutoff);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let r=t;if(r.schemaVersion!==1||typeof r.updatedAt!="string"||!r.entries||typeof r.entries!="object"||Array.isArray(r.entries))throw new Error("Invalid content-sync release-cutoff store.");return r}async function Bn(e,t){await ct(e.releaseCutoff,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function ct(e,t){await F.mkdir(k.dirname(e),{recursive:true});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await F.writeFile(r,JSON.stringify(t,null,2),"utf8"),await F.rename(r,e);}async function Ct(e){try{return JSON.parse(await F.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 Ur(e){let t=await Ct(e.baseline);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let r=t;if(r.schemaVersion!==1||typeof r.updatedAt!="string"||!r.entries||typeof r.entries!="object"||Array.isArray(r.entries))throw new Error("Invalid content-sync baseline store.");return r}async function Hn(e,t){await ct(e.baseline,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Lr(e){let t=await Ct(e.current);if(t===null)return null;let r=t;if(r.schemaVersion!==1||typeof r.jobId!="string"||typeof r.phase!="string"||!Number.isSafeInteger(r.fromSequence)||!Number.isSafeInteger(r.toSequence))throw new Error("Invalid content-sync current-range state.");return r}async function Vn(e,t){await ct(e.current,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Kn(e){let t=await Ct(e.impact);if(t===null)return null;let r=t;return vt(r),r}async function zn(e,t){vt(t),await ct(e.impact,t);}async function Jn(e,t){await ct(e.checkpoint,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Ht(e){let t=await Ct(e.state);if(t===null)return {schemaVersion:1,updatedAt:"",rules:{}};let r=t;if(r.schemaVersion!==1||typeof r.updatedAt!="string"||!r.rules||typeof r.rules!="object"||Array.isArray(r.rules))throw new Error("Invalid content-sync state store.");return r}async function Vt(e,t){await ct(e.state,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Wr(e){await Promise.all([e.current,e.checkpoint].map(async t=>{try{await F.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}));}async function Qn(e,t){let r=await Lr(e);return !r||r.coalesceKey!==t?false:(await Promise.all([e.current,e.checkpoint,e.impact,e.candidateManifest,e.invalidation,e.deployPlan].map(async n=>{try{await F.unlink(n);}catch(s){if(s.code!=="ENOENT")throw s}})),true)}var qr=["/sitemap_index.xml","/wp-sitemap.xml","/sitemap.xml"];function kt(e){let t=new Set;for(let r of [...e,...qr]){let n=String(r||"").trim();n&&t.add(n);}return [...t]}function _r(e){let t=e.pathname.toLowerCase();return t.endsWith(".xml")&&(t.includes("sitemap")||t.endsWith("/sitemap.xml"))}function Gn(e){if(!e||!/^https?:\/\//i.test(e))return false;try{return _r(new URL(e))}catch{return false}}function Yn(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function oi(e){let t=String(e??"").trim();if(!t)return "";let r=t;if(/^https?:\/\//i.test(r))try{r=new URL(r).pathname;}catch{return ""}if(r=r.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!r)return "";let n=r.endsWith("/"),s=r.replace(/^\/+/,"").split("/").map(a=>a.replace(/[^A-Za-z0-9._-]/g,"")).filter(a=>a.length>0&&a!=="."&&a!=="..");if(s.length===0)return "";let o=`/${s.join("/")}`;return n&&k.extname(o)===""&&(o+="/"),o==="/"?"":o}function Nr(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t.trim(),String(r??"")]).filter(([t])=>t.length>0))}function ii(e){if(!e||typeof e!="object")return {};let t={};for(let[r,n]of Object.entries(e)){let s=r.trim();if(!s||!n||typeof n!="object")continue;let o=n,a={};if(typeof o.targetOrigin=="string"){let i=Yn(o.targetOrigin);i&&(a.targetOrigin=i);}let c=Nr(o.extraReplacements);if(Object.keys(c).length>0&&(a.extraReplacements=c),o.s3&&typeof o.s3=="object"){let i={},d=o.s3;typeof d.bucket=="string"&&(i.bucket=d.bucket.trim()),typeof d.prefix=="string"&&(i.prefix=d.prefix.trim()),typeof d.region=="string"&&(i.region=d.region.trim()),typeof d.htmlCacheControl=="string"&&(i.htmlCacheControl=d.htmlCacheControl.trim()),typeof d.assetCacheControl=="string"&&(i.assetCacheControl=d.assetCacheControl.trim()),Object.keys(i).length>0&&(a.s3=i);}if(o.cloudFront&&typeof o.cloudFront=="object"){let i={},d=o.cloudFront;typeof d.distributionId=="string"&&(i.distributionId=d.distributionId.trim()),Array.isArray(d.invalidationPaths)&&(i.invalidationPaths=d.invalidationPaths.map(u=>String(u??"").trim()).filter(u=>u.length>0)),Object.keys(i).length>0&&(a.cloudFront=i);}t[s]=a;}return t}function Hr(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function ai(e,t){if(!e||typeof e!="object")return null;let r=e,n=r.command;if(n!=="publish"&&n!=="crawl"&&n!=="deploy"&&n!=="invalidate"&&n!=="retry-timeouts"&&n!=="url"&&n!=="content-sync")return null;let s=Number.parseInt(String(r.intervalMinutes??"0"),10);if(!Number.isFinite(s)||s<1)return null;let o=String(r.id??`${n}-${t+1}`).trim();if(!o)return null;let a=String(r.deploymentProfile??"").trim(),c=String(r.url??"").trim(),i=Array.isArray(r.postTypes)?[...new Set(r.postTypes.map(u=>String(u??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],d=Array.isArray(r.listingPaths)?[...new Set(r.listingPaths.map(u=>String(u??"").trim()).filter(Boolean))]:[];return n==="content-sync"&&i.length===0?null:{id:o,enabled:r.enabled!==false,command:n,intervalMinutes:s,...n==="publish"||n==="crawl"?{crawlMode:r.crawlMode==="incremental"?"incremental":"full"}:{},...(n==="publish"||n==="deploy"||n==="invalidate"||n==="content-sync")&&a?{deploymentProfile:a}:{},...c?{url:c}:{},...i.length>0?{postTypes:i}:{},...d.length>0?{listingPaths:d}:{},...typeof r.includeSubsites=="boolean"?{includeSubsites:r.includeSubsites}:{},...typeof r.includePostTypeArchives=="boolean"?{includePostTypeArchives:r.includePostTypeArchives}:{},...typeof r.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:r.includeTaxonomyArchives}:{},...typeof r.includeAuthorArchives=="boolean"?{includeAuthorArchives:r.includeAuthorArchives}:{},...typeof r.includeDateArchives=="boolean"?{includeDateArchives:r.includeDateArchives}:{},...typeof r.includePostsPage=="boolean"?{includePostsPage:r.includePostsPage}:{},...typeof r.includeSitemapChain=="boolean"?{includeSitemapChain:r.includeSitemapChain}:{}}}function Xn(e){let t=e&&typeof e=="object"?e:{},r=Array.isArray(t.rules)?t.rules.map((n,s)=>ai(n,s)).filter(n=>!!n):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:r}}function ci(e){let t=e&&typeof e=="object"?e:{},r=t.render&&typeof t.render=="object"?t.render:{},n=Number(r.concurrency??0),s=Number(r.batchSize??0),o=Number(r.maxAttempts??0),a=t.rewrite&&typeof t.rewrite=="object"?t.rewrite:{},c=t.deploy&&typeof t.deploy=="object"?t.deploy:{},i=(d,u)=>({enabled:typeof d.enabled=="boolean"?d.enabled:r.enabled===true,concurrency:Math.min(100,Math.max(1,Number(d.concurrency||u.concurrency))),batchSize:Math.min(500,Math.max(1,Number(d.batchSize||u.batchSize))),maxAttempts:Math.min(5,Math.max(1,Number(d.maxAttempts||2)))});return {render:{enabled:r.enabled===true,...Number.isInteger(n)&&n>0?{concurrency:n}:{},batchSize:Number.isInteger(s)&&s>0?Math.min(20,s):5,...Number.isInteger(o)&&o>0?{maxAttempts:Math.min(5,o)}:{}},rewrite:i(a,{concurrency:8,batchSize:25}),deploy:i(c,{concurrency:8,batchSize:50})}}function li(e){if(!e||typeof e!="object")return;let t=e,r={};for(let s of ["accountId","siteId"]){let o=t[s];typeof o=="string"&&o.trim()!==""&&(r[s]=o.trim());}let n=Number(t.lastUpdate??0);return Number.isFinite(n)&&n>0&&(r.lastUpdate=Math.floor(n)),t.subscriber===true&&(r.subscriber=true),Object.keys(r).length>0?r:void 0}function Vr(e){let t=e&&typeof e=="object"?e:{},r=String(t.accountId??"").trim(),n=String(t.siteId??"").trim(),s=t.subscriber===true,o=li(t.siteSettings),a={...o??{},...r?{accountId:o?.accountId??r}:{},...n?{siteId:o?.siteId??n}:{},...o?.subscriber===true||s?{subscriber:true}:{}},c={},i=String(t.apiBase??"").trim();i&&(c.apiBase=i);let d=String(t.runtimeToken??t.nonce??"").trim();d&&(c.runtimeToken=d);let u=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();u&&(c.virtualAssetBaseUrl=u),Object.keys(a).length>0&&(c.siteSettings=a);let l=Hr(t.subscriptionType);return l&&(c.subscriptionType=l),c}function ui(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function es(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function di(e,t){let r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[n,s]of new Headers(t.headers).entries())r.set(n,s);return r}async function ts(e,t,r=5){let n=new URL(es(e)),s=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),o=n.protocol==="http:"?Xo:Nn,a=di(e,t);return await new Promise((c,i)=>{let d=o.request(n,{method:s,headers:Object.fromEntries(a.entries()),...n.protocol==="https:"?{rejectUnauthorized:false}:{}},u=>{let l=[];u.on("data",g=>{l.push(Buffer.isBuffer(g)?g:Buffer.from(g));}),u.on("error",i),u.on("end",()=>{let g=u.statusCode??0,p=u.headers.location;if(r>0&&p&&[301,302,303,307,308].includes(g)){c(ts(new URL(p,n),{method:g===303?"GET":s},r-1));return}let f=new Headers;for(let[w,m]of Object.entries(u.headers))Array.isArray(m)?f.set(w,m.join(", ")):typeof m=="string"&&f.set(w,m);c(new Response(Buffer.concat(l),{status:g,statusText:u.statusMessage??"",headers:f}));});});d.on("error",i),d.end();})}function pi(e){let t=Vr(e.wpsuite),r={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},n=String(r.accountId??"").trim(),s=String(r.siteId??"").trim(),o=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...o?{virtualAssetBaseUrl:o}:{},...Object.keys(r).length>0?{siteSettings:r}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!n||!s||!o)return false;ui(e.sourceOrigin);let a=globalThis,i={...a.WpSuite??{},siteSettings:r,uploadUrl:o};return t.apiBase&&(i.apiBase=t.apiBase),a.WpSuite=i,true}async function mi(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!pi(e)){let s=e.wpsuite?.siteSettings,o=[String(s?.accountId??"").trim()?"":"accountId",String(s?.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): ${o.join(", ")}.`,requests:[]}}}let r=globalThis.fetch,n=[];try{typeof r=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(i,d)=>{let u=es(i);if(u.startsWith(t)){let l=(()=>{try{return new URL(u).pathname}catch{return u}})();try{let g=e.ignoreHttpsErrors&&u.startsWith("https://")?await ts(i,d):await r(i,d);return n.push({path:l,status:g.status,ok:g.ok,error:null}),g}catch(g){throw n.push({path:l,status:null,ok:!1,error:g instanceof Error?g.message:String(g)}),g}}return r(i,d)}));let{getConfig:s}=await import('@smart-cloud/wpsuite-core'),o=await s("publisher"),a=o&&typeof o=="object"?o:null,c=Hr(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:n}}}catch(s){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:s instanceof Error?s.message:String(s),requests:n}}}finally{typeof r=="function"&&(globalThis.fetch=r);}}function gi(e,t){let r=ii(t?.deploymentProfiles),n=String(t?.defaultDeploymentProfile??"").trim(),s=r[n]?n:"",o=Hr(t?.subscriptionType),a=Vr(e.wpsuite);return {...e,scheduler:Xn(t?.scheduler),deploymentProfiles:r,defaultDeploymentProfile:s,...o?{subscriptionType:o}:{},wpsuite:{...a,...a.siteSettings||o?{siteSettings:{...a.siteSettings??{},...a.siteSettings?.subscriber===true||o==="PROFESSIONAL"||o==="AGENCY"?{subscriber:true}:{}}}:{},...o?{subscriptionType:o}:{}}}}function Br(e,t){let n=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!n)return t;let s=n.split("/").map(o=>o.trim()).filter(o=>o.length>0&&o!=="."&&o!=="..");return s.length>0?s.join("/"):t}function fi(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?k.resolve(e):""}function Zn(e,t,r){let n=String(t||"").trim();return n&&k.isAbsolute(n)?k.resolve(n):k.resolve(e,Br(n,r))}async function Te(e,t={}){let r=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",n=await F.readFile(r,"utf8"),s=JSON.parse(n);s.sourceOrigin=s.sourceOrigin.replace(/\/$/,""),s.targetOrigin=Yn(s.targetOrigin),s.ignoreHttpsErrors??=false,s.outputDir=String(s.outputDir||"export").trim()||"export",s.urlRewriteMode||=s.targetOrigin==="."?"relative":"absolute",s.noJavaScriptRenderPathPrefixes||=[],s.seedPaths||=[],s.generated404RequestPath=oi(s.generated404RequestPath),s.sitemapPaths||=[...qr],s.allowedAssetHosts||=[],s.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],s.blockedPathPrefixes||=[],s.blockedSearchFragments||=[],s.pageCache={purgeBeforeCrawl:s.pageCache?.purgeBeforeCrawl===true};let o=Number(s.processingConcurrency)>0?Math.min(100,Math.max(1,Number(s.processingConcurrency))):null;s.concurrency=o??s.concurrency??1,s.maxPages||=0,s.extraReplacements=Nr(s.extraReplacements),s.postCrawlCopyMap=Nr(s.postCrawlCopyMap),s.logDir=String(s.logDir||"logs").trim()||"logs",s.verbose??=false,s.logLevel||=s.verbose?"debug":"info",s.s3SyncMode||="sdk-upload-delete",s.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},s.readiness.timeoutMs??=1500,s.readiness.fallbackWaitMs??=1500,s.viewport||={width:1440,height:1200},s.navigationTimeoutMs||=3e4,s.assetDownloadConcurrency=o??(Number(s.assetDownloadConcurrency)>0?Number(s.assetDownloadConcurrency):s.concurrency),s.rewriteConcurrency=o??(Number(s.rewriteConcurrency)>0?Number(s.rewriteConcurrency):s.assetDownloadConcurrency),s.wpsuite=Vr(s.wpsuite),s.scheduler=Xn(void 0),s.remoteWorkers=ci(s.remoteWorkers),typeof s.lambdaDelegationEnabled=="boolean"&&(s.remoteWorkers.render??={},s.remoteWorkers.rewrite??={},s.remoteWorkers.deploy??={},s.remoteWorkers.render.enabled=s.lambdaDelegationEnabled,s.remoteWorkers.rewrite.enabled=s.lambdaDelegationEnabled,s.remoteWorkers.deploy.enabled=s.lambdaDelegationEnabled),o!==null&&(s.processingConcurrency=o,s.remoteWorkers.render??={},s.remoteWorkers.rewrite??={},s.remoteWorkers.deploy??={},s.remoteWorkers.render.concurrency=o,s.remoteWorkers.rewrite.concurrency=o,s.remoteWorkers.deploy.concurrency=o),s.deploymentProfiles={},s.defaultDeploymentProfile="",s.deploymentTargetOverride=String(s.deploymentTargetOverride??"").trim();let a=await mi(s);t.onRemotePublisherConfigDiagnostic?.(a.diagnostic);let c=gi(s,a.remote),i=fi(),d=i?k.resolve(i,".."):"";return d?(c.outputDir=Zn(d,c.outputDir,"export"),c.logDir=Zn(d,c.logDir,"logs")):(k.isAbsolute(c.outputDir)||(c.outputDir=Br(c.outputDir,"export")),k.isAbsolute(c.logDir)||(c.logDir=Br(c.logDir,"logs"))),c}async function rs(e){await e.addInitScript(()=>{let t=window,r=[],n=new WeakSet,s=new WeakSet;Object.defineProperty(t,"__WPSUITE_STATIC_SERIALIZATION_STATE__",{value:{snapshots:r,runtimeCreatedElements:s},configurable:true});let o=Document.prototype.createElement;Document.prototype.createElement=function(g,p){let f=o.call(this,g,p);return s.add(f),f};let a=l=>{!(l instanceof Element)||n.has(l)||(n.add(l),r.push({host:l,pristine:l.cloneNode(true),sourceOwned:!s.has(l)}));},c=Element.prototype.attachShadow;Element.prototype.attachShadow=function(g){return a(this),c.call(this,g)};let i=new WeakSet,d=l=>{if(typeof l!="object"&&typeof l!="function"||l===null||i.has(l))return l;let g=l;if(typeof g.createRoot!="function")return l;let p=g.createRoot,f=function(w,...m){return a(w),Reflect.apply(p,this,[w,...m])};try{Object.defineProperty(g,"createRoot",{...Object.getOwnPropertyDescriptor(g,"createRoot"),value:f}),i.add(l);}catch{}return l},u=l=>{let g=d(t[l]);try{Object.defineProperty(t,l,{configurable:!0,enumerable:!0,get:()=>g,set:p=>{g=d(p);}});}catch{d(t[l]);}};u("ReactDOM"),u("ReactDOMClient");});}async function Kr(e){return e.evaluate(()=>{let t=window.__WPSUITE_STATIC_SERIALIZATION_STATE__,r=/^data-(?:[a-z0-9]+-)*(?:bound|initialized|mounted|hydrated)$/i;document.querySelectorAll("*").forEach(s=>{for(let o of [...s.attributes])r.test(o.name)&&s.removeAttribute(o.name);}),document.querySelectorAll("script, style, link, iframe").forEach(s=>{t?.runtimeCreatedElements.has(s)&&s.remove();});for(let s of t?.snapshots??[])s.host.isConnected&&(s.sourceOwned?s.host.replaceWith(s.pristine.cloneNode(true)):s.host.remove());for(let s of [document.head,document.body])for(let o of [...s.children])t?.runtimeCreatedElements.has(o)&&o.remove();return document.querySelectorAll("#wpsuite-consent-root, .grecaptcha-badge, iframe[src*='/recaptcha/']").forEach(s=>s.remove()),document.documentElement.classList.remove("wpsuite-consent-scroll-locked"),document.body.classList.remove("wpsuite-consent-scroll-locked"),`${document.doctype?new XMLSerializer().serializeToString(document.doctype):""}${document.documentElement.outerHTML}`})}var hi=".deploy-plan.json",wi="deploy-plan.json",yi=".crawl-incomplete.json",bi="crawl-incomplete.json";function ns(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?k.resolve(e):""}function ss(e){let t=String(e||"").replace(/\\/g,"/").replace(/^\/+/,"").trim(),r=k.posix.normalize(t);return !t||!r||r==="."||/^[a-zA-Z]:/.test(r)||r.startsWith("../")||r===".."?null:r}function Si(e){let t=String(e||"").trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("*")||t.includes("#"))return null;try{let r=new URL(t,"https://content-sync.invalid");return r.origin!=="https://content-sync.invalid"?null:`${k.posix.normalize(r.pathname)}${r.search}`}catch{return null}}function Ae(e){return [...new Set(e.map(ss).filter(t=>t!==null))]}function os(e,t){let r={generatedAt:String(t.generatedAt||new Date().toISOString()),outputDir:k.resolve(e.outputDir),runMode:t.runMode,crawlMode:t.crawlMode,fullSyncRequired:!!t.fullSyncRequired,changedFiles:Ae(t.changedFiles||[]),deletedFiles:Ae(t.deletedFiles||[]),rewriteTargets:Ae(t.rewriteTargets||[]),revalidateFiles:Ae(t.revalidateFiles||[])};return t.schemaVersion===2?{...r,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(),resolvedSitemapUrls:[...new Set((t.resolvedSitemapUrls||[]).map(n=>String(n||"").trim()).filter(n=>{try{let s=new URL(n);return s.protocol==="http:"||s.protocol==="https:"}catch{return false}}))],uploadGroups:{assets:Ae(t.uploadGroups?.assets||[]),content:Ae(t.uploadGroups?.content||[]),listings:Ae(t.uploadGroups?.listings||[]),resources:Ae(t.uploadGroups?.resources||[]),sitemapLeaves:Ae(t.uploadGroups?.sitemapLeaves||[]),sitemapIndexes:Ae(t.uploadGroups?.sitemapIndexes||[])},invalidationPaths:[...new Set((t.invalidationPaths||[]).map(Si).filter(n=>n!==null))].sort()}:{schemaVersion:1,...r,runMode:t.runMode}}function Pi(e){if(!e||typeof e!="object")return false;let t=e;if(t.schemaVersion===2){let r=t;return r.runMode==="content-sync"&&r.crawlMode==="incremental"&&r.fullSyncRequired===false&&typeof r.generatedAt=="string"&&typeof r.outputDir=="string"&&typeof r.consumerId=="string"&&r.consumerId.trim()!==""&&Number.isSafeInteger(r.fromSequence)&&Number.isSafeInteger(r.toSequence)&&Number(r.toSequence)>=Number(r.fromSequence)&&typeof r.impactHash=="string"&&/^[a-f0-9]{64}$/.test(r.impactHash)&&Array.isArray(r.resolvedSitemapUrls)&&Array.isArray(r.changedFiles)&&Array.isArray(r.deletedFiles)&&Array.isArray(r.rewriteTargets)&&(r.revalidateFiles===void 0||Array.isArray(r.revalidateFiles))&&!!r.uploadGroups&&Array.isArray(r.uploadGroups.assets)&&Array.isArray(r.uploadGroups.content)&&Array.isArray(r.uploadGroups.listings)&&Array.isArray(r.uploadGroups.resources)&&Array.isArray(r.uploadGroups.sitemapLeaves)&&Array.isArray(r.uploadGroups.sitemapIndexes)&&Array.isArray(r.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)&&(t.revalidateFiles===void 0||Array.isArray(t.revalidateFiles))}function zr(e){let t=k.join(k.resolve(e.outputDir),hi),r=ns();return r?[k.join(r,wi),t]:[t]}function Jr(e){let t=k.join(k.resolve(e.outputDir),yi),r=ns();return r?[k.join(r,bi),t]:[t]}function ge(e,t){let r=k.resolve(e),n=k.resolve(t),s=k.relative(r,n).replace(/\\/g,"/");return ss(s)}async function lt(e){let t=k.resolve(e.outputDir);for(let r of zr(e))try{let n=await F.readFile(r,"utf8"),s=JSON.parse(n);if(!Pi(s)||k.resolve(s.outputDir)!==t)continue;return os(e,s)}catch{}return null}async function Qr(e,t){let r=os(e,t);for(let n of zr(e)){await F.mkdir(k.dirname(n),{recursive:true});let s=`${n}.${process.pid}.${Date.now()}.tmp`;await F.writeFile(s,JSON.stringify(r,null,2),"utf8"),await F.rename(s,n);}}async function Ge(e){for(let t of zr(e))try{await F.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}async function Gr(e,t){let r={schemaVersion:1,startedAt:String(t.startedAt||new Date().toISOString()),outputDir:k.resolve(e.outputDir)};for(let n of Jr(e)){await F.mkdir(k.dirname(n),{recursive:true});let s=`${n}.${process.pid}.tmp`;await F.writeFile(s,JSON.stringify(r,null,2),"utf8"),await F.rename(s,n);}}async function is(e){let t=k.resolve(e.outputDir);for(let r of Jr(e)){let n;try{n=await F.readFile(r,"utf8");}catch(o){if(o.code==="ENOENT")continue;throw o}let s;try{s=JSON.parse(n);}catch{throw new Error(`Invalid incomplete crawl marker: ${r}`)}if(s.schemaVersion!==1||typeof s.startedAt!="string"||typeof s.outputDir!="string"||k.resolve(s.outputDir)!==t)throw new Error(`Invalid incomplete crawl marker: ${r}`);return {schemaVersion:1,startedAt:s.startedAt,outputDir:t}}return null}async function as(e){for(let t of Jr(e))try{await F.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}function $e(e,t=10){return us.createHash("sha1").update(e).digest("hex").slice(0,t)}async function Ri(e){await F.mkdir(k.dirname(e),{recursive:true});}async function _e(e,t,r){await Ri(e);let n=k.join(k.dirname(e),`.${k.basename(e)}.${process.pid}.${Date.now()}.${us.randomBytes(6).toString("hex")}.tmp`);try{typeof t=="string"?await F.writeFile(n,t,r??"utf8"):await F.writeFile(n,t),await F.rename(n,e);}catch(s){throw await F.unlink(n).catch(()=>{}),s}}function Oe(e){return [".html",".htm",".css",".js",".mjs",".json",".xml",".xsl",".txt",".svg",".map",".enc",".jws"].includes(k.extname(e).toLowerCase())}function Ne(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 ut(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Kt(e){return e.replace(/\//g,"\\/")}function cs(e){return e.replace(/\//g,"\\\\/")}function vi(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let r=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${r}`}catch{return null}}function ls(e,t,r){if(!t)return;e[t]=r;let n=Kt(t),s=Kt(r);e[n]=s;let o=cs(t),a=cs(r);e[o]=a;let c=ut(t),i=ut(r);e[c]=i;let d=ut(n),u=ut(s);e[d]=u;let l=ut(o),g=ut(a);e[l]=g;}function zt(e,t,r){ls(e,t,r);let n=vi(t);n&&n!==t&&ls(e,n,r);}function Zr(e,t){let r=t.startsWith("/")?t:`/${t}`,n=(e||"").replace(/\/$/,"");return !n||n==="."||n==="/"?r:`${n}${r}`}function ds(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function ps(e,t,r){if(!t)return r;let n=k.dirname(k.resolve(t)),s=k.resolve(e,r.replace(/^\/+/,"")),o=k.relative(n,s).replace(/\\/g,"/");return o?(o.startsWith(".")||(o=`./${o}`),o):"."}async function en(e,t){return (t?[...new Set(t)].map(n=>k.resolve(n)).filter(n=>n.startsWith(k.resolve(e.outputDir))).map(n=>k.relative(e.outputDir,n).replace(/\\/g,"/")).filter(n=>n.length>0):await Ci(["**/*"],{cwd:e.outputDir,onlyFiles:true,dot:true})).filter(n=>n!=="asset-map.json"&&Oe(n))}var Ti=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],Ai=new Set([".html",".htm"]),ms="WPSuite.io Static Publisher",Ei=ms.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function $i(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oi(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function Mi(e,t,r){return Oi(t)?e.replace(new RegExp(`(?<!:)${$i(t)}`,"g"),r):e.split(t).join(r)}function ji(e,t,r){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!r)return false;let s=k.extname(r).toLowerCase();return Ai.has(s)?/<head\b|<html\b|<!doctype html/i.test(t):false}function Fi(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${Ei}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${ms}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let n=e.includes(`\r
2
2
  `)?`\r
3
3
  `:`
4
4
  `;return e.replace(/<head\b[^>]*>/i,s=>`${s}${n} ${t}`)}function Di(e){let t=Ne(e).trim();return t.startsWith("{")||t.startsWith("[")||t.includes("\\/")||/"@context"|"@type"/.test(t)}function Ui(e,t){let r=[...new Set(t)].filter(o=>o.includes("/")&&!/\\+\//.test(o)).map(o=>[o,Kt(o)]).filter(([o,a])=>o!==a).sort((o,a)=>a[0].length-o[0].length);if(!r.length)return e;let n=o=>{let a=o;for(let[c,i]of r)a=a.split(c).join(i);return a},s=e.replace(/(<script\b[^>]*\btype=["']application\/(?:ld\+)?json["'][^>]*>)([\s\S]*?)(<\/script>)/gi,(o,a,c,i)=>`${a}${n(c)}${i}`);return s=s.replace(/(<meta\b[^>]*\bcontent=(['"]))([\s\S]*?)(\2[^>]*>)/gi,(o,a,c,i,d)=>Di(i)?`${a}${n(i)}${d}`:o),s}function Li(e,t){if(!t)return null;let r=k.dirname(k.resolve(t)),n=k.resolve(e.outputDir),s=k.relative(r,n).replace(/\\/g,"/");return s?(s.startsWith(".")||(s=`./${s}`),s.endsWith("/")?s:`${s}/`):"./"}function Wi(e,t,r){let n=Li(t,r);if(!n)return e;let s=e;for(let o of Ti){let a=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`(?:\\.{1,}/)+${a}`,"g"),i=new RegExp(`(?<!\\.)/${a}`,"g");s=s.replace(c,`${n}${o}`).replace(i,`${n}${o}`);let d=o.replace(/\//g,"\\/"),u=n.replace(/\//g,"\\/"),l=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),g=new RegExp(`(?:\\.{1,}\\\\/)+${l}`,"g"),p=new RegExp(`(?:\\.{1,}(?:\\\\/|\\\\))+${l}`,"g"),f=new RegExp(`(?<![\\.\\\\])\\/${l}`,"g");s=s.replace(g,`${u}${d}`).replace(p,`${u}${d}`).replace(f,`${u}${d}`);}return s}function Xr(e,t,r){if(e.urlRewriteMode==="absolute")return t;let n=(()=>{try{return new URL(t,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin)}catch{return null}})(),s=n?n.pathname:ds(t,e.targetOrigin),o=n?`${n.search}${n.hash}`:"";return e.urlRewriteMode==="root-relative"?`${s}${o}`:`${ps(e.outputDir,r,s)}${o}`}function Yr(e,t,r,n,s){zt(e,r,Xr(t,n,s));}function qi(e,t,r,n,s){if(!r||r===n)return;zt(e,r,n);let o=Xr(t,r,s),a=Xr(t,n,s);zt(e,o,a);}function tn(e,t,r,n,s={}){let o=e,a={};Yr(a,t,t.sourceOrigin,t.targetOrigin,n);for(let[i,d]of Object.entries(t.extraReplacements))Yr(a,t,i,d,n);for(let[i,d]of Object.entries(r))Yr(a,t,i,d,n);for(let[i,d]of Object.entries(s)){let u=r[i];!u||u===d||qi(a,t,d,u,n);}let c=Object.entries(a).sort((i,d)=>d[0].length-i[0].length);for(let[i,d]of c)o=Mi(o,i,d);return t.urlRewriteMode!=="absolute"&&(o=Wi(o,t,n)),o=Ui(o,c.map(([,i])=>i)),ji(t,o,n)&&(o=Fi(o)),o}async function _i(e,t,r,n){let s=k.join(e.outputDir,n),o=k.extname(s).toLowerCase(),a;try{a=await F.readFile(s,"utf8");}catch(d){if(d.code!=="ENOENT")throw d;return {changed:false}}let i=tn(a,e,t,o===".js"||o===".mjs"?void 0:s,r);return i!==a?(await _e(s,i,"utf8"),{changed:true}):{changed:false}}async function Ni(e,t){return await new Promise((r,n)=>{let s=i=>{if(c(),i?.error){n(new Error(i.error));return}r({changed:!!i?.changed});},o=i=>{c(),n(i);},a=i=>{c(),i!==0&&n(new Error(`Rewrite worker exited with code ${i}.`));},c=()=>{e.off("message",s),e.off("error",o),e.off("exit",a);};e.on("message",s),e.on("error",o),e.on("exit",a),e.postMessage({file:t});})}async function Jt(e,t,r={}){let n=await en(e,r.files),s=0;if(n.length===0)return 0;let o=Math.max(1,Number(e.rewriteConcurrency||e.assetDownloadConcurrency||1)),a=Math.max(1,Math.min(o,n.length,availableParallelism()));await r.onStart?.({totalFiles:n.length,workerCount:a});let c=0,i=0,d=null;if(a===1){for(let l of n){let g=await _i(e,t,r.previousAssetMap??{},l);g.changed&&(s+=1),i+=1,await r.onProgress?.({index:i,totalFiles:n.length,changedTextFiles:s,file:l,changed:g.changed});}return s}let u=Array.from({length:a},async()=>{let l=new Worker(new URL("./rewrite-worker.js",import.meta.url),{workerData:{config:e,assetMap:t,previousAssetMap:r.previousAssetMap??{}}});try{for(;!d;){let g=c;if(g>=n.length)return;c+=1;let p=n[g],f=await Ni(l,p);f.changed&&(s+=1),i+=1,await r.onProgress?.({index:i,totalFiles:n.length,changedTextFiles:s,file:p,changed:f.changed});}}catch(g){throw d=g instanceof Error?g:new Error(String(g)),d}finally{await l.terminate().catch(()=>{});}});return await Promise.all(u),s}var je={error:0,warn:1,info:2,debug:3},Bi=/^(?:authorization|proxyAuthorization|runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken|xStaticPublisherToken|xApiKey)$/i;function tt(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 Gt(e){return typeof e=="string"?tt(e):Array.isArray(e)?e.map(t=>Gt(t)):e instanceof Error?{name:e.name,message:tt(e.message),...e.stack?{stack:tt(e.stack)}:{}}:e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Bi.test(t)?"[REDACTED]":Gt(r)])):e}function Yt(e){return e?Gt(e):void 0}var gs=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",Qt=gs?k.join(gs,"current-progress.json"):"",fs=Promise.resolve();function hs(e){return e.includes("crawl")?"crawl":e.includes("deploy")?"deploy":e.includes("invalidate")?"invalidate":e}function Hi(e,t){let r={...e},n=typeof e.phase=="string"?e.phase.trim():"",s=typeof t.phase=="string"?t.phase.trim():"";if(s!==""&&(s==="deploy"||s.startsWith("deploy-"))&&n!==s)for(let c of ["index","totalFiles","staged","uploaded","skipped","failed","deleted","workerCount","completedBatches","totalBatches"])delete r[c];let a=new Set(["pagesQueued","pagesRendered","assetsQueued","sitemapsQueued","pagesDiscovered","assetsDiscovered","sitemapsDiscovered","pagesSaved","assetsSaved","donePages","doneAssets","doneSitemaps","changedTextFiles","uploaded","failed","index","totalFiles","completedBatches","totalBatches","pageQueue","assetQueue","sitemapQueue"]);for(let[c,i]of Object.entries(t)){let d=r[c];if(typeof d=="number"&&typeof i=="number"&&a.has(c)){r[c]=Math.max(d,i);continue}r[c]=i;}return r}function ws(e,t,r){Qt&&(fs=fs.then(async()=>{let n=new Date,s=n.toISOString();await F.mkdir(k.dirname(Qt),{recursive:true});let o=await F.readFile(Qt,"utf8").then(h=>JSON.parse(h)).catch(()=>null),a=o&&typeof o.details=="object"&&o.details?o.details:{},c=hs(e),i=o?.currentStep||hs(o?.source||""),d=o?.startedAt||s,u={...o?.stepDurationsSec??{}},l=o?.stepStartedAt||s;if(i&&i!==c&&o?.stepStartedAt){let h=Math.max(0,Math.round((n.getTime()-new Date(o.stepStartedAt).getTime())/1e3));u[i]=(u[i]??0)+h,l=s;}let g=Math.max(0,Math.round((n.getTime()-new Date(l).getTime())/1e3)),p=Math.max(0,Math.round((n.getTime()-new Date(d).getTime())/1e3)),f=tt(t),w=Yt(r)??{},m={checkedAt:s,source:e,message:f,details:Hi(a,w),startedAt:d,currentStep:c,stepStartedAt:l,stepElapsedSec:g,totalElapsedSec:p,stepDurationsSec:u};await F.writeFile(Qt,JSON.stringify(m,null,2),"utf8");}).catch(()=>{}));}async function ys(e,t){await F.mkdir(k.dirname(e),{recursive:true}),await F.appendFile(e,`${JSON.stringify(Gt(t))}
package/dist/crawl.js CHANGED
@@ -1,4 +1,4 @@
1
- import {request,chromium}from'playwright';import $,{readFile}from'fs/promises';import S from'path';import {gunzipSync}from'zlib';import {setTimeout as setTimeout$1}from'timers/promises';import ks from'fast-glob';import Yr from'mime-types';import Ar,{createHash}from'crypto';import cs from'http';import ls from'https';import {availableParallelism}from'os';import {Worker}from'worker_threads';import {LambdaClient,InvokeCommand}from'@aws-sdk/client-lambda';import {DynamoDBClient,GetItemCommand}from'@aws-sdk/client-dynamodb';import {S3Client,GetObjectCommand,PutObjectCommand,CopyObjectCommand}from'@aws-sdk/client-s3';import {fromTemporaryCredentials}from'@aws-sdk/credential-providers';async function dr(e){await e.addInitScript(()=>{let t=window,r=[],n=new WeakSet,s=new WeakSet;Object.defineProperty(t,"__WPSUITE_STATIC_SERIALIZATION_STATE__",{value:{snapshots:r,runtimeCreatedElements:s},configurable:true});let o=Document.prototype.createElement;Document.prototype.createElement=function(m,h){let f=o.call(this,m,h);return s.add(f),f};let i=u=>{!(u instanceof Element)||n.has(u)||(n.add(u),r.push({host:u,pristine:u.cloneNode(true),sourceOwned:!s.has(u)}));},c=Element.prototype.attachShadow;Element.prototype.attachShadow=function(m){return i(this),c.call(this,m)};let a=new WeakSet,l=u=>{if(typeof u!="object"&&typeof u!="function"||u===null||a.has(u))return u;let m=u;if(typeof m.createRoot!="function")return u;let h=m.createRoot,f=function(b,...p){return i(b),Reflect.apply(h,this,[b,...p])};try{Object.defineProperty(m,"createRoot",{...Object.getOwnPropertyDescriptor(m,"createRoot"),value:f}),a.add(u);}catch{}return u},d=u=>{let m=l(t[u]);try{Object.defineProperty(t,u,{configurable:!0,enumerable:!0,get:()=>m,set:h=>{m=l(h);}});}catch{l(t[u]);}};d("ReactDOM"),d("ReactDOMClient");});}async function Tt(e){return e.evaluate(()=>{let t=window.__WPSUITE_STATIC_SERIALIZATION_STATE__,r=/^data-(?:[a-z0-9]+-)*(?:bound|initialized|mounted|hydrated)$/i;document.querySelectorAll("*").forEach(s=>{for(let o of [...s.attributes])r.test(o.name)&&s.removeAttribute(o.name);}),document.querySelectorAll("script, style, link, iframe").forEach(s=>{t?.runtimeCreatedElements.has(s)&&s.remove();});for(let s of t?.snapshots??[])s.host.isConnected&&(s.sourceOwned?s.host.replaceWith(s.pristine.cloneNode(true)):s.host.remove());return document.querySelectorAll("#wpsuite-consent-root, .grecaptcha-badge, iframe[src*='/recaptcha/']").forEach(s=>s.remove()),document.documentElement.classList.remove("wpsuite-consent-scroll-locked"),document.body.classList.remove("wpsuite-consent-scroll-locked"),`${document.doctype?new XMLSerializer().serializeToString(document.doctype):""}${document.documentElement.outerHTML}`})}var Yn=".deploy-plan.json",Xn="deploy-plan.json",es=".crawl-incomplete.json",ts="crawl-incomplete.json";function pr(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function mr(e){let t=String(e||"").replace(/\\/g,"/").replace(/^\/+/,"").trim(),r=S.posix.normalize(t);return !t||!r||r==="."||/^[a-zA-Z]:/.test(r)||r.startsWith("../")||r===".."?null:r}function rs(e){let t=String(e||"").trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("*")||t.includes("#"))return null;try{let r=new URL(t,"https://content-sync.invalid");return r.origin!=="https://content-sync.invalid"?null:`${S.posix.normalize(r.pathname)}${r.search}`}catch{return null}}function ue(e){return [...new Set(e.map(mr).filter(t=>t!==null))]}function ns(e,t){let r={generatedAt:String(t.generatedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir),runMode:t.runMode,crawlMode:t.crawlMode,fullSyncRequired:!!t.fullSyncRequired,changedFiles:ue(t.changedFiles||[]),deletedFiles:ue(t.deletedFiles||[]),rewriteTargets:ue(t.rewriteTargets||[]),revalidateFiles:ue(t.revalidateFiles||[])};return t.schemaVersion===2?{...r,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(),resolvedSitemapUrls:[...new Set((t.resolvedSitemapUrls||[]).map(n=>String(n||"").trim()).filter(n=>{try{let s=new URL(n);return s.protocol==="http:"||s.protocol==="https:"}catch{return false}}))],uploadGroups:{assets:ue(t.uploadGroups?.assets||[]),content:ue(t.uploadGroups?.content||[]),listings:ue(t.uploadGroups?.listings||[]),resources:ue(t.uploadGroups?.resources||[]),sitemapLeaves:ue(t.uploadGroups?.sitemapLeaves||[]),sitemapIndexes:ue(t.uploadGroups?.sitemapIndexes||[])},invalidationPaths:[...new Set((t.invalidationPaths||[]).map(rs).filter(n=>n!==null))].sort()}:{schemaVersion:1,...r,runMode:t.runMode}}function gr(e){let t=S.join(S.resolve(e.outputDir),Yn),r=pr();return r?[S.join(r,Xn),t]:[t]}function hr(e){let t=S.join(S.resolve(e.outputDir),es),r=pr();return r?[S.join(r,ts),t]:[t]}function X(e,t){let r=S.resolve(e),n=S.resolve(t),s=S.relative(r,n).replace(/\\/g,"/");return mr(s)}async function At(e,t){let r=ns(e,t);for(let n of gr(e)){await $.mkdir(S.dirname(n),{recursive:true});let s=`${n}.${process.pid}.${Date.now()}.tmp`;await $.writeFile(s,JSON.stringify(r,null,2),"utf8"),await $.rename(s,n);}}async function fr(e){for(let t of gr(e))try{await $.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}async function It(e,t){let r={schemaVersion:1,startedAt:String(t.startedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir)};for(let n of hr(e)){await $.mkdir(S.dirname(n),{recursive:true});let s=`${n}.${process.pid}.tmp`;await $.writeFile(s,JSON.stringify(r,null,2),"utf8"),await $.rename(s,n);}}async function wr(e){for(let t of hr(e))try{await $.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}function os(e){return new URL(e).pathname.split("/").filter(Boolean).some(r=>{try{return decodeURIComponent(r).endsWith("__trashed")}catch{return r.endsWith("__trashed")}})}function Et(e){return Array.isArray(e)?e.map(Et):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Et(r)])):e}function is(e){return JSON.stringify(Et(e))}function as(e){return createHash("sha256").update(is(e)).digest("hex")}function yr(e){let{impactHash:t,...r}=e;if(e.schemaVersion!==1||!t)throw new Error("Invalid content-sync impact plan schema.");if(!Array.isArray(e.resourceRenderUrls)||!Array.isArray(e.resourceDeleteUrls))throw new Error("Invalid content-sync resource impact contract.");if(as(r)!==t)throw new Error("Content-sync impact plan hash mismatch.");for(let n of [...e.directRenderUrls,...e.deleteUrls,...e.resourceRenderUrls,...e.resourceDeleteUrls])if(os(n))throw new Error(`Content-sync impact contains a WordPress trash alias instead of the last public URL: ${n}`)}var Ot=["/sitemap_index.xml","/wp-sitemap.xml","/sitemap.xml"];function br(e){let t=new Set;for(let r of [...e,...Ot]){let n=String(r||"").trim();n&&t.add(n);}return [...t]}function Mt(e){let t=e.pathname.toLowerCase();return t.endsWith(".xml")&&(t.includes("sitemap")||t.endsWith("/sitemap.xml"))}function Sr(e){if(!e||!/^https?:\/\//i.test(e))return false;try{return Mt(new URL(e))}catch{return false}}function Rr(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function ds(e){let t=String(e??"").trim();if(!t)return "";let r=t;if(/^https?:\/\//i.test(r))try{r=new URL(r).pathname;}catch{return ""}if(r=r.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!r)return "";let n=r.endsWith("/"),s=r.replace(/^\/+/,"").split("/").map(i=>i.replace(/[^A-Za-z0-9._-]/g,"")).filter(i=>i.length>0&&i!=="."&&i!=="..");if(s.length===0)return "";let o=`/${s.join("/")}`;return n&&S.extname(o)===""&&(o+="/"),o==="/"?"":o}function $t(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t.trim(),String(r??"")]).filter(([t])=>t.length>0))}function ps(e){if(!e||typeof e!="object")return {};let t={};for(let[r,n]of Object.entries(e)){let s=r.trim();if(!s||!n||typeof n!="object")continue;let o=n,i={};if(typeof o.targetOrigin=="string"){let a=Rr(o.targetOrigin);a&&(i.targetOrigin=a);}let c=$t(o.extraReplacements);if(Object.keys(c).length>0&&(i.extraReplacements=c),o.s3&&typeof o.s3=="object"){let a={},l=o.s3;typeof l.bucket=="string"&&(a.bucket=l.bucket.trim()),typeof l.prefix=="string"&&(a.prefix=l.prefix.trim()),typeof l.region=="string"&&(a.region=l.region.trim()),typeof l.htmlCacheControl=="string"&&(a.htmlCacheControl=l.htmlCacheControl.trim()),typeof l.assetCacheControl=="string"&&(a.assetCacheControl=l.assetCacheControl.trim()),Object.keys(a).length>0&&(i.s3=a);}if(o.cloudFront&&typeof o.cloudFront=="object"){let a={},l=o.cloudFront;typeof l.distributionId=="string"&&(a.distributionId=l.distributionId.trim()),Array.isArray(l.invalidationPaths)&&(a.invalidationPaths=l.invalidationPaths.map(d=>String(d??"").trim()).filter(d=>d.length>0)),Object.keys(a).length>0&&(i.cloudFront=a);}t[s]=i;}return t}function Ut(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function ms(e,t){if(!e||typeof e!="object")return null;let r=e,n=r.command;if(n!=="publish"&&n!=="crawl"&&n!=="deploy"&&n!=="invalidate"&&n!=="retry-timeouts"&&n!=="url"&&n!=="content-sync")return null;let s=Number.parseInt(String(r.intervalMinutes??"0"),10);if(!Number.isFinite(s)||s<1)return null;let o=String(r.id??`${n}-${t+1}`).trim();if(!o)return null;let i=String(r.deploymentProfile??"").trim(),c=String(r.url??"").trim(),a=Array.isArray(r.postTypes)?[...new Set(r.postTypes.map(d=>String(d??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],l=Array.isArray(r.listingPaths)?[...new Set(r.listingPaths.map(d=>String(d??"").trim()).filter(Boolean))]:[];return n==="content-sync"&&a.length===0?null:{id:o,enabled:r.enabled!==false,command:n,intervalMinutes:s,...n==="publish"||n==="crawl"?{crawlMode:r.crawlMode==="incremental"?"incremental":"full"}:{},...(n==="publish"||n==="deploy"||n==="invalidate"||n==="content-sync")&&i?{deploymentProfile:i}:{},...c?{url:c}:{},...a.length>0?{postTypes:a}:{},...l.length>0?{listingPaths:l}:{},...typeof r.includeSubsites=="boolean"?{includeSubsites:r.includeSubsites}:{},...typeof r.includePostTypeArchives=="boolean"?{includePostTypeArchives:r.includePostTypeArchives}:{},...typeof r.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:r.includeTaxonomyArchives}:{},...typeof r.includeAuthorArchives=="boolean"?{includeAuthorArchives:r.includeAuthorArchives}:{},...typeof r.includeDateArchives=="boolean"?{includeDateArchives:r.includeDateArchives}:{},...typeof r.includePostsPage=="boolean"?{includePostsPage:r.includePostsPage}:{},...typeof r.includeSitemapChain=="boolean"?{includeSitemapChain:r.includeSitemapChain}:{}}}function vr(e){let t=e&&typeof e=="object"?e:{},r=Array.isArray(t.rules)?t.rules.map((n,s)=>ms(n,s)).filter(n=>!!n):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:r}}function gs(e){let t=e&&typeof e=="object"?e:{},r=t.render&&typeof t.render=="object"?t.render:{},n=Number(r.concurrency??0),s=Number(r.batchSize??0),o=Number(r.maxAttempts??0),i=t.rewrite&&typeof t.rewrite=="object"?t.rewrite:{},c=t.deploy&&typeof t.deploy=="object"?t.deploy:{},a=(l,d)=>({enabled:typeof l.enabled=="boolean"?l.enabled:r.enabled===true,concurrency:Math.min(100,Math.max(1,Number(l.concurrency||d.concurrency))),batchSize:Math.min(500,Math.max(1,Number(l.batchSize||d.batchSize))),maxAttempts:Math.min(5,Math.max(1,Number(l.maxAttempts||2)))});return {render:{enabled:r.enabled===true,...Number.isInteger(n)&&n>0?{concurrency:n}:{},batchSize:Number.isInteger(s)&&s>0?Math.min(20,s):5,...Number.isInteger(o)&&o>0?{maxAttempts:Math.min(5,o)}:{}},rewrite:a(i,{concurrency:8,batchSize:25}),deploy:a(c,{concurrency:8,batchSize:50})}}function hs(e){if(!e||typeof e!="object")return;let t=e,r={};for(let s of ["accountId","siteId"]){let o=t[s];typeof o=="string"&&o.trim()!==""&&(r[s]=o.trim());}let n=Number(t.lastUpdate??0);return Number.isFinite(n)&&n>0&&(r.lastUpdate=Math.floor(n)),t.subscriber===true&&(r.subscriber=true),Object.keys(r).length>0?r:void 0}function Lt(e){let t=e&&typeof e=="object"?e:{},r=String(t.accountId??"").trim(),n=String(t.siteId??"").trim(),s=t.subscriber===true,o=hs(t.siteSettings),i={...o??{},...r?{accountId:o?.accountId??r}:{},...n?{siteId:o?.siteId??n}:{},...o?.subscriber===true||s?{subscriber:true}:{}},c={},a=String(t.apiBase??"").trim();a&&(c.apiBase=a);let l=String(t.runtimeToken??t.nonce??"").trim();l&&(c.runtimeToken=l);let d=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();d&&(c.virtualAssetBaseUrl=d),Object.keys(i).length>0&&(c.siteSettings=i);let u=Ut(t.subscriptionType);return u&&(c.subscriptionType=u),c}function fs(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function kr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function ws(e,t){let r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[n,s]of new Headers(t.headers).entries())r.set(n,s);return r}async function Cr(e,t,r=5){let n=new URL(kr(e)),s=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),o=n.protocol==="http:"?cs:ls,i=ws(e,t);return await new Promise((c,a)=>{let l=o.request(n,{method:s,headers:Object.fromEntries(i.entries()),...n.protocol==="https:"?{rejectUnauthorized:false}:{}},d=>{let u=[];d.on("data",m=>{u.push(Buffer.isBuffer(m)?m:Buffer.from(m));}),d.on("error",a),d.on("end",()=>{let m=d.statusCode??0,h=d.headers.location;if(r>0&&h&&[301,302,303,307,308].includes(m)){c(Cr(new URL(h,n),{method:m===303?"GET":s},r-1));return}let f=new Headers;for(let[b,p]of Object.entries(d.headers))Array.isArray(p)?f.set(b,p.join(", ")):typeof p=="string"&&f.set(b,p);c(new Response(Buffer.concat(u),{status:m,statusText:d.statusMessage??"",headers:f}));});});l.on("error",a),l.end();})}function ys(e){let t=Lt(e.wpsuite),r={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},n=String(r.accountId??"").trim(),s=String(r.siteId??"").trim(),o=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...o?{virtualAssetBaseUrl:o}:{},...Object.keys(r).length>0?{siteSettings:r}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!n||!s||!o)return false;fs(e.sourceOrigin);let i=globalThis,a={...i.WpSuite??{},siteSettings:r,uploadUrl:o};return t.apiBase&&(a.apiBase=t.apiBase),i.WpSuite=a,true}async function bs(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!ys(e)){let s=e.wpsuite?.siteSettings,o=[String(s?.accountId??"").trim()?"":"accountId",String(s?.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): ${o.join(", ")}.`,requests:[]}}}let r=globalThis.fetch,n=[];try{typeof r=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(a,l)=>{let d=kr(a);if(d.startsWith(t)){let u=(()=>{try{return new URL(d).pathname}catch{return d}})();try{let m=e.ignoreHttpsErrors&&d.startsWith("https://")?await Cr(a,l):await r(a,l);return n.push({path:u,status:m.status,ok:m.ok,error:null}),m}catch(m){throw n.push({path:u,status:null,ok:!1,error:m instanceof Error?m.message:String(m)}),m}}return r(a,l)}));let{getConfig:s}=await import('@smart-cloud/wpsuite-core'),o=await s("publisher"),i=o&&typeof o=="object"?o:null,c=Ut(i?.subscriptionType);return {remote:i,diagnostic:{status:i?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:c??null,error:i?null:"WP Suite publisher config loader returned no configuration.",requests:n}}}catch(s){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:s instanceof Error?s.message:String(s),requests:n}}}finally{typeof r=="function"&&(globalThis.fetch=r);}}function Ss(e,t){let r=ps(t?.deploymentProfiles),n=String(t?.defaultDeploymentProfile??"").trim(),s=r[n]?n:"",o=Ut(t?.subscriptionType),i=Lt(e.wpsuite);return {...e,scheduler:vr(t?.scheduler),deploymentProfiles:r,defaultDeploymentProfile:s,...o?{subscriptionType:o}:{},wpsuite:{...i,...i.siteSettings||o?{siteSettings:{...i.siteSettings??{},...i.siteSettings?.subscriber===true||o==="PROFESSIONAL"||o==="AGENCY"?{subscriber:true}:{}}}:{},...o?{subscriptionType:o}:{}}}}function jt(e,t){let n=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!n)return t;let s=n.split("/").map(o=>o.trim()).filter(o=>o.length>0&&o!=="."&&o!=="..");return s.length>0?s.join("/"):t}function Ps(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function Pr(e,t,r){let n=String(t||"").trim();return n&&S.isAbsolute(n)?S.resolve(n):S.resolve(e,jt(n,r))}async function st(e,t={}){let r=String("").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",n=await $.readFile(r,"utf8"),s=JSON.parse(n);s.sourceOrigin=s.sourceOrigin.replace(/\/$/,""),s.targetOrigin=Rr(s.targetOrigin),s.ignoreHttpsErrors??=false,s.outputDir=String(s.outputDir||"export").trim()||"export",s.urlRewriteMode||=s.targetOrigin==="."?"relative":"absolute",s.noJavaScriptRenderPathPrefixes||=[],s.seedPaths||=[],s.generated404RequestPath=ds(s.generated404RequestPath),s.sitemapPaths||=[...Ot],s.allowedAssetHosts||=[],s.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],s.blockedPathPrefixes||=[],s.blockedSearchFragments||=[],s.pageCache={purgeBeforeCrawl:s.pageCache?.purgeBeforeCrawl===true};let o=Number(s.processingConcurrency)>0?Math.min(100,Math.max(1,Number(s.processingConcurrency))):null;s.concurrency=o??s.concurrency??1,s.maxPages||=0,s.extraReplacements=$t(s.extraReplacements),s.postCrawlCopyMap=$t(s.postCrawlCopyMap),s.logDir=String(s.logDir||"logs").trim()||"logs",s.verbose??=false,s.logLevel||=s.verbose?"debug":"info",s.s3SyncMode||="sdk-upload-delete",s.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},s.readiness.timeoutMs??=1500,s.readiness.fallbackWaitMs??=1500,s.viewport||={width:1440,height:1200},s.navigationTimeoutMs||=3e4,s.assetDownloadConcurrency=o??(Number(s.assetDownloadConcurrency)>0?Number(s.assetDownloadConcurrency):s.concurrency),s.rewriteConcurrency=o??(Number(s.rewriteConcurrency)>0?Number(s.rewriteConcurrency):s.assetDownloadConcurrency),s.wpsuite=Lt(s.wpsuite),s.scheduler=vr(void 0),s.remoteWorkers=gs(s.remoteWorkers),typeof s.lambdaDelegationEnabled=="boolean"&&(s.remoteWorkers.render??={},s.remoteWorkers.rewrite??={},s.remoteWorkers.deploy??={},s.remoteWorkers.render.enabled=s.lambdaDelegationEnabled,s.remoteWorkers.rewrite.enabled=s.lambdaDelegationEnabled,s.remoteWorkers.deploy.enabled=s.lambdaDelegationEnabled),o!==null&&(s.processingConcurrency=o,s.remoteWorkers.render??={},s.remoteWorkers.rewrite??={},s.remoteWorkers.deploy??={},s.remoteWorkers.render.concurrency=o,s.remoteWorkers.rewrite.concurrency=o,s.remoteWorkers.deploy.concurrency=o),s.deploymentProfiles={},s.defaultDeploymentProfile="",s.deploymentTargetOverride=String(s.deploymentTargetOverride??"").trim();let i=await bs(s);t.onRemotePublisherConfigDiagnostic?.(i.diagnostic);let c=Ss(s,i.remote),a=Ps(),l=a?S.resolve(a,".."):"";return l?(c.outputDir=Pr(l,c.outputDir,"export"),c.logDir=Pr(l,c.logDir,"logs")):(S.isAbsolute(c.outputDir)||(c.outputDir=jt(c.outputDir,"export")),S.isAbsolute(c.logDir)||(c.logDir=jt(c.logDir,"logs"))),c}function ce(e,t=10){return Ar.createHash("sha1").update(e).digest("hex").slice(0,t)}async function Rs(e){await $.mkdir(S.dirname(e),{recursive:true});}async function be(e,t,r){await Rs(e);let n=S.join(S.dirname(e),`.${S.basename(e)}.${process.pid}.${Date.now()}.${Ar.randomBytes(6).toString("hex")}.tmp`);try{typeof t=="string"?await $.writeFile(n,t,r??"utf8"):await $.writeFile(n,t),await $.rename(n,e);}catch(s){throw await $.unlink(n).catch(()=>{}),s}}function le(e){return [".html",".htm",".css",".js",".mjs",".json",".xml",".xsl",".txt",".svg",".map",".enc",".jws"].includes(S.extname(e).toLowerCase())}function Se(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 je(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ot(e){return e.replace(/\//g,"\\/")}function xr(e){return e.replace(/\//g,"\\\\/")}function vs(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let r=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${r}`}catch{return null}}function Tr(e,t,r){if(!t)return;e[t]=r;let n=ot(t),s=ot(r);e[n]=s;let o=xr(t),i=xr(r);e[o]=i;let c=je(t),a=je(r);e[c]=a;let l=je(n),d=je(s);e[l]=d;let u=je(o),m=je(i);e[u]=m;}function it(e,t,r){Tr(e,t,r);let n=vs(t);n&&n!==t&&Tr(e,n,r);}function Dt(e,t){let r=t.startsWith("/")?t:`/${t}`,n=(e||"").replace(/\/$/,"");return !n||n==="."||n==="/"?r:`${n}${r}`}function Ir(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function Er(e,t,r){if(!t)return r;let n=S.dirname(S.resolve(t)),s=S.resolve(e,r.replace(/^\/+/,"")),o=S.relative(n,s).replace(/\\/g,"/");return o?(o.startsWith(".")||(o=`./${o}`),o):"."}async function qt(e,t){return (t?[...new Set(t)].map(n=>S.resolve(n)).filter(n=>n.startsWith(S.resolve(e.outputDir))).map(n=>S.relative(e.outputDir,n).replace(/\\/g,"/")).filter(n=>n.length>0):await ks(["**/*"],{cwd:e.outputDir,onlyFiles:true,dot:true})).filter(n=>n!=="asset-map.json"&&le(n))}var As=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],Is=new Set([".html",".htm"]),Or="WPSuite.io Static Publisher",Es=Or.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ms(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function $s(e,t,r){return Ms(t)?e.replace(new RegExp(`(?<!:)${Os(t)}`,"g"),r):e.split(t).join(r)}function js(e,t,r){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!r)return false;let s=S.extname(r).toLowerCase();return Is.has(s)?/<head\b|<html\b|<!doctype html/i.test(t):false}function Us(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${Es}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${Or}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let n=e.includes(`\r
1
+ import {request,chromium}from'playwright';import $,{readFile}from'fs/promises';import S from'path';import {gunzipSync}from'zlib';import {setTimeout as setTimeout$1}from'timers/promises';import ks from'fast-glob';import Yr from'mime-types';import Ar,{createHash}from'crypto';import cs from'http';import ls from'https';import {availableParallelism}from'os';import {Worker}from'worker_threads';import {LambdaClient,InvokeCommand}from'@aws-sdk/client-lambda';import {DynamoDBClient,GetItemCommand}from'@aws-sdk/client-dynamodb';import {S3Client,GetObjectCommand,PutObjectCommand,CopyObjectCommand}from'@aws-sdk/client-s3';import {fromTemporaryCredentials}from'@aws-sdk/credential-providers';async function dr(e){await e.addInitScript(()=>{let t=window,r=[],n=new WeakSet,s=new WeakSet;Object.defineProperty(t,"__WPSUITE_STATIC_SERIALIZATION_STATE__",{value:{snapshots:r,runtimeCreatedElements:s},configurable:true});let o=Document.prototype.createElement;Document.prototype.createElement=function(m,h){let f=o.call(this,m,h);return s.add(f),f};let i=u=>{!(u instanceof Element)||n.has(u)||(n.add(u),r.push({host:u,pristine:u.cloneNode(true),sourceOwned:!s.has(u)}));},c=Element.prototype.attachShadow;Element.prototype.attachShadow=function(m){return i(this),c.call(this,m)};let a=new WeakSet,l=u=>{if(typeof u!="object"&&typeof u!="function"||u===null||a.has(u))return u;let m=u;if(typeof m.createRoot!="function")return u;let h=m.createRoot,f=function(b,...p){return i(b),Reflect.apply(h,this,[b,...p])};try{Object.defineProperty(m,"createRoot",{...Object.getOwnPropertyDescriptor(m,"createRoot"),value:f}),a.add(u);}catch{}return u},d=u=>{let m=l(t[u]);try{Object.defineProperty(t,u,{configurable:!0,enumerable:!0,get:()=>m,set:h=>{m=l(h);}});}catch{l(t[u]);}};d("ReactDOM"),d("ReactDOMClient");});}async function Tt(e){return e.evaluate(()=>{let t=window.__WPSUITE_STATIC_SERIALIZATION_STATE__,r=/^data-(?:[a-z0-9]+-)*(?:bound|initialized|mounted|hydrated)$/i;document.querySelectorAll("*").forEach(s=>{for(let o of [...s.attributes])r.test(o.name)&&s.removeAttribute(o.name);}),document.querySelectorAll("script, style, link, iframe").forEach(s=>{t?.runtimeCreatedElements.has(s)&&s.remove();});for(let s of t?.snapshots??[])s.host.isConnected&&(s.sourceOwned?s.host.replaceWith(s.pristine.cloneNode(true)):s.host.remove());for(let s of [document.head,document.body])for(let o of [...s.children])t?.runtimeCreatedElements.has(o)&&o.remove();return document.querySelectorAll("#wpsuite-consent-root, .grecaptcha-badge, iframe[src*='/recaptcha/']").forEach(s=>s.remove()),document.documentElement.classList.remove("wpsuite-consent-scroll-locked"),document.body.classList.remove("wpsuite-consent-scroll-locked"),`${document.doctype?new XMLSerializer().serializeToString(document.doctype):""}${document.documentElement.outerHTML}`})}var Yn=".deploy-plan.json",Xn="deploy-plan.json",es=".crawl-incomplete.json",ts="crawl-incomplete.json";function pr(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function mr(e){let t=String(e||"").replace(/\\/g,"/").replace(/^\/+/,"").trim(),r=S.posix.normalize(t);return !t||!r||r==="."||/^[a-zA-Z]:/.test(r)||r.startsWith("../")||r===".."?null:r}function rs(e){let t=String(e||"").trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("*")||t.includes("#"))return null;try{let r=new URL(t,"https://content-sync.invalid");return r.origin!=="https://content-sync.invalid"?null:`${S.posix.normalize(r.pathname)}${r.search}`}catch{return null}}function ue(e){return [...new Set(e.map(mr).filter(t=>t!==null))]}function ns(e,t){let r={generatedAt:String(t.generatedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir),runMode:t.runMode,crawlMode:t.crawlMode,fullSyncRequired:!!t.fullSyncRequired,changedFiles:ue(t.changedFiles||[]),deletedFiles:ue(t.deletedFiles||[]),rewriteTargets:ue(t.rewriteTargets||[]),revalidateFiles:ue(t.revalidateFiles||[])};return t.schemaVersion===2?{...r,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(),resolvedSitemapUrls:[...new Set((t.resolvedSitemapUrls||[]).map(n=>String(n||"").trim()).filter(n=>{try{let s=new URL(n);return s.protocol==="http:"||s.protocol==="https:"}catch{return false}}))],uploadGroups:{assets:ue(t.uploadGroups?.assets||[]),content:ue(t.uploadGroups?.content||[]),listings:ue(t.uploadGroups?.listings||[]),resources:ue(t.uploadGroups?.resources||[]),sitemapLeaves:ue(t.uploadGroups?.sitemapLeaves||[]),sitemapIndexes:ue(t.uploadGroups?.sitemapIndexes||[])},invalidationPaths:[...new Set((t.invalidationPaths||[]).map(rs).filter(n=>n!==null))].sort()}:{schemaVersion:1,...r,runMode:t.runMode}}function gr(e){let t=S.join(S.resolve(e.outputDir),Yn),r=pr();return r?[S.join(r,Xn),t]:[t]}function hr(e){let t=S.join(S.resolve(e.outputDir),es),r=pr();return r?[S.join(r,ts),t]:[t]}function X(e,t){let r=S.resolve(e),n=S.resolve(t),s=S.relative(r,n).replace(/\\/g,"/");return mr(s)}async function At(e,t){let r=ns(e,t);for(let n of gr(e)){await $.mkdir(S.dirname(n),{recursive:true});let s=`${n}.${process.pid}.${Date.now()}.tmp`;await $.writeFile(s,JSON.stringify(r,null,2),"utf8"),await $.rename(s,n);}}async function fr(e){for(let t of gr(e))try{await $.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}async function It(e,t){let r={schemaVersion:1,startedAt:String(t.startedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir)};for(let n of hr(e)){await $.mkdir(S.dirname(n),{recursive:true});let s=`${n}.${process.pid}.tmp`;await $.writeFile(s,JSON.stringify(r,null,2),"utf8"),await $.rename(s,n);}}async function wr(e){for(let t of hr(e))try{await $.unlink(t);}catch(r){if(r.code!=="ENOENT")throw r}}function os(e){return new URL(e).pathname.split("/").filter(Boolean).some(r=>{try{return decodeURIComponent(r).endsWith("__trashed")}catch{return r.endsWith("__trashed")}})}function Et(e){return Array.isArray(e)?e.map(Et):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Et(r)])):e}function is(e){return JSON.stringify(Et(e))}function as(e){return createHash("sha256").update(is(e)).digest("hex")}function yr(e){let{impactHash:t,...r}=e;if(e.schemaVersion!==1||!t)throw new Error("Invalid content-sync impact plan schema.");if(!Array.isArray(e.resourceRenderUrls)||!Array.isArray(e.resourceDeleteUrls))throw new Error("Invalid content-sync resource impact contract.");if(as(r)!==t)throw new Error("Content-sync impact plan hash mismatch.");for(let n of [...e.directRenderUrls,...e.deleteUrls,...e.resourceRenderUrls,...e.resourceDeleteUrls])if(os(n))throw new Error(`Content-sync impact contains a WordPress trash alias instead of the last public URL: ${n}`)}var Ot=["/sitemap_index.xml","/wp-sitemap.xml","/sitemap.xml"];function br(e){let t=new Set;for(let r of [...e,...Ot]){let n=String(r||"").trim();n&&t.add(n);}return [...t]}function Mt(e){let t=e.pathname.toLowerCase();return t.endsWith(".xml")&&(t.includes("sitemap")||t.endsWith("/sitemap.xml"))}function Sr(e){if(!e||!/^https?:\/\//i.test(e))return false;try{return Mt(new URL(e))}catch{return false}}function Rr(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function ds(e){let t=String(e??"").trim();if(!t)return "";let r=t;if(/^https?:\/\//i.test(r))try{r=new URL(r).pathname;}catch{return ""}if(r=r.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!r)return "";let n=r.endsWith("/"),s=r.replace(/^\/+/,"").split("/").map(i=>i.replace(/[^A-Za-z0-9._-]/g,"")).filter(i=>i.length>0&&i!=="."&&i!=="..");if(s.length===0)return "";let o=`/${s.join("/")}`;return n&&S.extname(o)===""&&(o+="/"),o==="/"?"":o}function $t(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t.trim(),String(r??"")]).filter(([t])=>t.length>0))}function ps(e){if(!e||typeof e!="object")return {};let t={};for(let[r,n]of Object.entries(e)){let s=r.trim();if(!s||!n||typeof n!="object")continue;let o=n,i={};if(typeof o.targetOrigin=="string"){let a=Rr(o.targetOrigin);a&&(i.targetOrigin=a);}let c=$t(o.extraReplacements);if(Object.keys(c).length>0&&(i.extraReplacements=c),o.s3&&typeof o.s3=="object"){let a={},l=o.s3;typeof l.bucket=="string"&&(a.bucket=l.bucket.trim()),typeof l.prefix=="string"&&(a.prefix=l.prefix.trim()),typeof l.region=="string"&&(a.region=l.region.trim()),typeof l.htmlCacheControl=="string"&&(a.htmlCacheControl=l.htmlCacheControl.trim()),typeof l.assetCacheControl=="string"&&(a.assetCacheControl=l.assetCacheControl.trim()),Object.keys(a).length>0&&(i.s3=a);}if(o.cloudFront&&typeof o.cloudFront=="object"){let a={},l=o.cloudFront;typeof l.distributionId=="string"&&(a.distributionId=l.distributionId.trim()),Array.isArray(l.invalidationPaths)&&(a.invalidationPaths=l.invalidationPaths.map(d=>String(d??"").trim()).filter(d=>d.length>0)),Object.keys(a).length>0&&(i.cloudFront=a);}t[s]=i;}return t}function Ut(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function ms(e,t){if(!e||typeof e!="object")return null;let r=e,n=r.command;if(n!=="publish"&&n!=="crawl"&&n!=="deploy"&&n!=="invalidate"&&n!=="retry-timeouts"&&n!=="url"&&n!=="content-sync")return null;let s=Number.parseInt(String(r.intervalMinutes??"0"),10);if(!Number.isFinite(s)||s<1)return null;let o=String(r.id??`${n}-${t+1}`).trim();if(!o)return null;let i=String(r.deploymentProfile??"").trim(),c=String(r.url??"").trim(),a=Array.isArray(r.postTypes)?[...new Set(r.postTypes.map(d=>String(d??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],l=Array.isArray(r.listingPaths)?[...new Set(r.listingPaths.map(d=>String(d??"").trim()).filter(Boolean))]:[];return n==="content-sync"&&a.length===0?null:{id:o,enabled:r.enabled!==false,command:n,intervalMinutes:s,...n==="publish"||n==="crawl"?{crawlMode:r.crawlMode==="incremental"?"incremental":"full"}:{},...(n==="publish"||n==="deploy"||n==="invalidate"||n==="content-sync")&&i?{deploymentProfile:i}:{},...c?{url:c}:{},...a.length>0?{postTypes:a}:{},...l.length>0?{listingPaths:l}:{},...typeof r.includeSubsites=="boolean"?{includeSubsites:r.includeSubsites}:{},...typeof r.includePostTypeArchives=="boolean"?{includePostTypeArchives:r.includePostTypeArchives}:{},...typeof r.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:r.includeTaxonomyArchives}:{},...typeof r.includeAuthorArchives=="boolean"?{includeAuthorArchives:r.includeAuthorArchives}:{},...typeof r.includeDateArchives=="boolean"?{includeDateArchives:r.includeDateArchives}:{},...typeof r.includePostsPage=="boolean"?{includePostsPage:r.includePostsPage}:{},...typeof r.includeSitemapChain=="boolean"?{includeSitemapChain:r.includeSitemapChain}:{}}}function vr(e){let t=e&&typeof e=="object"?e:{},r=Array.isArray(t.rules)?t.rules.map((n,s)=>ms(n,s)).filter(n=>!!n):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:r}}function gs(e){let t=e&&typeof e=="object"?e:{},r=t.render&&typeof t.render=="object"?t.render:{},n=Number(r.concurrency??0),s=Number(r.batchSize??0),o=Number(r.maxAttempts??0),i=t.rewrite&&typeof t.rewrite=="object"?t.rewrite:{},c=t.deploy&&typeof t.deploy=="object"?t.deploy:{},a=(l,d)=>({enabled:typeof l.enabled=="boolean"?l.enabled:r.enabled===true,concurrency:Math.min(100,Math.max(1,Number(l.concurrency||d.concurrency))),batchSize:Math.min(500,Math.max(1,Number(l.batchSize||d.batchSize))),maxAttempts:Math.min(5,Math.max(1,Number(l.maxAttempts||2)))});return {render:{enabled:r.enabled===true,...Number.isInteger(n)&&n>0?{concurrency:n}:{},batchSize:Number.isInteger(s)&&s>0?Math.min(20,s):5,...Number.isInteger(o)&&o>0?{maxAttempts:Math.min(5,o)}:{}},rewrite:a(i,{concurrency:8,batchSize:25}),deploy:a(c,{concurrency:8,batchSize:50})}}function hs(e){if(!e||typeof e!="object")return;let t=e,r={};for(let s of ["accountId","siteId"]){let o=t[s];typeof o=="string"&&o.trim()!==""&&(r[s]=o.trim());}let n=Number(t.lastUpdate??0);return Number.isFinite(n)&&n>0&&(r.lastUpdate=Math.floor(n)),t.subscriber===true&&(r.subscriber=true),Object.keys(r).length>0?r:void 0}function Lt(e){let t=e&&typeof e=="object"?e:{},r=String(t.accountId??"").trim(),n=String(t.siteId??"").trim(),s=t.subscriber===true,o=hs(t.siteSettings),i={...o??{},...r?{accountId:o?.accountId??r}:{},...n?{siteId:o?.siteId??n}:{},...o?.subscriber===true||s?{subscriber:true}:{}},c={},a=String(t.apiBase??"").trim();a&&(c.apiBase=a);let l=String(t.runtimeToken??t.nonce??"").trim();l&&(c.runtimeToken=l);let d=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();d&&(c.virtualAssetBaseUrl=d),Object.keys(i).length>0&&(c.siteSettings=i);let u=Ut(t.subscriptionType);return u&&(c.subscriptionType=u),c}function fs(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function kr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function ws(e,t){let r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[n,s]of new Headers(t.headers).entries())r.set(n,s);return r}async function Cr(e,t,r=5){let n=new URL(kr(e)),s=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),o=n.protocol==="http:"?cs:ls,i=ws(e,t);return await new Promise((c,a)=>{let l=o.request(n,{method:s,headers:Object.fromEntries(i.entries()),...n.protocol==="https:"?{rejectUnauthorized:false}:{}},d=>{let u=[];d.on("data",m=>{u.push(Buffer.isBuffer(m)?m:Buffer.from(m));}),d.on("error",a),d.on("end",()=>{let m=d.statusCode??0,h=d.headers.location;if(r>0&&h&&[301,302,303,307,308].includes(m)){c(Cr(new URL(h,n),{method:m===303?"GET":s},r-1));return}let f=new Headers;for(let[b,p]of Object.entries(d.headers))Array.isArray(p)?f.set(b,p.join(", ")):typeof p=="string"&&f.set(b,p);c(new Response(Buffer.concat(u),{status:m,statusText:d.statusMessage??"",headers:f}));});});l.on("error",a),l.end();})}function ys(e){let t=Lt(e.wpsuite),r={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},n=String(r.accountId??"").trim(),s=String(r.siteId??"").trim(),o=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...o?{virtualAssetBaseUrl:o}:{},...Object.keys(r).length>0?{siteSettings:r}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!n||!s||!o)return false;fs(e.sourceOrigin);let i=globalThis,a={...i.WpSuite??{},siteSettings:r,uploadUrl:o};return t.apiBase&&(a.apiBase=t.apiBase),i.WpSuite=a,true}async function bs(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!ys(e)){let s=e.wpsuite?.siteSettings,o=[String(s?.accountId??"").trim()?"":"accountId",String(s?.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): ${o.join(", ")}.`,requests:[]}}}let r=globalThis.fetch,n=[];try{typeof r=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(a,l)=>{let d=kr(a);if(d.startsWith(t)){let u=(()=>{try{return new URL(d).pathname}catch{return d}})();try{let m=e.ignoreHttpsErrors&&d.startsWith("https://")?await Cr(a,l):await r(a,l);return n.push({path:u,status:m.status,ok:m.ok,error:null}),m}catch(m){throw n.push({path:u,status:null,ok:!1,error:m instanceof Error?m.message:String(m)}),m}}return r(a,l)}));let{getConfig:s}=await import('@smart-cloud/wpsuite-core'),o=await s("publisher"),i=o&&typeof o=="object"?o:null,c=Ut(i?.subscriptionType);return {remote:i,diagnostic:{status:i?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:c??null,error:i?null:"WP Suite publisher config loader returned no configuration.",requests:n}}}catch(s){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:s instanceof Error?s.message:String(s),requests:n}}}finally{typeof r=="function"&&(globalThis.fetch=r);}}function Ss(e,t){let r=ps(t?.deploymentProfiles),n=String(t?.defaultDeploymentProfile??"").trim(),s=r[n]?n:"",o=Ut(t?.subscriptionType),i=Lt(e.wpsuite);return {...e,scheduler:vr(t?.scheduler),deploymentProfiles:r,defaultDeploymentProfile:s,...o?{subscriptionType:o}:{},wpsuite:{...i,...i.siteSettings||o?{siteSettings:{...i.siteSettings??{},...i.siteSettings?.subscriber===true||o==="PROFESSIONAL"||o==="AGENCY"?{subscriber:true}:{}}}:{},...o?{subscriptionType:o}:{}}}}function jt(e,t){let n=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!n)return t;let s=n.split("/").map(o=>o.trim()).filter(o=>o.length>0&&o!=="."&&o!=="..");return s.length>0?s.join("/"):t}function Ps(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function Pr(e,t,r){let n=String(t||"").trim();return n&&S.isAbsolute(n)?S.resolve(n):S.resolve(e,jt(n,r))}async function st(e,t={}){let r=String("").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",n=await $.readFile(r,"utf8"),s=JSON.parse(n);s.sourceOrigin=s.sourceOrigin.replace(/\/$/,""),s.targetOrigin=Rr(s.targetOrigin),s.ignoreHttpsErrors??=false,s.outputDir=String(s.outputDir||"export").trim()||"export",s.urlRewriteMode||=s.targetOrigin==="."?"relative":"absolute",s.noJavaScriptRenderPathPrefixes||=[],s.seedPaths||=[],s.generated404RequestPath=ds(s.generated404RequestPath),s.sitemapPaths||=[...Ot],s.allowedAssetHosts||=[],s.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],s.blockedPathPrefixes||=[],s.blockedSearchFragments||=[],s.pageCache={purgeBeforeCrawl:s.pageCache?.purgeBeforeCrawl===true};let o=Number(s.processingConcurrency)>0?Math.min(100,Math.max(1,Number(s.processingConcurrency))):null;s.concurrency=o??s.concurrency??1,s.maxPages||=0,s.extraReplacements=$t(s.extraReplacements),s.postCrawlCopyMap=$t(s.postCrawlCopyMap),s.logDir=String(s.logDir||"logs").trim()||"logs",s.verbose??=false,s.logLevel||=s.verbose?"debug":"info",s.s3SyncMode||="sdk-upload-delete",s.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},s.readiness.timeoutMs??=1500,s.readiness.fallbackWaitMs??=1500,s.viewport||={width:1440,height:1200},s.navigationTimeoutMs||=3e4,s.assetDownloadConcurrency=o??(Number(s.assetDownloadConcurrency)>0?Number(s.assetDownloadConcurrency):s.concurrency),s.rewriteConcurrency=o??(Number(s.rewriteConcurrency)>0?Number(s.rewriteConcurrency):s.assetDownloadConcurrency),s.wpsuite=Lt(s.wpsuite),s.scheduler=vr(void 0),s.remoteWorkers=gs(s.remoteWorkers),typeof s.lambdaDelegationEnabled=="boolean"&&(s.remoteWorkers.render??={},s.remoteWorkers.rewrite??={},s.remoteWorkers.deploy??={},s.remoteWorkers.render.enabled=s.lambdaDelegationEnabled,s.remoteWorkers.rewrite.enabled=s.lambdaDelegationEnabled,s.remoteWorkers.deploy.enabled=s.lambdaDelegationEnabled),o!==null&&(s.processingConcurrency=o,s.remoteWorkers.render??={},s.remoteWorkers.rewrite??={},s.remoteWorkers.deploy??={},s.remoteWorkers.render.concurrency=o,s.remoteWorkers.rewrite.concurrency=o,s.remoteWorkers.deploy.concurrency=o),s.deploymentProfiles={},s.defaultDeploymentProfile="",s.deploymentTargetOverride=String(s.deploymentTargetOverride??"").trim();let i=await bs(s);t.onRemotePublisherConfigDiagnostic?.(i.diagnostic);let c=Ss(s,i.remote),a=Ps(),l=a?S.resolve(a,".."):"";return l?(c.outputDir=Pr(l,c.outputDir,"export"),c.logDir=Pr(l,c.logDir,"logs")):(S.isAbsolute(c.outputDir)||(c.outputDir=jt(c.outputDir,"export")),S.isAbsolute(c.logDir)||(c.logDir=jt(c.logDir,"logs"))),c}function ce(e,t=10){return Ar.createHash("sha1").update(e).digest("hex").slice(0,t)}async function Rs(e){await $.mkdir(S.dirname(e),{recursive:true});}async function be(e,t,r){await Rs(e);let n=S.join(S.dirname(e),`.${S.basename(e)}.${process.pid}.${Date.now()}.${Ar.randomBytes(6).toString("hex")}.tmp`);try{typeof t=="string"?await $.writeFile(n,t,r??"utf8"):await $.writeFile(n,t),await $.rename(n,e);}catch(s){throw await $.unlink(n).catch(()=>{}),s}}function le(e){return [".html",".htm",".css",".js",".mjs",".json",".xml",".xsl",".txt",".svg",".map",".enc",".jws"].includes(S.extname(e).toLowerCase())}function Se(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 je(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ot(e){return e.replace(/\//g,"\\/")}function xr(e){return e.replace(/\//g,"\\\\/")}function vs(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let r=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${r}`}catch{return null}}function Tr(e,t,r){if(!t)return;e[t]=r;let n=ot(t),s=ot(r);e[n]=s;let o=xr(t),i=xr(r);e[o]=i;let c=je(t),a=je(r);e[c]=a;let l=je(n),d=je(s);e[l]=d;let u=je(o),m=je(i);e[u]=m;}function it(e,t,r){Tr(e,t,r);let n=vs(t);n&&n!==t&&Tr(e,n,r);}function Dt(e,t){let r=t.startsWith("/")?t:`/${t}`,n=(e||"").replace(/\/$/,"");return !n||n==="."||n==="/"?r:`${n}${r}`}function Ir(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function Er(e,t,r){if(!t)return r;let n=S.dirname(S.resolve(t)),s=S.resolve(e,r.replace(/^\/+/,"")),o=S.relative(n,s).replace(/\\/g,"/");return o?(o.startsWith(".")||(o=`./${o}`),o):"."}async function qt(e,t){return (t?[...new Set(t)].map(n=>S.resolve(n)).filter(n=>n.startsWith(S.resolve(e.outputDir))).map(n=>S.relative(e.outputDir,n).replace(/\\/g,"/")).filter(n=>n.length>0):await ks(["**/*"],{cwd:e.outputDir,onlyFiles:true,dot:true})).filter(n=>n!=="asset-map.json"&&le(n))}var As=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],Is=new Set([".html",".htm"]),Or="WPSuite.io Static Publisher",Es=Or.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ms(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function $s(e,t,r){return Ms(t)?e.replace(new RegExp(`(?<!:)${Os(t)}`,"g"),r):e.split(t).join(r)}function js(e,t,r){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!r)return false;let s=S.extname(r).toLowerCase();return Is.has(s)?/<head\b|<html\b|<!doctype html/i.test(t):false}function Us(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${Es}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${Or}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let n=e.includes(`\r
2
2
  `)?`\r
3
3
  `:`
4
4
  `;return e.replace(/<head\b[^>]*>/i,s=>`${s}${n} ${t}`)}function Ls(e){let t=Se(e).trim();return t.startsWith("{")||t.startsWith("[")||t.includes("\\/")||/"@context"|"@type"/.test(t)}function Ds(e,t){let r=[...new Set(t)].filter(o=>o.includes("/")&&!/\\+\//.test(o)).map(o=>[o,ot(o)]).filter(([o,i])=>o!==i).sort((o,i)=>i[0].length-o[0].length);if(!r.length)return e;let n=o=>{let i=o;for(let[c,a]of r)i=i.split(c).join(a);return i},s=e.replace(/(<script\b[^>]*\btype=["']application\/(?:ld\+)?json["'][^>]*>)([\s\S]*?)(<\/script>)/gi,(o,i,c,a)=>`${i}${n(c)}${a}`);return s=s.replace(/(<meta\b[^>]*\bcontent=(['"]))([\s\S]*?)(\2[^>]*>)/gi,(o,i,c,a,l)=>Ls(a)?`${i}${n(a)}${l}`:o),s}function Fs(e,t){if(!t)return null;let r=S.dirname(S.resolve(t)),n=S.resolve(e.outputDir),s=S.relative(r,n).replace(/\\/g,"/");return s?(s.startsWith(".")||(s=`./${s}`),s.endsWith("/")?s:`${s}/`):"./"}function Ws(e,t,r){let n=Fs(t,r);if(!n)return e;let s=e;for(let o of As){let i=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`(?:\\.{1,}/)+${i}`,"g"),a=new RegExp(`(?<!\\.)/${i}`,"g");s=s.replace(c,`${n}${o}`).replace(a,`${n}${o}`);let l=o.replace(/\//g,"\\/"),d=n.replace(/\//g,"\\/"),u=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),m=new RegExp(`(?:\\.{1,}\\\\/)+${u}`,"g"),h=new RegExp(`(?:\\.{1,}(?:\\\\/|\\\\))+${u}`,"g"),f=new RegExp(`(?<![\\.\\\\])\\/${u}`,"g");s=s.replace(m,`${d}${l}`).replace(h,`${d}${l}`).replace(f,`${d}${l}`);}return s}function Wt(e,t,r){if(e.urlRewriteMode==="absolute")return t;let n=(()=>{try{return new URL(t,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin)}catch{return null}})(),s=n?n.pathname:Ir(t,e.targetOrigin),o=n?`${n.search}${n.hash}`:"";return e.urlRewriteMode==="root-relative"?`${s}${o}`:`${Er(e.outputDir,r,s)}${o}`}function Ft(e,t,r,n,s){it(e,r,Wt(t,n,s));}function qs(e,t,r,n,s){if(!r||r===n)return;it(e,r,n);let o=Wt(t,r,s),i=Wt(t,n,s);it(e,o,i);}function Nt(e,t,r,n,s={}){let o=e,i={};Ft(i,t,t.sourceOrigin,t.targetOrigin,n);for(let[a,l]of Object.entries(t.extraReplacements))Ft(i,t,a,l,n);for(let[a,l]of Object.entries(r))Ft(i,t,a,l,n);for(let[a,l]of Object.entries(s)){let d=r[a];!d||d===l||qs(i,t,l,d,n);}let c=Object.entries(i).sort((a,l)=>l[0].length-a[0].length);for(let[a,l]of c)o=$s(o,a,l);return t.urlRewriteMode!=="absolute"&&(o=Ws(o,t,n)),o=Ds(o,c.map(([,a])=>a)),js(t,o,n)&&(o=Us(o)),o}async function Ns(e,t,r,n){let s=S.join(e.outputDir,n),o=S.extname(s).toLowerCase(),i;try{i=await $.readFile(s,"utf8");}catch(l){if(l.code!=="ENOENT")throw l;return {changed:false}}let a=Nt(i,e,t,o===".js"||o===".mjs"?void 0:s,r);return a!==i?(await be(s,a,"utf8"),{changed:true}):{changed:false}}async function _s(e,t){return await new Promise((r,n)=>{let s=a=>{if(c(),a?.error){n(new Error(a.error));return}r({changed:!!a?.changed});},o=a=>{c(),n(a);},i=a=>{c(),a!==0&&n(new Error(`Rewrite worker exited with code ${a}.`));},c=()=>{e.off("message",s),e.off("error",o),e.off("exit",i);};e.on("message",s),e.on("error",o),e.on("exit",i),e.postMessage({file:t});})}async function Mr(e,t,r={}){let n=await qt(e,r.files),s=0;if(n.length===0)return 0;let o=Math.max(1,Number(e.rewriteConcurrency||e.assetDownloadConcurrency||1)),i=Math.max(1,Math.min(o,n.length,availableParallelism()));await r.onStart?.({totalFiles:n.length,workerCount:i});let c=0,a=0,l=null;if(i===1){for(let u of n){let m=await Ns(e,t,r.previousAssetMap??{},u);m.changed&&(s+=1),a+=1,await r.onProgress?.({index:a,totalFiles:n.length,changedTextFiles:s,file:u,changed:m.changed});}return s}let d=Array.from({length:i},async()=>{let u=new Worker(new URL("./rewrite-worker.js",import.meta.url),{workerData:{config:e,assetMap:t,previousAssetMap:r.previousAssetMap??{}}});try{for(;!l;){let m=c;if(m>=n.length)return;c+=1;let h=n[m],f=await _s(u,h);f.changed&&(s+=1),a+=1,await r.onProgress?.({index:a,totalFiles:n.length,changedTextFiles:s,file:h,changed:f.changed});}}catch(m){throw l=m instanceof Error?m:new Error(String(m)),l}finally{await u.terminate().catch(()=>{});}});return await Promise.all(d),s}var Ae={error:0,warn:1,info:2,debug:3},Hs=/^(?:authorization|proxyAuthorization|runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken|xStaticPublisherToken|xApiKey)$/i;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]")}function ut(e){return typeof e=="string"?Pe(e):Array.isArray(e)?e.map(t=>ut(t)):e instanceof Error?{name:e.name,message:Pe(e.message),...e.stack?{stack:Pe(e.stack)}:{}}:e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Hs.test(t)?"[REDACTED]":ut(r)])):e}function _t(e){return e?ut(e):void 0}var $r=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",at=$r?S.join($r,"current-progress.json"):"",jr=Promise.resolve();function Ur(e){return e.includes("crawl")?"crawl":e.includes("deploy")?"deploy":e.includes("invalidate")?"invalidate":e}function Bs(e,t){let r={...e},n=typeof e.phase=="string"?e.phase.trim():"",s=typeof t.phase=="string"?t.phase.trim():"";if(s!==""&&(s==="deploy"||s.startsWith("deploy-"))&&n!==s)for(let c of ["index","totalFiles","staged","uploaded","skipped","failed","deleted","workerCount","completedBatches","totalBatches"])delete r[c];let i=new Set(["pagesQueued","pagesRendered","assetsQueued","sitemapsQueued","pagesDiscovered","assetsDiscovered","sitemapsDiscovered","pagesSaved","assetsSaved","donePages","doneAssets","doneSitemaps","changedTextFiles","uploaded","failed","index","totalFiles","completedBatches","totalBatches","pageQueue","assetQueue","sitemapQueue"]);for(let[c,a]of Object.entries(t)){let l=r[c];if(typeof l=="number"&&typeof a=="number"&&i.has(c)){r[c]=Math.max(l,a);continue}r[c]=a;}return r}function Vs(e,t,r){at&&(jr=jr.then(async()=>{let n=new Date,s=n.toISOString();await $.mkdir(S.dirname(at),{recursive:true});let o=await $.readFile(at,"utf8").then(g=>JSON.parse(g)).catch(()=>null),i=o&&typeof o.details=="object"&&o.details?o.details:{},c=Ur(e),a=o?.currentStep||Ur(o?.source||""),l=o?.startedAt||s,d={...o?.stepDurationsSec??{}},u=o?.stepStartedAt||s;if(a&&a!==c&&o?.stepStartedAt){let g=Math.max(0,Math.round((n.getTime()-new Date(o.stepStartedAt).getTime())/1e3));d[a]=(d[a]??0)+g,u=s;}let m=Math.max(0,Math.round((n.getTime()-new Date(u).getTime())/1e3)),h=Math.max(0,Math.round((n.getTime()-new Date(l).getTime())/1e3)),f=Pe(t),b=_t(r)??{},p={checkedAt:s,source:e,message:f,details:Bs(i,b),startedAt:l,currentStep:c,stepStartedAt:u,stepElapsedSec:m,totalElapsedSec:h,stepDurationsSec:d};await $.writeFile(at,JSON.stringify(p,null,2),"utf8");}).catch(()=>{}));}async function zs(e,t){await $.mkdir(S.dirname(e),{recursive:true}),await $.appendFile(e,`${JSON.stringify(ut(t))}
@@ -1,7 +1,7 @@
1
- import {S3Client,HeadObjectCommand,CopyObjectCommand,DeleteObjectsCommand,PutObjectCommand,GetObjectCommand}from'@aws-sdk/client-s3';import {request,chromium}from'playwright';import {createHash}from'crypto';import {lookup}from'dns/promises';import {isIP}from'net';import E from'path';import'fast-glob';import {statfs,readdir,readFile,rm,mkdir}from'fs/promises';import'os';import'worker_threads';import {DynamoDBClient,UpdateItemCommand}from'@aws-sdk/client-dynamodb';import je from'mime-types';import {setTimeout}from'timers/promises';import {writeSync}from'fs';var P=1,Se=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function _(e,t){let r=String(e??"").trim();if(!Se.test(r))throw new Error(`${t} must match ${Se.source} and be at most 128 characters.`);return r}function U(e){let t=String(e??"").trim().replace(/^\/+|\/+$/g,"");if(!t)return "";let r=t.split("/").filter(Boolean);if(r.some(o=>o==="."||o===".."))throw new Error("S3 prefix contains an unsafe dot path segment.");return `${r.join("/")}/`}function v(e,...t){let r=U(e),o=t.map((n,s)=>{let a=String(n??"").replace(/^\/+|\/+$/g,"");if(!a||a.split("/").some(i=>i==="."||i===".."))throw new Error(`Unsafe S3 key segment at index ${s}.`);return a});return `${r}${o.join("/")}`}function z(e,t,r){return `${v(e,"jobs",_(t,"jobId"),"tasks",_(r,"taskId"))}/`}function L(e){return createHash("sha256").update(e).digest("hex")}function W(e,t){let r=String(e??"").replace(/^\/+/,""),o=U(t);if(!r||r.includes("\0"))throw new Error("S3 object key is empty or invalid.");if(o&&!r.startsWith(o))throw new Error(`S3 object key is outside the configured workspace prefix: ${r}`);if(r.split("/").some(n=>n===".."))throw new Error("S3 object key contains an unsafe parent segment.");return r}function O(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object.`);return e}function w(e,t){if(typeof e!="string"||!e.trim())throw new Error(`${t} must be a non-empty string.`);return e.trim()}function k(e,t,r,o){if(!Number.isInteger(e)||Number(e)<r||Number(e)>o)throw new Error(`${t} must be an integer between ${r} and ${o}.`);return Number(e)}function at(e){return e.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase()}function G(e){let t=e.split(".");if(t.length!==4)return null;let r=t.map(o=>Number(o));return r.every((o,n)=>Number.isInteger(o)&&o>=0&&o<=255&&String(o)===t[n])?r:null}function ae(e){let t=e.toLowerCase();if(t.includes("%")||t.split("::").length>2)return null;let r=t,o=r.lastIndexOf(":");if(r.includes(".")&&o>=0){let u=G(r.slice(o+1));if(!u)return null;r=`${r.slice(0,o)}:${((u[0]??0)*256+(u[1]??0)).toString(16)}:${((u[2]??0)*256+(u[3]??0)).toString(16)}`;}let[n,s]=r.split("::"),a=n?n.split(":"):[],i=s?s.split(":"):[],c=r.includes("::"),d=8-a.length-i.length;return c&&d<1||!c&&d!==0||[...a,...i].some(u=>!/^[0-9a-f]{1,4}$/.test(u))?null:[...a.map(u=>Number.parseInt(u,16)),...Array.from({length:d},()=>0),...i.map(u=>Number.parseInt(u,16))]}function ke(e){let t=G(e);if(!t)return "an invalid IPv4 address";let[r=0,o=0,n=0,s=0]=t;return r===0?"the unspecified/current-network IPv4 range":r===10||r===172&&o>=16&&o<=31||r===192&&o===168?"an RFC1918 private IPv4 range":r===127?"the IPv4 loopback range":r===169&&o===254?"the IPv4 link-local/metadata range":r===100&&o===100&&n===100&&s===200?"a cloud instance metadata endpoint":r===100&&o>=64&&o<=127?"the shared carrier-grade NAT IPv4 range":r===198&&(o===18||o===19)?"the IPv4 benchmarking range":r>=224&&r<=239?"the IPv4 multicast range":r>=240?"the reserved IPv4 range":null}function ct(e){let t=ae(e);if(!t||t.length!==8)return "an invalid IPv6 address";if(t.every(n=>n===0))return "the unspecified IPv6 address";if(t.slice(0,7).every(n=>n===0)&&t[7]===1)return "the IPv6 loopback address";let r=t[0]??0;if((r&65024)===64512)return "an IPv6 unique-local range";if((r&65472)===65152)return "the IPv6 link-local range";if((r&65280)===65280)return "the IPv6 multicast range";if(t.slice(0,5).every(n=>n===0)&&t[5]===65535){let n=t[6]??0,s=t[7]??0;return ke(`${n>>8}.${n&255}.${s>>8}.${s&255}`)}return null}function ce(e){return G(e)?ke(e):ae(e)?ct(e):"an invalid IP address"}function V(e,t){let r=w(e,t),o;try{o=new URL(r);}catch{throw new Error(`${t} must be a valid URL.`)}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`${t} must use HTTP or HTTPS.`);if(o.username||o.password)throw new Error(`${t} must not contain URL credentials.`);let n=at(o);if(!n)throw new Error(`${t} must contain a hostname.`);if(n==="localhost"||n.endsWith(".localhost"))throw new Error(`${t} must not target localhost.`);if(n==="metadata.google.internal")throw new Error(`${t} must not target a cloud instance metadata endpoint.`);if(G(n)||ae(n)){let s=ce(n);if(s)throw new Error(`${t} must not target ${s}.`)}return o}function lt(e){let t=V(e.sourceOrigin,"sourceOrigin").origin;if(!Array.isArray(e.urls)||e.urls.length<1||e.urls.length>20)throw new Error("Render tasks require between 1 and 20 URLs.");for(let[s,a]of e.urls.entries())if(V(a,`urls[${s}]`).origin!==t)throw new Error(`urls[${s}] is outside sourceOrigin.`);let r=O(e.options,"options");if(typeof r.ignoreHttpsErrors!="boolean")throw new Error("options.ignoreHttpsErrors must be a boolean.");if(typeof r.javaScriptEnabled!="boolean")throw new Error("options.javaScriptEnabled must be a boolean.");let o=O(r.viewport,"options.viewport");k(o.width,"options.viewport.width",320,7680),k(o.height,"options.viewport.height",240,7680),k(r.navigationTimeoutMs,"options.navigationTimeoutMs",1e3,6e5),k(r.autoScrollTimeoutMs,"options.autoScrollTimeoutMs",0,12e4);let n=O(r.readiness,"options.readiness");for(let s of ["waitForSelector","waitForFunction"])if(n[s]!==null&&typeof n[s]!="string")throw new Error(`options.readiness.${s} must be a string or null.`);k(n.timeoutMs,"options.readiness.timeoutMs",0,12e4),k(n.fallbackWaitMs,"options.readiness.fallbackWaitMs",0,12e4);}function ut(e){if(!Array.isArray(e.urls)||e.urls.length<1||e.urls.length>20)throw new Error("Asset tasks require between 1 and 20 URLs.");for(let[r,o]of e.urls.entries())V(o,`urls[${r}]`);let t=O(e.options,"options");if(typeof t.ignoreHttpsErrors!="boolean")throw new Error("options.ignoreHttpsErrors must be a boolean.");k(t.timeoutMs,"options.timeoutMs",1e3,12e4);}function dt(e){if(w(e.configKey,"configKey"),w(e.assetMapKey,"assetMapKey"),e.previousAssetMapKey!==void 0&&w(e.previousAssetMapKey,"previousAssetMapKey"),!Array.isArray(e.items)||e.items.length<1||e.items.length>500)throw new Error("Rewrite tasks require between 1 and 500 objects.");for(let[t,r]of e.items.entries()){let o=O(r,`items[${t}]`);w(o.inputKey,`items[${t}].inputKey`),w(o.outputKey,`items[${t}].outputKey`),w(o.relativePath,`items[${t}].relativePath`),o.contentType!==void 0&&o.contentType!==null&&w(o.contentType,`items[${t}].contentType`);}}function pt(e){if(_(w(e.targetId,"targetId"),"targetId"),!Array.isArray(e.items)||e.items.length>1e3)throw new Error("Deploy copy tasks accept at most 1000 objects.");for(let[r,o]of e.items.entries()){let n=O(o,`items[${r}]`);w(n.sourceKey,`items[${r}].sourceKey`),w(n.targetRelativeKey,`items[${r}].targetRelativeKey`),w(n.sha256,`items[${r}].sha256`),n.normalizedSha256!==void 0&&w(n.normalizedSha256,`items[${r}].normalizedSha256`),k(n.bytes,`items[${r}].bytes`,0,Number.MAX_SAFE_INTEGER),w(n.contentType,`items[${r}].contentType`),w(n.cacheControl,`items[${r}].cacheControl`);}let t=e.deleteRelativeKeys??[];if(!Array.isArray(t)||t.length>1e3)throw new Error("Deploy copy tasks accept at most 1000 deletion keys.");for(let[r,o]of t.entries())w(o,`deleteRelativeKeys[${r}]`);if(e.items.length===0&&t.length===0)throw new Error("Deploy copy tasks require copy or deletion work.")}function Pe(e){if(!e||typeof e!="object")throw new Error("Worker event must be a JSON object.");let t=e;if(t.schemaVersion!==P)throw new Error(`Unsupported worker protocol version: ${String(t.schemaVersion)}.`);let r=t.operation;if(r!=="render"&&r!=="asset"&&r!=="rewrite"&&r!=="deploy-copy"&&r!=="health")throw new Error(`Unsupported worker operation: ${String(r)}.`);return _(String(t.jobId??""),"jobId"),_(String(t.taskId??""),"taskId"),r==="render"&&lt(t),r==="asset"&&ut(t),r==="rewrite"&&dt(t),r==="deploy-copy"&&pt(t),e}function ft(e){return e.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase()}async function ht(e){return (await lookup(e,{all:true,verbatim:true})).map(t=>t.address)}async function le(e,t,r=ht){let o=V(e,t),n=ft(o);if(isIP(n))return o;let s;try{s=await r(n);}catch{throw new Error(`${t} hostname could not be resolved safely.`)}if(s.length===0)throw new Error(`${t} hostname resolved to no addresses.`);for(let a of s){let i=ce(a);if(i)throw new Error(`${t} hostname resolves to ${i}.`)}return o}async function Ie(e,t=le){let r=null;return await e.route("**/*",async o=>{try{await t(o.request().url(),"render request");}catch(n){r??=n instanceof Error?n:new Error(String(n)),await o.abort("blockedbyclient").catch(()=>{});return}await o.continue();}),await e.routeWebSocket("**/*",async o=>{try{await t(o.url(),"render WebSocket request");}catch(n){r??=n instanceof Error?n:new Error(String(n)),await o.close({code:1008,reason:"Blocked by network policy"});return}await o.close({code:1008,reason:"Only HTTP(S) requests are allowed"}),r??=new Error("render WebSocket request must use HTTP or HTTPS.");}),{getViolation:()=>r}}function yt(e){return e.replace(/&amp;/gi,"&").replace(/&quot;/gi,'"').replace(/&#39;|&apos;/gi,"'").replace(/&lt;/gi,"<").replace(/&gt;/gi,">")}function Rt(e,t){let r=e.trim();if(!r||r.startsWith("data:")||r.startsWith("blob:")||r.startsWith("javascript:")||r.startsWith("#"))return null;try{let o=new URL(r,t);return o.protocol!=="http:"&&o.protocol!=="https:"||o.username||o.password?null:(o.hash="",o.toString())}catch{return null}}function C(e,t,r){let o=Rt(t,r);o&&e.add(o);}function bt(e,t,r){for(let o of t.split(",")){let n=o.trim().split(/\s+/,1)[0];n&&C(e,n,r);}}function ue(e,t,r=""){let o=new Set,n=yt(t).replace(/\\\//g,"/");for(let i of n.matchAll(/\b(?:src|href|poster|data-src|data-href|data-resource-url)\s*=\s*["']([^"']+)["']/gi))C(o,i[1]??"",e);for(let i of n.matchAll(/\b(?:srcset|data-srcset)\s*=\s*["']([^"']+)["']/gi))bt(o,i[1]??"",e);for(let i of n.matchAll(/url\(\s*(?:"([^"]+)"|'([^']+)'|([^)]*?))\s*\)/gi))C(o,i[1]??i[2]??i[3]??"",e);for(let i of n.matchAll(/@import\s+(?:url\()?\s*['"]?([^'"\s;)]+)['"]?\s*\)?/gi))C(o,i[1]??"",e);for(let i of n.matchAll(/<\?xml-stylesheet[^>]+href=["']([^"']+)["'][^>]*\?>/gi))C(o,i[1]??"",e);let s=(()=>{try{return E.extname(new URL(e).pathname).toLowerCase()}catch{return ""}})();if(s===".js"||s===".mjs"||/(?:java|ecma)script/i.test(r))for(let i of n.matchAll(/["']((?:\.\.?\/|\/)?[^"'\s]+\.(?:js|mjs)(?:[?#][^"']*)?)["']/gi))C(o,i[1]??"",e);return [...o].sort()}function ve(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 A(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function X(e){return e.replace(/\//g,"\\/")}function xe(e){return e.replace(/\//g,"\\\\/")}function Et(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let r=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${r}`}catch{return null}}function Te(e,t,r){if(!t)return;e[t]=r;let o=X(t),n=X(r);e[o]=n;let s=xe(t),a=xe(r);e[s]=a;let i=A(t),c=A(r);e[i]=c;let d=A(o),u=A(n);e[d]=u;let l=A(s),p=A(a);e[l]=p;}function Z(e,t,r){Te(e,t,r);let o=Et(t);o&&o!==t&&Te(e,o,r);}function Oe(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function We(e,t,r){if(!t)return r;let o=E.dirname(E.resolve(t)),n=E.resolve(e,r.replace(/^\/+/,"")),s=E.relative(o,n).replace(/\\/g,"/");return s?(s.startsWith(".")||(s=`./${s}`),s):"."}var St=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],kt=new Set([".html",".htm"]),Ce="WPSuite.io Static Publisher",Pt=Ce.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function It(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xt(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function Tt(e,t,r){return xt(t)?e.replace(new RegExp(`(?<!:)${It(t)}`,"g"),r):e.split(t).join(r)}function vt(e,t,r){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!r)return false;let n=E.extname(r).toLowerCase();return kt.has(n)?/<head\b|<html\b|<!doctype html/i.test(t):false}function Ot(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${Pt}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${Ce}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let o=e.includes(`\r
1
+ import {S3Client,HeadObjectCommand,CopyObjectCommand,DeleteObjectsCommand,PutObjectCommand,GetObjectCommand}from'@aws-sdk/client-s3';import {request,chromium}from'playwright';import {createHash}from'crypto';import {lookup}from'dns/promises';import {isIP}from'net';import E from'path';import'fast-glob';import {statfs,readdir,readFile,rm,mkdir}from'fs/promises';import'os';import'worker_threads';import {DynamoDBClient,UpdateItemCommand}from'@aws-sdk/client-dynamodb';import je from'mime-types';import {setTimeout}from'timers/promises';import {writeSync}from'fs';var P=1,Se=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function _(e,t){let r=String(e??"").trim();if(!Se.test(r))throw new Error(`${t} must match ${Se.source} and be at most 128 characters.`);return r}function U(e){let t=String(e??"").trim().replace(/^\/+|\/+$/g,"");if(!t)return "";let r=t.split("/").filter(Boolean);if(r.some(o=>o==="."||o===".."))throw new Error("S3 prefix contains an unsafe dot path segment.");return `${r.join("/")}/`}function v(e,...t){let r=U(e),o=t.map((n,s)=>{let a=String(n??"").replace(/^\/+|\/+$/g,"");if(!a||a.split("/").some(i=>i==="."||i===".."))throw new Error(`Unsafe S3 key segment at index ${s}.`);return a});return `${r}${o.join("/")}`}function z(e,t,r){return `${v(e,"jobs",_(t,"jobId"),"tasks",_(r,"taskId"))}/`}function L(e){return createHash("sha256").update(e).digest("hex")}function C(e,t){let r=String(e??"").replace(/^\/+/,""),o=U(t);if(!r||r.includes("\0"))throw new Error("S3 object key is empty or invalid.");if(o&&!r.startsWith(o))throw new Error(`S3 object key is outside the configured workspace prefix: ${r}`);if(r.split("/").some(n=>n===".."))throw new Error("S3 object key contains an unsafe parent segment.");return r}function O(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object.`);return e}function w(e,t){if(typeof e!="string"||!e.trim())throw new Error(`${t} must be a non-empty string.`);return e.trim()}function k(e,t,r,o){if(!Number.isInteger(e)||Number(e)<r||Number(e)>o)throw new Error(`${t} must be an integer between ${r} and ${o}.`);return Number(e)}function at(e){return e.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase()}function G(e){let t=e.split(".");if(t.length!==4)return null;let r=t.map(o=>Number(o));return r.every((o,n)=>Number.isInteger(o)&&o>=0&&o<=255&&String(o)===t[n])?r:null}function ae(e){let t=e.toLowerCase();if(t.includes("%")||t.split("::").length>2)return null;let r=t,o=r.lastIndexOf(":");if(r.includes(".")&&o>=0){let u=G(r.slice(o+1));if(!u)return null;r=`${r.slice(0,o)}:${((u[0]??0)*256+(u[1]??0)).toString(16)}:${((u[2]??0)*256+(u[3]??0)).toString(16)}`;}let[n,s]=r.split("::"),a=n?n.split(":"):[],i=s?s.split(":"):[],c=r.includes("::"),d=8-a.length-i.length;return c&&d<1||!c&&d!==0||[...a,...i].some(u=>!/^[0-9a-f]{1,4}$/.test(u))?null:[...a.map(u=>Number.parseInt(u,16)),...Array.from({length:d},()=>0),...i.map(u=>Number.parseInt(u,16))]}function ke(e){let t=G(e);if(!t)return "an invalid IPv4 address";let[r=0,o=0,n=0,s=0]=t;return r===0?"the unspecified/current-network IPv4 range":r===10||r===172&&o>=16&&o<=31||r===192&&o===168?"an RFC1918 private IPv4 range":r===127?"the IPv4 loopback range":r===169&&o===254?"the IPv4 link-local/metadata range":r===100&&o===100&&n===100&&s===200?"a cloud instance metadata endpoint":r===100&&o>=64&&o<=127?"the shared carrier-grade NAT IPv4 range":r===198&&(o===18||o===19)?"the IPv4 benchmarking range":r>=224&&r<=239?"the IPv4 multicast range":r>=240?"the reserved IPv4 range":null}function ct(e){let t=ae(e);if(!t||t.length!==8)return "an invalid IPv6 address";if(t.every(n=>n===0))return "the unspecified IPv6 address";if(t.slice(0,7).every(n=>n===0)&&t[7]===1)return "the IPv6 loopback address";let r=t[0]??0;if((r&65024)===64512)return "an IPv6 unique-local range";if((r&65472)===65152)return "the IPv6 link-local range";if((r&65280)===65280)return "the IPv6 multicast range";if(t.slice(0,5).every(n=>n===0)&&t[5]===65535){let n=t[6]??0,s=t[7]??0;return ke(`${n>>8}.${n&255}.${s>>8}.${s&255}`)}return null}function ce(e){return G(e)?ke(e):ae(e)?ct(e):"an invalid IP address"}function V(e,t){let r=w(e,t),o;try{o=new URL(r);}catch{throw new Error(`${t} must be a valid URL.`)}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`${t} must use HTTP or HTTPS.`);if(o.username||o.password)throw new Error(`${t} must not contain URL credentials.`);let n=at(o);if(!n)throw new Error(`${t} must contain a hostname.`);if(n==="localhost"||n.endsWith(".localhost"))throw new Error(`${t} must not target localhost.`);if(n==="metadata.google.internal")throw new Error(`${t} must not target a cloud instance metadata endpoint.`);if(G(n)||ae(n)){let s=ce(n);if(s)throw new Error(`${t} must not target ${s}.`)}return o}function lt(e){let t=V(e.sourceOrigin,"sourceOrigin").origin;if(!Array.isArray(e.urls)||e.urls.length<1||e.urls.length>20)throw new Error("Render tasks require between 1 and 20 URLs.");for(let[s,a]of e.urls.entries())if(V(a,`urls[${s}]`).origin!==t)throw new Error(`urls[${s}] is outside sourceOrigin.`);let r=O(e.options,"options");if(typeof r.ignoreHttpsErrors!="boolean")throw new Error("options.ignoreHttpsErrors must be a boolean.");if(typeof r.javaScriptEnabled!="boolean")throw new Error("options.javaScriptEnabled must be a boolean.");let o=O(r.viewport,"options.viewport");k(o.width,"options.viewport.width",320,7680),k(o.height,"options.viewport.height",240,7680),k(r.navigationTimeoutMs,"options.navigationTimeoutMs",1e3,6e5),k(r.autoScrollTimeoutMs,"options.autoScrollTimeoutMs",0,12e4);let n=O(r.readiness,"options.readiness");for(let s of ["waitForSelector","waitForFunction"])if(n[s]!==null&&typeof n[s]!="string")throw new Error(`options.readiness.${s} must be a string or null.`);k(n.timeoutMs,"options.readiness.timeoutMs",0,12e4),k(n.fallbackWaitMs,"options.readiness.fallbackWaitMs",0,12e4);}function ut(e){if(!Array.isArray(e.urls)||e.urls.length<1||e.urls.length>20)throw new Error("Asset tasks require between 1 and 20 URLs.");for(let[r,o]of e.urls.entries())V(o,`urls[${r}]`);let t=O(e.options,"options");if(typeof t.ignoreHttpsErrors!="boolean")throw new Error("options.ignoreHttpsErrors must be a boolean.");k(t.timeoutMs,"options.timeoutMs",1e3,12e4);}function dt(e){if(w(e.configKey,"configKey"),w(e.assetMapKey,"assetMapKey"),e.previousAssetMapKey!==void 0&&w(e.previousAssetMapKey,"previousAssetMapKey"),!Array.isArray(e.items)||e.items.length<1||e.items.length>500)throw new Error("Rewrite tasks require between 1 and 500 objects.");for(let[t,r]of e.items.entries()){let o=O(r,`items[${t}]`);w(o.inputKey,`items[${t}].inputKey`),w(o.outputKey,`items[${t}].outputKey`),w(o.relativePath,`items[${t}].relativePath`),o.contentType!==void 0&&o.contentType!==null&&w(o.contentType,`items[${t}].contentType`);}}function pt(e){if(_(w(e.targetId,"targetId"),"targetId"),!Array.isArray(e.items)||e.items.length>1e3)throw new Error("Deploy copy tasks accept at most 1000 objects.");for(let[r,o]of e.items.entries()){let n=O(o,`items[${r}]`);w(n.sourceKey,`items[${r}].sourceKey`),w(n.targetRelativeKey,`items[${r}].targetRelativeKey`),w(n.sha256,`items[${r}].sha256`),n.normalizedSha256!==void 0&&w(n.normalizedSha256,`items[${r}].normalizedSha256`),k(n.bytes,`items[${r}].bytes`,0,Number.MAX_SAFE_INTEGER),w(n.contentType,`items[${r}].contentType`),w(n.cacheControl,`items[${r}].cacheControl`);}let t=e.deleteRelativeKeys??[];if(!Array.isArray(t)||t.length>1e3)throw new Error("Deploy copy tasks accept at most 1000 deletion keys.");for(let[r,o]of t.entries())w(o,`deleteRelativeKeys[${r}]`);if(e.items.length===0&&t.length===0)throw new Error("Deploy copy tasks require copy or deletion work.")}function Pe(e){if(!e||typeof e!="object")throw new Error("Worker event must be a JSON object.");let t=e;if(t.schemaVersion!==P)throw new Error(`Unsupported worker protocol version: ${String(t.schemaVersion)}.`);let r=t.operation;if(r!=="render"&&r!=="asset"&&r!=="rewrite"&&r!=="deploy-copy"&&r!=="health")throw new Error(`Unsupported worker operation: ${String(r)}.`);return _(String(t.jobId??""),"jobId"),_(String(t.taskId??""),"taskId"),r==="render"&&lt(t),r==="asset"&&ut(t),r==="rewrite"&&dt(t),r==="deploy-copy"&&pt(t),e}function ft(e){return e.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase()}async function ht(e){return (await lookup(e,{all:true,verbatim:true})).map(t=>t.address)}async function le(e,t,r=ht){let o=V(e,t),n=ft(o);if(isIP(n))return o;let s;try{s=await r(n);}catch{throw new Error(`${t} hostname could not be resolved safely.`)}if(s.length===0)throw new Error(`${t} hostname resolved to no addresses.`);for(let a of s){let i=ce(a);if(i)throw new Error(`${t} hostname resolves to ${i}.`)}return o}async function Ie(e,t=le){let r=null;return await e.route("**/*",async o=>{try{await t(o.request().url(),"render request");}catch(n){r??=n instanceof Error?n:new Error(String(n)),await o.abort("blockedbyclient").catch(()=>{});return}await o.continue();}),await e.routeWebSocket("**/*",async o=>{try{await t(o.url(),"render WebSocket request");}catch(n){r??=n instanceof Error?n:new Error(String(n)),await o.close({code:1008,reason:"Blocked by network policy"});return}await o.close({code:1008,reason:"Only HTTP(S) requests are allowed"}),r??=new Error("render WebSocket request must use HTTP or HTTPS.");}),{getViolation:()=>r}}function yt(e){return e.replace(/&amp;/gi,"&").replace(/&quot;/gi,'"').replace(/&#39;|&apos;/gi,"'").replace(/&lt;/gi,"<").replace(/&gt;/gi,">")}function Rt(e,t){let r=e.trim();if(!r||r.startsWith("data:")||r.startsWith("blob:")||r.startsWith("javascript:")||r.startsWith("#"))return null;try{let o=new URL(r,t);return o.protocol!=="http:"&&o.protocol!=="https:"||o.username||o.password?null:(o.hash="",o.toString())}catch{return null}}function W(e,t,r){let o=Rt(t,r);o&&e.add(o);}function bt(e,t,r){for(let o of t.split(",")){let n=o.trim().split(/\s+/,1)[0];n&&W(e,n,r);}}function ue(e,t,r=""){let o=new Set,n=yt(t).replace(/\\\//g,"/");for(let i of n.matchAll(/\b(?:src|href|poster|data-src|data-href|data-resource-url)\s*=\s*["']([^"']+)["']/gi))W(o,i[1]??"",e);for(let i of n.matchAll(/\b(?:srcset|data-srcset)\s*=\s*["']([^"']+)["']/gi))bt(o,i[1]??"",e);for(let i of n.matchAll(/url\(\s*(?:"([^"]+)"|'([^']+)'|([^)]*?))\s*\)/gi))W(o,i[1]??i[2]??i[3]??"",e);for(let i of n.matchAll(/@import\s+(?:url\()?\s*['"]?([^'"\s;)]+)['"]?\s*\)?/gi))W(o,i[1]??"",e);for(let i of n.matchAll(/<\?xml-stylesheet[^>]+href=["']([^"']+)["'][^>]*\?>/gi))W(o,i[1]??"",e);let s=(()=>{try{return E.extname(new URL(e).pathname).toLowerCase()}catch{return ""}})();if(s===".js"||s===".mjs"||/(?:java|ecma)script/i.test(r))for(let i of n.matchAll(/["']((?:\.\.?\/|\/)?[^"'\s]+\.(?:js|mjs)(?:[?#][^"']*)?)["']/gi))W(o,i[1]??"",e);return [...o].sort()}function ve(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 A(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function X(e){return e.replace(/\//g,"\\/")}function xe(e){return e.replace(/\//g,"\\\\/")}function Et(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let r=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${r}`}catch{return null}}function Te(e,t,r){if(!t)return;e[t]=r;let o=X(t),n=X(r);e[o]=n;let s=xe(t),a=xe(r);e[s]=a;let i=A(t),c=A(r);e[i]=c;let d=A(o),u=A(n);e[d]=u;let l=A(s),p=A(a);e[l]=p;}function Z(e,t,r){Te(e,t,r);let o=Et(t);o&&o!==t&&Te(e,o,r);}function Oe(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function Ce(e,t,r){if(!t)return r;let o=E.dirname(E.resolve(t)),n=E.resolve(e,r.replace(/^\/+/,"")),s=E.relative(o,n).replace(/\\/g,"/");return s?(s.startsWith(".")||(s=`./${s}`),s):"."}var St=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],kt=new Set([".html",".htm"]),We="WPSuite.io Static Publisher",Pt=We.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function It(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xt(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function Tt(e,t,r){return xt(t)?e.replace(new RegExp(`(?<!:)${It(t)}`,"g"),r):e.split(t).join(r)}function vt(e,t,r){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!r)return false;let n=E.extname(r).toLowerCase();return kt.has(n)?/<head\b|<html\b|<!doctype html/i.test(t):false}function Ot(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${Pt}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${We}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let o=e.includes(`\r
2
2
  `)?`\r
3
3
  `:`
4
- `;return e.replace(/<head\b[^>]*>/i,n=>`${n}${o} ${t}`)}function Wt(e){let t=ve(e).trim();return t.startsWith("{")||t.startsWith("[")||t.includes("\\/")||/"@context"|"@type"/.test(t)}function Ct(e,t){let r=[...new Set(t)].filter(s=>s.includes("/")&&!/\\+\//.test(s)).map(s=>[s,X(s)]).filter(([s,a])=>s!==a).sort((s,a)=>a[0].length-s[0].length);if(!r.length)return e;let o=s=>{let a=s;for(let[i,c]of r)a=a.split(i).join(c);return a},n=e.replace(/(<script\b[^>]*\btype=["']application\/(?:ld\+)?json["'][^>]*>)([\s\S]*?)(<\/script>)/gi,(s,a,i,c)=>`${a}${o(i)}${c}`);return n=n.replace(/(<meta\b[^>]*\bcontent=(['"]))([\s\S]*?)(\2[^>]*>)/gi,(s,a,i,c,d)=>Wt(c)?`${a}${o(c)}${d}`:s),n}function At(e,t){if(!t)return null;let r=E.dirname(E.resolve(t)),o=E.resolve(e.outputDir),n=E.relative(r,o).replace(/\\/g,"/");return n?(n.startsWith(".")||(n=`./${n}`),n.endsWith("/")?n:`${n}/`):"./"}function Mt(e,t,r){let o=At(t,r);if(!o)return e;let n=e;for(let s of St){let a=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(?:\\.{1,}/)+${a}`,"g"),c=new RegExp(`(?<!\\.)/${a}`,"g");n=n.replace(i,`${o}${s}`).replace(c,`${o}${s}`);let d=s.replace(/\//g,"\\/"),u=o.replace(/\//g,"\\/"),l=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),p=new RegExp(`(?:\\.{1,}\\\\/)+${l}`,"g"),m=new RegExp(`(?:\\.{1,}(?:\\\\/|\\\\))+${l}`,"g"),f=new RegExp(`(?<![\\.\\\\])\\/${l}`,"g");n=n.replace(p,`${u}${d}`).replace(m,`${u}${d}`).replace(f,`${u}${d}`);}return n}function pe(e,t,r){if(e.urlRewriteMode==="absolute")return t;let o=(()=>{try{return new URL(t,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin)}catch{return null}})(),n=o?o.pathname:Oe(t,e.targetOrigin),s=o?`${o.search}${o.hash}`:"";return e.urlRewriteMode==="root-relative"?`${n}${s}`:`${We(e.outputDir,r,n)}${s}`}function de(e,t,r,o,n){Z(e,r,pe(t,o,n));}function $t(e,t,r,o,n){if(!r||r===o)return;Z(e,r,o);let s=pe(t,r,n),a=pe(t,o,n);Z(e,s,a);}function Ae(e,t,r,o,n={}){let s=e,a={};de(a,t,t.sourceOrigin,t.targetOrigin,o);for(let[c,d]of Object.entries(t.extraReplacements))de(a,t,c,d,o);for(let[c,d]of Object.entries(r))de(a,t,c,d,o);for(let[c,d]of Object.entries(n)){let u=r[c];!u||u===d||$t(a,t,d,u,o);}let i=Object.entries(a).sort((c,d)=>d[0].length-c[0].length);for(let[c,d]of i)s=Tt(s,c,d);return t.urlRewriteMode!=="absolute"&&(s=Mt(s,t,o)),s=Ct(s,i.map(([,c])=>c)),vt(t,s,o)&&(s=Ot(s)),s}var me=String(process.env.PUBLISHER_PROGRESS_TABLE??"").trim(),Me=Number(process.env.PUBLISHER_PROGRESS_RETENTION_SECONDS??604800),Vt=Number.isFinite(Me)?Math.max(86400,Me):604800,$e=me?new DynamoDBClient({}):null;function Ut(e){return e.operation==="render"||e.operation==="asset"?e.urls.length:e.operation==="rewrite"?e.items.length:e.items.length+(e.deleteRelativeKeys?.length??0)}async function Lt(e){if(!(!$e||!me))try{let t=Math.floor(Date.now()/1e3)+Vt;await $e.send(new UpdateItemCommand({TableName:me,Key:{jobId:{S:e.jobId},taskId:{S:e.taskId}},UpdateExpression:"SET #operation = :operation, #status = :status, completedItems = :completedItems, failedItems = :failedItems, totalItems = :totalItems, #sequence = :sequence, updatedAt = :updatedAt, expiresAt = :expiresAt"+(e.requestId?", requestId = :requestId":""),ConditionExpression:"attribute_not_exists(#sequence) OR #sequence < :sequence",ExpressionAttributeNames:{"#operation":"operation","#status":"status","#sequence":"sequence"},ExpressionAttributeValues:{":operation":{S:e.operation},":status":{S:e.status},":completedItems":{N:String(e.completedItems)},":failedItems":{N:String(e.failedItems)},":totalItems":{N:String(e.totalItems)},":sequence":{N:String(e.sequence)},":updatedAt":{S:e.updatedAt},":expiresAt":{N:String(t)},...e.requestId?{":requestId":{S:e.requestId}}:{}}}));}catch(t){if(t.name==="ConditionalCheckFailedException")return;console.warn(JSON.stringify({message:"Remote worker progress status could not be written.",jobId:e.jobId,taskId:e.taskId,error:t instanceof Error?t.message:String(t)}));}}var Y=class{#t;#o;#e;#s;#i;#a=-1;#c=0;#n=0;#l=0;constructor(t,r,o=Lt){this.#t=t,this.#o=r??null,this.#e=Ut(t),this.#s=Math.max(1,Math.ceil(this.#e/20)),this.#i=o;}async started(){await this.#r("running",0,0,0);}async updated(t,r){this.#n=t,this.#l=r;let o=t+r,n=Date.now();o<this.#e&&o-this.#a<this.#s&&n-this.#c<5e3||await this.#r("running",t,r,o+1);}async completed(t){await this.#r(t.status,t.completedItems,t.failedItems,this.#e+2);}async failed(){let t=Math.min(this.#e-this.#n,Math.max(1,this.#l));await this.#r("failed",this.#n,t,this.#e+3);}async#r(t,r,o,n){this.#a=r+o,this.#c=Date.now(),await this.#i({jobId:this.#t.jobId,taskId:this.#t.taskId,operation:this.#t.operation,status:t,completedItems:r,failedItems:o,totalItems:this.#e,sequence:n,updatedAt:new Date().toISOString(),requestId:this.#o});}};var Dt=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\s*;.*)?$/u;function Kt(e){try{return new URL(e).pathname}catch{return e}}function Q(e,t,r){let o=String(e??"").trim();if(Dt.test(o))return o;let n=je.lookup(Kt(t));return n?je.contentType(n)||n:r}function ge(e){return String(e??"").split(";").map(t=>t.trim().toLowerCase()).filter(Boolean).join(";")}var Ue="playwright_chromiumdev_profile-",zt="/tmp/wpsuite-publisher-browser";function I(e){return Math.round(e/1024/1024*100)/100}async function _e(e){try{let t=await statfs(e),r=t.blocks*t.bsize,o=t.bavail*t.bsize;return {path:e,totalMiB:I(r),availableMiB:I(o),usedMiB:I(r-o)}}catch(t){return {path:e,totalMiB:null,availableMiB:null,usedMiB:null,error:t instanceof Error?t.message:String(t)}}}async function Gt(e){return (await fe(e)).filter(t=>t.startsWith(Ue))}async function fe(e){try{return (await readdir(e,{withFileTypes:!0})).map(t=>t.name).sort()}catch(t){if(t.code==="ENOENT")return [];throw t}}function he(){return E.resolve(process.env.PUBLISHER_BROWSER_TEMP_ROOT?.trim()||zt)}async function Le(e=he()){let t=Ke(e),r=E.join(t,"home"),o=E.join(t,"cache"),n=E.join(t,"config");await Promise.all([t,r,o,n].map(s=>mkdir(s,{recursive:true}))),process.env.TMPDIR=t,process.env.HOME=r,process.env.XDG_CACHE_HOME=o,process.env.XDG_CONFIG_HOME=n;}async function De(e=he()){let t=process.memoryUsage(),[r,o,n,s]=await Promise.all([_e(e),_e("/dev/shm"),Gt(e),fe(e)]);return {processMemoryMiB:{rss:I(t.rss),heapUsed:I(t.heapUsed),heapTotal:I(t.heapTotal),external:I(t.external),arrayBuffers:I(t.arrayBuffers)},tempStorage:r,sharedMemory:o,playwrightProfiles:{count:n.length,names:n.slice(0,20)},tempEntries:{count:s.length,names:s.slice(0,20)}}}function Ke(e){let t=E.resolve(e);if(t===E.parse(t).root)throw new Error(`Refusing to clean filesystem root: ${t}`);if(t==="/tmp"||t==="/var/tmp")throw new Error(`Refusing to clean shared temp root: ${t}`);return t}async function Be(e=he()){let t=Ke(e),r=await fe(t);for(let o of r)await rm(E.join(t,o),{recursive:true,force:true,maxRetries:3,retryDelay:50});return r}function Jt(e){let t=e.split("\0",1)[0]??"",r=E.basename(t).toLowerCase();return r.includes("chrome-headless-shell")||r==="chrome_crashpad_handler"||r==="chromium"||r==="chromium-browser"||e.includes(Ue)&&/(?:chrome|chromium)/i.test(e)}async function Ne(e="/proc",t=r=>process.kill(r,"SIGKILL")){let r;try{r=await readdir(e,{withFileTypes:!0});}catch(n){if(n.code==="ENOENT")return [];throw n}let o=[];for(let n of r){if(!n.isDirectory()||!/^\d+$/.test(n.name))continue;let s=Number(n.name);if(!Number.isSafeInteger(s)||s<1||s===process.pid)continue;let a;try{a=await readFile(E.join(e,n.name,"cmdline"),"utf8");}catch(i){if(["ENOENT","EACCES","EPERM","ESRCH"].includes(String(i.code)))continue;throw i}if(Jt(a))try{t(s),o.push(s);}catch(i){if(["ESRCH","EPERM"].includes(String(i.code)))continue;throw i}}return o.length>0&&await setTimeout(100),o.sort((n,s)=>n-s)}var K={},qe=false;function Zt(e){if(e)try{let t=new URL(e);return t.username="",t.password="",t.search="",t.hash="",t.toString()}catch{return}}function Fe(e){return {...e,...e.url?{url:Zt(e.url)}:{}}}function He(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,...e.stack?{errorStack:e.stack}:{}}:{error:String(e)}}function we(e,t={}){try{writeSync(2,`${JSON.stringify({level:"ERROR",message:"Remote worker runtime diagnostic.",event:e,...K,...t,timestamp:new Date().toISOString()})}
5
- `);}catch{}}function ze(){qe||(qe=true,process.on("uncaughtExceptionMonitor",(e,t)=>{we("runtime.uncaught-exception",{origin:t,...He(e)});}),process.on("exit",e=>{we("runtime.process-exit",{exitCode:e});}));}async function g(e,t,r={},o="info"){try{K=Fe(t);let n=null;try{n=await De();}catch(a){r={...r,resourceSnapshotError:a instanceof Error?a.message:String(a)};}let s=JSON.stringify({message:"Remote worker checkpoint.",event:e,...K,...r,...n?{resources:n}:{}});console[o](s);}catch(n){we("checkpoint.write-failed",{checkpointEvent:e,...He(n)});}}function ee(e){K=Fe(e);}function Ge(){K={};}async function Je(e){await e.addInitScript(()=>{let t=window,r=[],o=new WeakSet,n=new WeakSet;Object.defineProperty(t,"__WPSUITE_STATIC_SERIALIZATION_STATE__",{value:{snapshots:r,runtimeCreatedElements:n},configurable:true});let s=Document.prototype.createElement;Document.prototype.createElement=function(p,m){let f=s.call(this,p,m);return n.add(f),f};let a=l=>{!(l instanceof Element)||o.has(l)||(o.add(l),r.push({host:l,pristine:l.cloneNode(true),sourceOwned:!n.has(l)}));},i=Element.prototype.attachShadow;Element.prototype.attachShadow=function(p){return a(this),i.call(this,p)};let c=new WeakSet,d=l=>{if(typeof l!="object"&&typeof l!="function"||l===null||c.has(l))return l;let p=l;if(typeof p.createRoot!="function")return l;let m=p.createRoot,f=function(R,...x){return a(R),Reflect.apply(m,this,[R,...x])};try{Object.defineProperty(p,"createRoot",{...Object.getOwnPropertyDescriptor(p,"createRoot"),value:f}),c.add(l);}catch{}return l},u=l=>{let p=d(t[l]);try{Object.defineProperty(t,l,{configurable:!0,enumerable:!0,get:()=>p,set:m=>{p=d(m);}});}catch{d(t[l]);}};u("ReactDOM"),u("ReactDOMClient");});}async function Xe(e){return e.evaluate(()=>{let t=window.__WPSUITE_STATIC_SERIALIZATION_STATE__,r=/^data-(?:[a-z0-9]+-)*(?:bound|initialized|mounted|hydrated)$/i;document.querySelectorAll("*").forEach(n=>{for(let s of [...n.attributes])r.test(s.name)&&n.removeAttribute(s.name);}),document.querySelectorAll("script, style, link, iframe").forEach(n=>{t?.runtimeCreatedElements.has(n)&&n.remove();});for(let n of t?.snapshots??[])n.host.isConnected&&(n.sourceOwned?n.host.replaceWith(n.pristine.cloneNode(true)):n.host.remove());return document.querySelectorAll("#wpsuite-consent-root, .grecaptcha-badge, iframe[src*='/recaptcha/']").forEach(n=>n.remove()),document.documentElement.classList.remove("wpsuite-consent-scroll-locked"),document.body.classList.remove("wpsuite-consent-scroll-locked"),`${document.doctype?new XMLSerializer().serializeToString(document.doctype):""}${document.documentElement.outerHTML}`})}var M=String(process.env.PUBLISHER_WORKSPACE_BUCKET??"").trim(),S=U(process.env.PUBLISHER_WORKSPACE_PREFIX??""),te=String(process.env.PUBLISHER_ALLOWED_OPERATION??"").trim(),$=String(process.env.PUBLISHER_EXPORTER_VERSION??"unknown").trim(),B=String(process.env.PUBLISHER_PROXY_URL??"").trim(),sr=ir(process.env.PUBLISHER_ALLOWED_TARGETS??"[]"),et=new S3Client({}),Ze=new Map,b=null,N=false;ze();function ir(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>{if(!r||typeof r!="object")return !1;let o=r;return ["id","bucketName","prefix","region"].every(n=>typeof o[n]=="string")}).map(r=>({...r,prefix:U(r.prefix)})):[]}catch{return []}}function ye(){if(!M)throw new Error("PUBLISHER_WORKSPACE_BUCKET is required.")}async function Re(e,t){try{let r=await Ne();r.length>0&&await g(`browser.stale-processes-killed.${t}`,e,{killedProcesses:r.length,killedProcessIds:r},"warn");let o=await Be();o.length>0&&await g(`browser.temp-entries-removed.${t}`,e,{removedEntries:o.length,removedEntryNames:o.slice(0,20)}),await Le();}catch(r){if(await g(`browser.profile-cleanup-failed.${t}`,e,{error:r instanceof Error?r.message:String(r)},"error"),t==="before-launch")throw r}}async function ar(e){if(b){let r=await b.catch(()=>null);if(r?.isConnected())return r}await g("browser.launch-preparing",e),await Re(e,"before-launch"),await g("browser.launch-started",e);let t=chromium.launch({headless:true,args:["--no-sandbox","--disable-setuid-sandbox","--no-zygote","--disable-gpu"],...B?{proxy:{server:B}}:{}});b=t;try{let r=await t;return r.once("disconnected",()=>{b===t&&(b=null);let o=N;ee(e),g("browser.disconnected",e,{expected:o},o?"info":"error");}),await g("browser.launch-succeeded",e),r}catch(r){throw b===t&&(b=null),await g("browser.launch-failed",e,{error:r instanceof Error?r.message:String(r)},"error"),r}}async function tt(e){let t=b;if(b=null,t){let r=await t.catch(()=>null);r&&(N=true,await r.close().catch(async o=>{await g("browser.close-failed",e,{error:o instanceof Error?o.message:String(o)},"warn");}),N=false);}await Re(e,"after-close");}async function cr(e,t){let r;for(let o=1;o<=2;o+=1){let n=await ar({...t,attempt:o}),s=null;try{s=await n.newContext({viewport:e.options.viewport,ignoreHTTPSErrors:e.options.ignoreHttpsErrors,javaScriptEnabled:e.options.javaScriptEnabled,serviceWorkers:"block",userAgent:"WPSuiteStaticPublisher/remote-worker-v1"}),e.options.javaScriptEnabled&&await lr(s);let a=await Ie(s);return {context:s,page:await s.newPage(),networkPolicyViolation:a.getViolation}}catch(a){r=a,await s?.close().catch(()=>{}),b=null,N=true,await n.close().catch(()=>{}),N=false,await Re({...t,attempt:o},"after-close");}}throw r instanceof Error?r:new Error(`Unable to create a Chromium page: ${String(r)}`)}async function lr(e){await Je(e),await e.addInitScript(()=>{Object.defineProperty(window,"__WPSUITE_STATIC_EXPORT__",{value:true,writable:false,configurable:true});let t=r=>{if(r==null||String(r)==="")return true;try{let o=new URL(String(r),window.location.href),n=new URL(window.location.href);return o.hash="",n.hash="",o.href===n.href}catch{return false}};try{let r=window.location.assign.bind(window.location),o=window.location.replace.bind(window.location);Object.defineProperty(window.location,"assign",{configurable:!0,value:n=>{if(!t(n))return r(n)}}),Object.defineProperty(window.location,"replace",{configurable:!0,value:n=>{if(!t(n))return o(n)}}),Object.defineProperty(window.location,"reload",{configurable:!0,value:()=>{}});}catch{}});}async function ur(e,t){await e.evaluate(async r=>{await new Promise(o=>{let n=0,s=700,a=Date.now(),i=()=>{window.clearInterval(c),window.scrollTo(0,0),o();},c=window.setInterval(()=>{if(Date.now()-a>=r){i();return}window.scrollBy(0,s),n+=s;let d=Math.max(document.body?.scrollHeight||0,document.documentElement?.scrollHeight||0);n>=d+window.innerHeight&&i();},120);});},t);}async function rt(e){ye();let t=W(e,S),r=await et.send(new GetObjectCommand({Bucket:M,Key:t}));if(!r.Body)throw new Error(`S3 object has no body: ${t}`);return {body:await r.Body.transformToString("utf8"),contentType:r.ContentType?.trim()||null}}async function dr(e){return (await rt(e)).body}async function ne(e){return JSON.parse(await dr(e))}async function oe(e,t,r){ye();let o=W(e,S),n=typeof t=="string"?Buffer.from(t,"utf8"):t,s=await et.send(new PutObjectCommand({Bucket:M,Key:o,Body:n,ContentType:r,Metadata:{sha256:L(n)}}));return {bucket:M,key:o,sha256:L(n),bytes:n.byteLength,contentType:r,...s.ETag?{etag:s.ETag}:{},...s.VersionId?{versionId:s.VersionId}:{}}}async function pr(e,t){return await oe(e,`${JSON.stringify(t,null,2)}
4
+ `;return e.replace(/<head\b[^>]*>/i,n=>`${n}${o} ${t}`)}function Ct(e){let t=ve(e).trim();return t.startsWith("{")||t.startsWith("[")||t.includes("\\/")||/"@context"|"@type"/.test(t)}function Wt(e,t){let r=[...new Set(t)].filter(s=>s.includes("/")&&!/\\+\//.test(s)).map(s=>[s,X(s)]).filter(([s,a])=>s!==a).sort((s,a)=>a[0].length-s[0].length);if(!r.length)return e;let o=s=>{let a=s;for(let[i,c]of r)a=a.split(i).join(c);return a},n=e.replace(/(<script\b[^>]*\btype=["']application\/(?:ld\+)?json["'][^>]*>)([\s\S]*?)(<\/script>)/gi,(s,a,i,c)=>`${a}${o(i)}${c}`);return n=n.replace(/(<meta\b[^>]*\bcontent=(['"]))([\s\S]*?)(\2[^>]*>)/gi,(s,a,i,c,d)=>Ct(c)?`${a}${o(c)}${d}`:s),n}function At(e,t){if(!t)return null;let r=E.dirname(E.resolve(t)),o=E.resolve(e.outputDir),n=E.relative(r,o).replace(/\\/g,"/");return n?(n.startsWith(".")||(n=`./${n}`),n.endsWith("/")?n:`${n}/`):"./"}function Mt(e,t,r){let o=At(t,r);if(!o)return e;let n=e;for(let s of St){let a=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(?:\\.{1,}/)+${a}`,"g"),c=new RegExp(`(?<!\\.)/${a}`,"g");n=n.replace(i,`${o}${s}`).replace(c,`${o}${s}`);let d=s.replace(/\//g,"\\/"),u=o.replace(/\//g,"\\/"),l=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),p=new RegExp(`(?:\\.{1,}\\\\/)+${l}`,"g"),m=new RegExp(`(?:\\.{1,}(?:\\\\/|\\\\))+${l}`,"g"),f=new RegExp(`(?<![\\.\\\\])\\/${l}`,"g");n=n.replace(p,`${u}${d}`).replace(m,`${u}${d}`).replace(f,`${u}${d}`);}return n}function pe(e,t,r){if(e.urlRewriteMode==="absolute")return t;let o=(()=>{try{return new URL(t,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin)}catch{return null}})(),n=o?o.pathname:Oe(t,e.targetOrigin),s=o?`${o.search}${o.hash}`:"";return e.urlRewriteMode==="root-relative"?`${n}${s}`:`${Ce(e.outputDir,r,n)}${s}`}function de(e,t,r,o,n){Z(e,r,pe(t,o,n));}function $t(e,t,r,o,n){if(!r||r===o)return;Z(e,r,o);let s=pe(t,r,n),a=pe(t,o,n);Z(e,s,a);}function Ae(e,t,r,o,n={}){let s=e,a={};de(a,t,t.sourceOrigin,t.targetOrigin,o);for(let[c,d]of Object.entries(t.extraReplacements))de(a,t,c,d,o);for(let[c,d]of Object.entries(r))de(a,t,c,d,o);for(let[c,d]of Object.entries(n)){let u=r[c];!u||u===d||$t(a,t,d,u,o);}let i=Object.entries(a).sort((c,d)=>d[0].length-c[0].length);for(let[c,d]of i)s=Tt(s,c,d);return t.urlRewriteMode!=="absolute"&&(s=Mt(s,t,o)),s=Wt(s,i.map(([,c])=>c)),vt(t,s,o)&&(s=Ot(s)),s}var me=String(process.env.PUBLISHER_PROGRESS_TABLE??"").trim(),Me=Number(process.env.PUBLISHER_PROGRESS_RETENTION_SECONDS??604800),Vt=Number.isFinite(Me)?Math.max(86400,Me):604800,$e=me?new DynamoDBClient({}):null;function Ut(e){return e.operation==="render"||e.operation==="asset"?e.urls.length:e.operation==="rewrite"?e.items.length:e.items.length+(e.deleteRelativeKeys?.length??0)}async function Lt(e){if(!(!$e||!me))try{let t=Math.floor(Date.now()/1e3)+Vt;await $e.send(new UpdateItemCommand({TableName:me,Key:{jobId:{S:e.jobId},taskId:{S:e.taskId}},UpdateExpression:"SET #operation = :operation, #status = :status, completedItems = :completedItems, failedItems = :failedItems, totalItems = :totalItems, #sequence = :sequence, updatedAt = :updatedAt, expiresAt = :expiresAt"+(e.requestId?", requestId = :requestId":""),ConditionExpression:"attribute_not_exists(#sequence) OR #sequence < :sequence",ExpressionAttributeNames:{"#operation":"operation","#status":"status","#sequence":"sequence"},ExpressionAttributeValues:{":operation":{S:e.operation},":status":{S:e.status},":completedItems":{N:String(e.completedItems)},":failedItems":{N:String(e.failedItems)},":totalItems":{N:String(e.totalItems)},":sequence":{N:String(e.sequence)},":updatedAt":{S:e.updatedAt},":expiresAt":{N:String(t)},...e.requestId?{":requestId":{S:e.requestId}}:{}}}));}catch(t){if(t.name==="ConditionalCheckFailedException")return;console.warn(JSON.stringify({message:"Remote worker progress status could not be written.",jobId:e.jobId,taskId:e.taskId,error:t instanceof Error?t.message:String(t)}));}}var Y=class{#t;#o;#e;#s;#i;#a=-1;#c=0;#n=0;#l=0;constructor(t,r,o=Lt){this.#t=t,this.#o=r??null,this.#e=Ut(t),this.#s=Math.max(1,Math.ceil(this.#e/20)),this.#i=o;}async started(){await this.#r("running",0,0,0);}async updated(t,r){this.#n=t,this.#l=r;let o=t+r,n=Date.now();o<this.#e&&o-this.#a<this.#s&&n-this.#c<5e3||await this.#r("running",t,r,o+1);}async completed(t){await this.#r(t.status,t.completedItems,t.failedItems,this.#e+2);}async failed(){let t=Math.min(this.#e-this.#n,Math.max(1,this.#l));await this.#r("failed",this.#n,t,this.#e+3);}async#r(t,r,o,n){this.#a=r+o,this.#c=Date.now(),await this.#i({jobId:this.#t.jobId,taskId:this.#t.taskId,operation:this.#t.operation,status:t,completedItems:r,failedItems:o,totalItems:this.#e,sequence:n,updatedAt:new Date().toISOString(),requestId:this.#o});}};var Dt=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\s*;.*)?$/u;function Kt(e){try{return new URL(e).pathname}catch{return e}}function Q(e,t,r){let o=String(e??"").trim();if(Dt.test(o))return o;let n=je.lookup(Kt(t));return n?je.contentType(n)||n:r}function ge(e){return String(e??"").split(";").map(t=>t.trim().toLowerCase()).filter(Boolean).join(";")}var Ue="playwright_chromiumdev_profile-",zt="/tmp/wpsuite-publisher-browser";function I(e){return Math.round(e/1024/1024*100)/100}async function _e(e){try{let t=await statfs(e),r=t.blocks*t.bsize,o=t.bavail*t.bsize;return {path:e,totalMiB:I(r),availableMiB:I(o),usedMiB:I(r-o)}}catch(t){return {path:e,totalMiB:null,availableMiB:null,usedMiB:null,error:t instanceof Error?t.message:String(t)}}}async function Gt(e){return (await fe(e)).filter(t=>t.startsWith(Ue))}async function fe(e){try{return (await readdir(e,{withFileTypes:!0})).map(t=>t.name).sort()}catch(t){if(t.code==="ENOENT")return [];throw t}}function he(){return E.resolve(process.env.PUBLISHER_BROWSER_TEMP_ROOT?.trim()||zt)}async function Le(e=he()){let t=Ke(e),r=E.join(t,"home"),o=E.join(t,"cache"),n=E.join(t,"config");await Promise.all([t,r,o,n].map(s=>mkdir(s,{recursive:true}))),process.env.TMPDIR=t,process.env.HOME=r,process.env.XDG_CACHE_HOME=o,process.env.XDG_CONFIG_HOME=n;}async function De(e=he()){let t=process.memoryUsage(),[r,o,n,s]=await Promise.all([_e(e),_e("/dev/shm"),Gt(e),fe(e)]);return {processMemoryMiB:{rss:I(t.rss),heapUsed:I(t.heapUsed),heapTotal:I(t.heapTotal),external:I(t.external),arrayBuffers:I(t.arrayBuffers)},tempStorage:r,sharedMemory:o,playwrightProfiles:{count:n.length,names:n.slice(0,20)},tempEntries:{count:s.length,names:s.slice(0,20)}}}function Ke(e){let t=E.resolve(e);if(t===E.parse(t).root)throw new Error(`Refusing to clean filesystem root: ${t}`);if(t==="/tmp"||t==="/var/tmp")throw new Error(`Refusing to clean shared temp root: ${t}`);return t}async function Be(e=he()){let t=Ke(e),r=await fe(t);for(let o of r)await rm(E.join(t,o),{recursive:true,force:true,maxRetries:3,retryDelay:50});return r}function Jt(e){let t=e.split("\0",1)[0]??"",r=E.basename(t).toLowerCase();return r.includes("chrome-headless-shell")||r==="chrome_crashpad_handler"||r==="chromium"||r==="chromium-browser"||e.includes(Ue)&&/(?:chrome|chromium)/i.test(e)}async function Ne(e="/proc",t=r=>process.kill(r,"SIGKILL")){let r;try{r=await readdir(e,{withFileTypes:!0});}catch(n){if(n.code==="ENOENT")return [];throw n}let o=[];for(let n of r){if(!n.isDirectory()||!/^\d+$/.test(n.name))continue;let s=Number(n.name);if(!Number.isSafeInteger(s)||s<1||s===process.pid)continue;let a;try{a=await readFile(E.join(e,n.name,"cmdline"),"utf8");}catch(i){if(["ENOENT","EACCES","EPERM","ESRCH"].includes(String(i.code)))continue;throw i}if(Jt(a))try{t(s),o.push(s);}catch(i){if(["ESRCH","EPERM"].includes(String(i.code)))continue;throw i}}return o.length>0&&await setTimeout(100),o.sort((n,s)=>n-s)}var K={},qe=false;function Zt(e){if(e)try{let t=new URL(e);return t.username="",t.password="",t.search="",t.hash="",t.toString()}catch{return}}function Fe(e){return {...e,...e.url?{url:Zt(e.url)}:{}}}function He(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,...e.stack?{errorStack:e.stack}:{}}:{error:String(e)}}function we(e,t={}){try{writeSync(2,`${JSON.stringify({level:"ERROR",message:"Remote worker runtime diagnostic.",event:e,...K,...t,timestamp:new Date().toISOString()})}
5
+ `);}catch{}}function ze(){qe||(qe=true,process.on("uncaughtExceptionMonitor",(e,t)=>{we("runtime.uncaught-exception",{origin:t,...He(e)});}),process.on("exit",e=>{we("runtime.process-exit",{exitCode:e});}));}async function g(e,t,r={},o="info"){try{K=Fe(t);let n=null;try{n=await De();}catch(a){r={...r,resourceSnapshotError:a instanceof Error?a.message:String(a)};}let s=JSON.stringify({message:"Remote worker checkpoint.",event:e,...K,...r,...n?{resources:n}:{}});console[o](s);}catch(n){we("checkpoint.write-failed",{checkpointEvent:e,...He(n)});}}function ee(e){K=Fe(e);}function Ge(){K={};}async function Je(e){await e.addInitScript(()=>{let t=window,r=[],o=new WeakSet,n=new WeakSet;Object.defineProperty(t,"__WPSUITE_STATIC_SERIALIZATION_STATE__",{value:{snapshots:r,runtimeCreatedElements:n},configurable:true});let s=Document.prototype.createElement;Document.prototype.createElement=function(p,m){let f=s.call(this,p,m);return n.add(f),f};let a=l=>{!(l instanceof Element)||o.has(l)||(o.add(l),r.push({host:l,pristine:l.cloneNode(true),sourceOwned:!n.has(l)}));},i=Element.prototype.attachShadow;Element.prototype.attachShadow=function(p){return a(this),i.call(this,p)};let c=new WeakSet,d=l=>{if(typeof l!="object"&&typeof l!="function"||l===null||c.has(l))return l;let p=l;if(typeof p.createRoot!="function")return l;let m=p.createRoot,f=function(R,...x){return a(R),Reflect.apply(m,this,[R,...x])};try{Object.defineProperty(p,"createRoot",{...Object.getOwnPropertyDescriptor(p,"createRoot"),value:f}),c.add(l);}catch{}return l},u=l=>{let p=d(t[l]);try{Object.defineProperty(t,l,{configurable:!0,enumerable:!0,get:()=>p,set:m=>{p=d(m);}});}catch{d(t[l]);}};u("ReactDOM"),u("ReactDOMClient");});}async function Xe(e){return e.evaluate(()=>{let t=window.__WPSUITE_STATIC_SERIALIZATION_STATE__,r=/^data-(?:[a-z0-9]+-)*(?:bound|initialized|mounted|hydrated)$/i;document.querySelectorAll("*").forEach(n=>{for(let s of [...n.attributes])r.test(s.name)&&n.removeAttribute(s.name);}),document.querySelectorAll("script, style, link, iframe").forEach(n=>{t?.runtimeCreatedElements.has(n)&&n.remove();});for(let n of t?.snapshots??[])n.host.isConnected&&(n.sourceOwned?n.host.replaceWith(n.pristine.cloneNode(true)):n.host.remove());for(let n of [document.head,document.body])for(let s of [...n.children])t?.runtimeCreatedElements.has(s)&&s.remove();return document.querySelectorAll("#wpsuite-consent-root, .grecaptcha-badge, iframe[src*='/recaptcha/']").forEach(n=>n.remove()),document.documentElement.classList.remove("wpsuite-consent-scroll-locked"),document.body.classList.remove("wpsuite-consent-scroll-locked"),`${document.doctype?new XMLSerializer().serializeToString(document.doctype):""}${document.documentElement.outerHTML}`})}var M=String(process.env.PUBLISHER_WORKSPACE_BUCKET??"").trim(),S=U(process.env.PUBLISHER_WORKSPACE_PREFIX??""),te=String(process.env.PUBLISHER_ALLOWED_OPERATION??"").trim(),$=String(process.env.PUBLISHER_EXPORTER_VERSION??"unknown").trim(),B=String(process.env.PUBLISHER_PROXY_URL??"").trim(),sr=ir(process.env.PUBLISHER_ALLOWED_TARGETS??"[]"),et=new S3Client({}),Ze=new Map,b=null,N=false;ze();function ir(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>{if(!r||typeof r!="object")return !1;let o=r;return ["id","bucketName","prefix","region"].every(n=>typeof o[n]=="string")}).map(r=>({...r,prefix:U(r.prefix)})):[]}catch{return []}}function ye(){if(!M)throw new Error("PUBLISHER_WORKSPACE_BUCKET is required.")}async function Re(e,t){try{let r=await Ne();r.length>0&&await g(`browser.stale-processes-killed.${t}`,e,{killedProcesses:r.length,killedProcessIds:r},"warn");let o=await Be();o.length>0&&await g(`browser.temp-entries-removed.${t}`,e,{removedEntries:o.length,removedEntryNames:o.slice(0,20)}),await Le();}catch(r){if(await g(`browser.profile-cleanup-failed.${t}`,e,{error:r instanceof Error?r.message:String(r)},"error"),t==="before-launch")throw r}}async function ar(e){if(b){let r=await b.catch(()=>null);if(r?.isConnected())return r}await g("browser.launch-preparing",e),await Re(e,"before-launch"),await g("browser.launch-started",e);let t=chromium.launch({headless:true,args:["--no-sandbox","--disable-setuid-sandbox","--no-zygote","--disable-gpu"],...B?{proxy:{server:B}}:{}});b=t;try{let r=await t;return r.once("disconnected",()=>{b===t&&(b=null);let o=N;ee(e),g("browser.disconnected",e,{expected:o},o?"info":"error");}),await g("browser.launch-succeeded",e),r}catch(r){throw b===t&&(b=null),await g("browser.launch-failed",e,{error:r instanceof Error?r.message:String(r)},"error"),r}}async function tt(e){let t=b;if(b=null,t){let r=await t.catch(()=>null);r&&(N=true,await r.close().catch(async o=>{await g("browser.close-failed",e,{error:o instanceof Error?o.message:String(o)},"warn");}),N=false);}await Re(e,"after-close");}async function cr(e,t){let r;for(let o=1;o<=2;o+=1){let n=await ar({...t,attempt:o}),s=null;try{s=await n.newContext({viewport:e.options.viewport,ignoreHTTPSErrors:e.options.ignoreHttpsErrors,javaScriptEnabled:e.options.javaScriptEnabled,serviceWorkers:"block",userAgent:"WPSuiteStaticPublisher/remote-worker-v1"}),e.options.javaScriptEnabled&&await lr(s);let a=await Ie(s);return {context:s,page:await s.newPage(),networkPolicyViolation:a.getViolation}}catch(a){r=a,await s?.close().catch(()=>{}),b=null,N=true,await n.close().catch(()=>{}),N=false,await Re({...t,attempt:o},"after-close");}}throw r instanceof Error?r:new Error(`Unable to create a Chromium page: ${String(r)}`)}async function lr(e){await Je(e),await e.addInitScript(()=>{Object.defineProperty(window,"__WPSUITE_STATIC_EXPORT__",{value:true,writable:false,configurable:true});let t=r=>{if(r==null||String(r)==="")return true;try{let o=new URL(String(r),window.location.href),n=new URL(window.location.href);return o.hash="",n.hash="",o.href===n.href}catch{return false}};try{let r=window.location.assign.bind(window.location),o=window.location.replace.bind(window.location);Object.defineProperty(window.location,"assign",{configurable:!0,value:n=>{if(!t(n))return r(n)}}),Object.defineProperty(window.location,"replace",{configurable:!0,value:n=>{if(!t(n))return o(n)}}),Object.defineProperty(window.location,"reload",{configurable:!0,value:()=>{}});}catch{}});}async function ur(e,t){await e.evaluate(async r=>{await new Promise(o=>{let n=0,s=700,a=Date.now(),i=()=>{window.clearInterval(c),window.scrollTo(0,0),o();},c=window.setInterval(()=>{if(Date.now()-a>=r){i();return}window.scrollBy(0,s),n+=s;let d=Math.max(document.body?.scrollHeight||0,document.documentElement?.scrollHeight||0);n>=d+window.innerHeight&&i();},120);});},t);}async function rt(e){ye();let t=C(e,S),r=await et.send(new GetObjectCommand({Bucket:M,Key:t}));if(!r.Body)throw new Error(`S3 object has no body: ${t}`);return {body:await r.Body.transformToString("utf8"),contentType:r.ContentType?.trim()||null}}async function dr(e){return (await rt(e)).body}async function ne(e){return JSON.parse(await dr(e))}async function oe(e,t,r){ye();let o=C(e,S),n=typeof t=="string"?Buffer.from(t,"utf8"):t,s=await et.send(new PutObjectCommand({Bucket:M,Key:o,Body:n,ContentType:r,Metadata:{sha256:L(n)}}));return {bucket:M,key:o,sha256:L(n),bytes:n.byteLength,contentType:r,...s.ETag?{etag:s.ETag}:{},...s.VersionId?{versionId:s.VersionId}:{}}}async function pr(e,t){return await oe(e,`${JSON.stringify(t,null,2)}
6
6
  `,"application/json; charset=utf-8")}async function mr(e){try{let t=await ne(e);return t.response??t}catch(t){if(t.name==="NoSuchKey"||t.$metadata?.httpStatusCode===404)return null;throw t}}function re(e){return [...new Set(e)].filter(t=>{try{let r=new URL(t);return (r.protocol==="http:"||r.protocol==="https:")&&!r.username&&!r.password}catch{return false}}).sort()}async function gr(e,t,r,o){let n=null,s=null,a,i=new Set;try{let c=await cr(e,o);n=c.context,s=c.page,a=c.networkPolicyViolation,s.on("request",y=>i.add(y.url()));let d=await s.goto(t,{waitUntil:"domcontentloaded",timeout:e.options.navigationTimeoutMs});e.options.readiness.waitForSelector&&await s.waitForSelector(e.options.readiness.waitForSelector,{timeout:e.options.readiness.timeoutMs}).catch(()=>{}),e.options.javaScriptEnabled&&e.options.readiness.waitForFunction&&await s.waitForFunction(e.options.readiness.waitForFunction,void 0,{timeout:e.options.readiness.timeoutMs}).catch(()=>{}),e.options.javaScriptEnabled?await ur(s,e.options.autoScrollTimeoutMs):await s.waitForLoadState("load",{timeout:e.options.readiness.timeoutMs}).catch(()=>{}),e.options.readiness.fallbackWaitMs>0&&await s.waitForTimeout(e.options.readiness.fallbackWaitMs);let u=a?.();if(u)throw u;let l=await s.evaluate(()=>{let y=(T,nt)=>{let se=[];for(let ot of document.querySelectorAll(T))for(let be of nt){let ie=ot.getAttribute(be);if(ie)if(be.includes("srcset"))for(let st of ie.split(",")){let Ee=st.trim().split(/\s+/,1)[0];Ee&&se.push(Ee);}else se.push(ie);}return se},j=T=>{try{return new URL(T,document.baseURI).href}catch{return null}};return {links:y("a[href]",["href"]).map(j).filter(T=>T!==null),assets:y("img,script,link,source,video,audio,iframe,[data-src],[data-href],[data-resource-url]",["src","href","srcset","data-src","data-srcset","data-href","data-resource-url","poster"]).map(j).filter(T=>T!==null)}}),p=await Xe(s),m=a();if(m)throw m;let f=new URL(t),R=re(l.links).filter(y=>{let j=new URL(y);return j.hash="",j.origin===f.origin}),x=v(z(S,e.jobId,e.taskId),"pages",`${String(r).padStart(4,"0")}-${L(t).slice(0,24)}.html`),q=Q(d?.headers()["content-type"],s.url()||t,"text/html; charset=utf-8"),F=await oe(x,p,q),h=(await n.cookies()).map(y=>({name:y.name,domain:y.domain,path:y.path,expires:y.expires,httpOnly:y.httpOnly,secure:y.secure,sameSite:y.sameSite,..."partitionKey"in y?{partitioned:!0}:{}})),H=d?.status()??null;return {requestedUrl:t,finalUrl:s?.url()||null,outcome:H!==null&&H>=400?"http-error":"rendered",httpStatus:H,contentType:q,html:F,discoveredPages:R,discoveredAssets:re([...l.assets,...ue(s.url()||t,p,d?.headers()["content-type"]??"text/html")]),networkUrls:re([...i]),cookies:h}}catch(c){return {requestedUrl:t,finalUrl:s?.url()||null,outcome:"failed",httpStatus:null,contentType:null,html:null,discoveredPages:[],discoveredAssets:[],networkUrls:re([...i]),cookies:[],error:c instanceof Error?c.message:String(c)}}finally{await n?.close().catch(()=>{});}}function fr(e){return e.outcome==="failed"&&typeof e.error=="string"&&/(?:target page, context or browser has been closed|browser closed|connection closed)/i.test(e.error)}async function hr(e,t,r,o){let n=null;for(let s=1;s<=2;s+=1){let a={requestId:t.awsRequestId,jobId:e.jobId,taskId:e.taskId,operation:e.operation,pageIndex:o,url:r,attempt:s,remainingTimeMs:t.getRemainingTimeInMillis?.()};ee(a),await g("render.page-started",a);let i=await gr(e,r,o,a);n=i;let c=fr(i);if(c&&await tt(a),await g(c?"render.page-browser-closed":"render.page-finished",{...a,remainingTimeMs:t.getRemainingTimeInMillis?.()},{outcome:i.outcome,httpStatus:i.httpStatus,...i.error?{error:i.error.split(`
7
- `,1)[0]}:{}},i.outcome==="failed"?"warn":"info"),!c||s===2)return i;await g("render.page-retry-with-fresh-browser",a,{nextAttempt:s+1},"warn");}if(n)return n;throw new Error(`Remote render did not produce a result for ${r}.`)}function wr(e,t){let r=t.toLowerCase();if(r.startsWith("text/")||r.includes("javascript")||r.includes("json")||r.includes("xml")||r.includes("svg"))return true;try{return /\.(?:css|js|mjs|json|xml|xsl|svg|txt|map|html?)$/i.test(new URL(e).pathname)}catch{return false}}async function yr(e,t,r){let o=t;for(let n=0;n<=5;n+=1){await le(o,"asset request");let s=await e.get(o,{timeout:r,failOnStatusCode:false,maxRedirects:0}),a=s.status();if(a<300||a>=400)return s;let i=s.headers().location;if(!i)return s;if(n===5)throw await s.dispose(),new Error("Asset request exceeded five redirects.");o=new URL(i,o).toString(),await s.dispose();}throw new Error("Asset redirect handling failed.")}async function Rr(e,t,r){if(!Array.isArray(e.urls)||e.urls.length<1||e.urls.length>20)throw new Error("Asset tasks require between 1 and 20 URLs.");let o=await request.newContext({ignoreHTTPSErrors:e.options.ignoreHttpsErrors,userAgent:"WPSuiteStaticPublisher/remote-asset-worker-v1",...B?{proxy:{server:B}}:{}}),n=[],s=async i=>{n.push(i);let c=n.filter(d=>d.outcome==="failed"||d.outcome==="deferred").length;await r.updated(n.length-c,c);};try{for(let i=0;i<e.urls.length;i+=1){let c=e.urls[i],d=t.getRemainingTimeInMillis?.();if(d!==void 0&&d<3e4){await s({requestedUrl:c,finalUrl:null,outcome:"deferred",httpStatus:null,contentType:null,cacheControl:null,lastModified:null,object:null,discoveredAssets:[],error:"Worker stopped accepting assets because less than 30 seconds remained."});continue}let u=null;try{u=await yr(o,c,e.options.timeoutMs);let l=u.status(),p=u.headers(),m=u.url()||c;if(l<200||l>=300){await s({requestedUrl:c,finalUrl:m,outcome:"http-error",httpStatus:l,contentType:p["content-type"]??null,cacheControl:p["cache-control"]??null,lastModified:p["last-modified"]??null,object:null,discoveredAssets:[],error:`Asset returned HTTP ${l}.`});continue}let f=await u.body(),R=Q(p["content-type"],m,"application/octet-stream"),x=await oe(v(z(S,e.jobId,e.taskId),"assets",`${String(i).padStart(4,"0")}-${L(c).slice(0,24)}.bin`),f,R);await s({requestedUrl:c,finalUrl:m,outcome:"fetched",httpStatus:l,contentType:R,cacheControl:p["cache-control"]??null,lastModified:p["last-modified"]??null,object:x,discoveredAssets:wr(m,R)?ue(m,new TextDecoder("utf8").decode(f),R):[]});}catch(l){await s({requestedUrl:c,finalUrl:u?.url()??null,outcome:"failed",httpStatus:u?.status()??null,contentType:u?.headers()["content-type"]??null,cacheControl:u?.headers()["cache-control"]??null,lastModified:u?.headers()["last-modified"]??null,object:null,discoveredAssets:[],error:l instanceof Error?l.message:String(l)});}finally{await u?.dispose().catch(()=>{});}}}finally{await o.dispose();}let a=n.filter(i=>i.outcome==="failed"||i.outcome==="deferred").length;return {response:{schemaVersion:P,operation:"asset",jobId:e.jobId,taskId:e.taskId,status:a>0?"partial":"succeeded",completedItems:n.length-a,failedItems:a,exporterVersion:$},detail:{assets:n}}}async function br(e,t,r){if(!Array.isArray(e.urls)||e.urls.length<1||e.urls.length>20)throw new Error("Render tasks require between 1 and 20 URLs.");let o=new URL(e.sourceOrigin).origin,n=[];for(let a=0;a<e.urls.length;a+=1){let i=e.urls[a];if(!i)continue;let c=t.getRemainingTimeInMillis?.();if(c!==void 0&&c<6e4){n.push({requestedUrl:i,finalUrl:null,outcome:"deferred",httpStatus:null,contentType:null,html:null,discoveredPages:[],discoveredAssets:[],networkUrls:[],cookies:[],error:"Worker stopped accepting URLs because less than 60 seconds remained."}),await r.updated(n.filter(l=>l.outcome!=="failed"&&l.outcome!=="deferred").length,n.filter(l=>l.outcome==="failed"||l.outcome==="deferred").length);continue}let d=new URL(i);if(d.origin!==o)throw new Error(`Primary render URL is outside sourceOrigin: ${i}`);n.push(await hr(e,t,d.toString(),a));let u=n.filter(l=>l.outcome==="failed"||l.outcome==="deferred").length;await r.updated(n.length-u,u);}let s=n.filter(a=>a.outcome==="failed"||a.outcome==="deferred").length;return {response:{schemaVersion:P,operation:"render",jobId:e.jobId,taskId:e.taskId,status:s>0?"partial":"succeeded",completedItems:n.length-s,failedItems:s,exporterVersion:$},detail:{pages:n}}}async function Er(e,t){if(!Array.isArray(e.items)||e.items.length<1||e.items.length>500)throw new Error("Rewrite tasks require between 1 and 500 objects.");let o={...await ne(e.configKey),outputDir:"/workspace"},n=await ne(e.assetMapKey),s=e.previousAssetMapKey?await ne(e.previousAssetMapKey):{},a=[];for(let i of e.items){let c=W(i.inputKey,S),d=W(i.outputKey,S),u=await rt(c),l=u.body,p=`/workspace/${i.relativePath.replace(/^\/+/,"")}`,m=Ae(l,o,n,p,s),f=Q(i.contentType||u.contentType,i.relativePath,"text/plain; charset=utf-8"),R=await oe(d,m,f);a.push({inputKey:c,outputKey:d,changed:m!==l,output:R}),await t.updated(a.length,0);}return {response:{schemaVersion:P,operation:"rewrite",jobId:e.jobId,taskId:e.taskId,status:"succeeded",completedItems:a.length,failedItems:0,exporterVersion:$},detail:{objects:a}}}function Sr(e,t){return `${e}/${t.split("/").map(r=>encodeURIComponent(r)).join("/")}`}async function kr(e,t){if(!Array.isArray(e.items)||e.items.length>1e3)throw new Error("Deploy copy tasks accept at most 1000 objects.");let r=sr.find(u=>u.id===e.targetId);if(!r)throw new Error(`Unknown deployment target: ${e.targetId}`);let o=Ze.get(r.region);o||(o=new S3Client({region:r.region}),Ze.set(r.region,o));let n=[];for(let u of e.items){let l=W(u.sourceKey,S),p=v(r.prefix,u.targetRelativeKey);try{let m=await o.send(new HeadObjectCommand({Bucket:r.bucketName,Key:p})).catch(h=>{if((h&&typeof h=="object"&&"$metadata"in h?Number(h.$metadata?.httpStatusCode):0)===404||h?.name==="NotFound")return null;throw h}),f=String(m?.CacheControl??"").replace(/\s+/g,"")===u.cacheControl.replace(/\s+/g,""),R=ge(m?.ContentType)===ge(u.contentType),x=m?.Metadata?.["wpsuite-sha256"]===u.sha256,q=!!u.normalizedSha256&&m?.Metadata?.["wpsuite-normalized-sha256"]===u.normalizedSha256;if(f&&R&&(x||q)){n.push({sourceKey:l,targetKey:p,status:"skipped"}),await t.updated(n.filter(h=>h.status!=="failed").length,n.filter(h=>h.status==="failed").length);continue}let F=await o.send(new CopyObjectCommand({Bucket:r.bucketName,Key:p,CopySource:Sr(M,l),MetadataDirective:"REPLACE",ContentType:u.contentType,CacheControl:u.cacheControl,Metadata:{"wpsuite-sha256":u.sha256,...u.normalizedSha256?{"wpsuite-normalized-sha256":u.normalizedSha256}:{}}}));n.push({sourceKey:l,targetKey:p,status:"copied",...F.CopyObjectResult?.ETag?{etag:F.CopyObjectResult.ETag}:{}}),await t.updated(n.filter(h=>h.status!=="failed").length,n.filter(h=>h.status==="failed").length);}catch(m){n.push({sourceKey:l,targetKey:p,status:"failed",error:m instanceof Error?m.message:String(m)}),await t.updated(n.filter(f=>f.status!=="failed").length,n.filter(f=>f.status==="failed").length);}}let a=(e.deleteRelativeKeys??[]).map(u=>v(r.prefix,u)),i=[],c=[];if(a.length>0){let u=await o.send(new DeleteObjectsCommand({Bucket:r.bucketName,Delete:{Objects:a.map(l=>({Key:l})),Quiet:false}}));i.push(...(u.Deleted??[]).flatMap(l=>l.Key?[l.Key]:[])),c.push(...(u.Errors??[]).map(l=>({key:l.Key??"",error:l.Message??l.Code??"S3 deletion failed"}))),await t.updated(n.filter(l=>l.status!=="failed").length+i.length,n.filter(l=>l.status==="failed").length+c.length);}let d=n.filter(u=>u.status==="failed").length+c.length;return {response:{schemaVersion:P,operation:"deploy-copy",jobId:e.jobId,taskId:e.taskId,status:d>0?"partial":"succeeded",completedItems:n.filter(u=>u.status!=="failed").length+i.length,failedItems:d,exporterVersion:$},detail:{objects:n,deletedKeys:i,deleteErrors:c,targetId:r.id}}}async function Ye(e,t,r){if(e.operation==="health")return {response:{schemaVersion:P,operation:"health",jobId:e.jobId,taskId:e.taskId,status:"succeeded",completedItems:1,failedItems:0,exporterVersion:$},detail:{allowedOperation:te,workspaceBucket:M,workspacePrefix:S,proxyConfigured:!!B}};if(te&&te!==e.operation)throw new Error(`Function is configured for ${te}, not ${e.operation}.`);if(!r)throw new Error("Remote worker progress reporter is required.");return e.operation==="render"?await br(e,t,r):e.operation==="asset"?await Rr(e,t,r):e.operation==="rewrite"?await Er(e,r):await kr(e,r)}async function Sn(e,t={}){let r=Pe(e),o=setInterval(()=>{},1e3),n={requestId:t.awsRequestId,jobId:r.jobId,taskId:r.taskId,operation:r.operation,remainingTimeMs:t.getRemainingTimeInMillis?.()};ee(n),await g("invocation.started",n,{exporterVersion:$});try{if(r.operation==="health"){let c=(await Ye(r,t)).response;return await g("invocation.completed",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()},{status:c.status}),c}ye();let s=v(z(S,r.jobId,r.taskId),"result.json"),a=await mr(s),i=new Y(r,t.awsRequestId);if(a)return await i.completed(a),await g("invocation.completed-from-existing-result",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()},{status:a.status}),a;await i.started();try{let c=await Ye(r,t,i),d={...c.response,resultKey:s};return await pr(s,{schemaVersion:P,response:d,detail:c.detail,completedAt:new Date().toISOString(),requestId:t.awsRequestId??null}),await i.completed(d),await g("invocation.completed",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()},{status:d.status,completedItems:d.completedItems,failedItems:d.failedItems}),d}catch(c){throw await i.failed(),c}}catch(s){throw await g("invocation.failed",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()},{errorName:s instanceof Error?s.name:"UnknownError",error:s instanceof Error?s.message:String(s)},"error"),s}finally{await g("invocation.cleanup-started",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()}),r.operation==="render"&&await tt({...n,remainingTimeMs:t.getRemainingTimeInMillis?.()}),await g("invocation.cleanup-finished",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()}),clearInterval(o),Ge();}}export{Sn as handler};
7
+ `,1)[0]}:{}},i.outcome==="failed"?"warn":"info"),!c||s===2)return i;await g("render.page-retry-with-fresh-browser",a,{nextAttempt:s+1},"warn");}if(n)return n;throw new Error(`Remote render did not produce a result for ${r}.`)}function wr(e,t){let r=t.toLowerCase();if(r.startsWith("text/")||r.includes("javascript")||r.includes("json")||r.includes("xml")||r.includes("svg"))return true;try{return /\.(?:css|js|mjs|json|xml|xsl|svg|txt|map|html?)$/i.test(new URL(e).pathname)}catch{return false}}async function yr(e,t,r){let o=t;for(let n=0;n<=5;n+=1){await le(o,"asset request");let s=await e.get(o,{timeout:r,failOnStatusCode:false,maxRedirects:0}),a=s.status();if(a<300||a>=400)return s;let i=s.headers().location;if(!i)return s;if(n===5)throw await s.dispose(),new Error("Asset request exceeded five redirects.");o=new URL(i,o).toString(),await s.dispose();}throw new Error("Asset redirect handling failed.")}async function Rr(e,t,r){if(!Array.isArray(e.urls)||e.urls.length<1||e.urls.length>20)throw new Error("Asset tasks require between 1 and 20 URLs.");let o=await request.newContext({ignoreHTTPSErrors:e.options.ignoreHttpsErrors,userAgent:"WPSuiteStaticPublisher/remote-asset-worker-v1",...B?{proxy:{server:B}}:{}}),n=[],s=async i=>{n.push(i);let c=n.filter(d=>d.outcome==="failed"||d.outcome==="deferred").length;await r.updated(n.length-c,c);};try{for(let i=0;i<e.urls.length;i+=1){let c=e.urls[i],d=t.getRemainingTimeInMillis?.();if(d!==void 0&&d<3e4){await s({requestedUrl:c,finalUrl:null,outcome:"deferred",httpStatus:null,contentType:null,cacheControl:null,lastModified:null,object:null,discoveredAssets:[],error:"Worker stopped accepting assets because less than 30 seconds remained."});continue}let u=null;try{u=await yr(o,c,e.options.timeoutMs);let l=u.status(),p=u.headers(),m=u.url()||c;if(l<200||l>=300){await s({requestedUrl:c,finalUrl:m,outcome:"http-error",httpStatus:l,contentType:p["content-type"]??null,cacheControl:p["cache-control"]??null,lastModified:p["last-modified"]??null,object:null,discoveredAssets:[],error:`Asset returned HTTP ${l}.`});continue}let f=await u.body(),R=Q(p["content-type"],m,"application/octet-stream"),x=await oe(v(z(S,e.jobId,e.taskId),"assets",`${String(i).padStart(4,"0")}-${L(c).slice(0,24)}.bin`),f,R);await s({requestedUrl:c,finalUrl:m,outcome:"fetched",httpStatus:l,contentType:R,cacheControl:p["cache-control"]??null,lastModified:p["last-modified"]??null,object:x,discoveredAssets:wr(m,R)?ue(m,new TextDecoder("utf8").decode(f),R):[]});}catch(l){await s({requestedUrl:c,finalUrl:u?.url()??null,outcome:"failed",httpStatus:u?.status()??null,contentType:u?.headers()["content-type"]??null,cacheControl:u?.headers()["cache-control"]??null,lastModified:u?.headers()["last-modified"]??null,object:null,discoveredAssets:[],error:l instanceof Error?l.message:String(l)});}finally{await u?.dispose().catch(()=>{});}}}finally{await o.dispose();}let a=n.filter(i=>i.outcome==="failed"||i.outcome==="deferred").length;return {response:{schemaVersion:P,operation:"asset",jobId:e.jobId,taskId:e.taskId,status:a>0?"partial":"succeeded",completedItems:n.length-a,failedItems:a,exporterVersion:$},detail:{assets:n}}}async function br(e,t,r){if(!Array.isArray(e.urls)||e.urls.length<1||e.urls.length>20)throw new Error("Render tasks require between 1 and 20 URLs.");let o=new URL(e.sourceOrigin).origin,n=[];for(let a=0;a<e.urls.length;a+=1){let i=e.urls[a];if(!i)continue;let c=t.getRemainingTimeInMillis?.();if(c!==void 0&&c<6e4){n.push({requestedUrl:i,finalUrl:null,outcome:"deferred",httpStatus:null,contentType:null,html:null,discoveredPages:[],discoveredAssets:[],networkUrls:[],cookies:[],error:"Worker stopped accepting URLs because less than 60 seconds remained."}),await r.updated(n.filter(l=>l.outcome!=="failed"&&l.outcome!=="deferred").length,n.filter(l=>l.outcome==="failed"||l.outcome==="deferred").length);continue}let d=new URL(i);if(d.origin!==o)throw new Error(`Primary render URL is outside sourceOrigin: ${i}`);n.push(await hr(e,t,d.toString(),a));let u=n.filter(l=>l.outcome==="failed"||l.outcome==="deferred").length;await r.updated(n.length-u,u);}let s=n.filter(a=>a.outcome==="failed"||a.outcome==="deferred").length;return {response:{schemaVersion:P,operation:"render",jobId:e.jobId,taskId:e.taskId,status:s>0?"partial":"succeeded",completedItems:n.length-s,failedItems:s,exporterVersion:$},detail:{pages:n}}}async function Er(e,t){if(!Array.isArray(e.items)||e.items.length<1||e.items.length>500)throw new Error("Rewrite tasks require between 1 and 500 objects.");let o={...await ne(e.configKey),outputDir:"/workspace"},n=await ne(e.assetMapKey),s=e.previousAssetMapKey?await ne(e.previousAssetMapKey):{},a=[];for(let i of e.items){let c=C(i.inputKey,S),d=C(i.outputKey,S),u=await rt(c),l=u.body,p=`/workspace/${i.relativePath.replace(/^\/+/,"")}`,m=Ae(l,o,n,p,s),f=Q(i.contentType||u.contentType,i.relativePath,"text/plain; charset=utf-8"),R=await oe(d,m,f);a.push({inputKey:c,outputKey:d,changed:m!==l,output:R}),await t.updated(a.length,0);}return {response:{schemaVersion:P,operation:"rewrite",jobId:e.jobId,taskId:e.taskId,status:"succeeded",completedItems:a.length,failedItems:0,exporterVersion:$},detail:{objects:a}}}function Sr(e,t){return `${e}/${t.split("/").map(r=>encodeURIComponent(r)).join("/")}`}async function kr(e,t){if(!Array.isArray(e.items)||e.items.length>1e3)throw new Error("Deploy copy tasks accept at most 1000 objects.");let r=sr.find(u=>u.id===e.targetId);if(!r)throw new Error(`Unknown deployment target: ${e.targetId}`);let o=Ze.get(r.region);o||(o=new S3Client({region:r.region}),Ze.set(r.region,o));let n=[];for(let u of e.items){let l=C(u.sourceKey,S),p=v(r.prefix,u.targetRelativeKey);try{let m=await o.send(new HeadObjectCommand({Bucket:r.bucketName,Key:p})).catch(h=>{if((h&&typeof h=="object"&&"$metadata"in h?Number(h.$metadata?.httpStatusCode):0)===404||h?.name==="NotFound")return null;throw h}),f=String(m?.CacheControl??"").replace(/\s+/g,"")===u.cacheControl.replace(/\s+/g,""),R=ge(m?.ContentType)===ge(u.contentType),x=m?.Metadata?.["wpsuite-sha256"]===u.sha256,q=!!u.normalizedSha256&&m?.Metadata?.["wpsuite-normalized-sha256"]===u.normalizedSha256;if(f&&R&&(x||q)){n.push({sourceKey:l,targetKey:p,status:"skipped"}),await t.updated(n.filter(h=>h.status!=="failed").length,n.filter(h=>h.status==="failed").length);continue}let F=await o.send(new CopyObjectCommand({Bucket:r.bucketName,Key:p,CopySource:Sr(M,l),MetadataDirective:"REPLACE",ContentType:u.contentType,CacheControl:u.cacheControl,Metadata:{"wpsuite-sha256":u.sha256,...u.normalizedSha256?{"wpsuite-normalized-sha256":u.normalizedSha256}:{}}}));n.push({sourceKey:l,targetKey:p,status:"copied",...F.CopyObjectResult?.ETag?{etag:F.CopyObjectResult.ETag}:{}}),await t.updated(n.filter(h=>h.status!=="failed").length,n.filter(h=>h.status==="failed").length);}catch(m){n.push({sourceKey:l,targetKey:p,status:"failed",error:m instanceof Error?m.message:String(m)}),await t.updated(n.filter(f=>f.status!=="failed").length,n.filter(f=>f.status==="failed").length);}}let a=(e.deleteRelativeKeys??[]).map(u=>v(r.prefix,u)),i=[],c=[];if(a.length>0){let u=await o.send(new DeleteObjectsCommand({Bucket:r.bucketName,Delete:{Objects:a.map(l=>({Key:l})),Quiet:false}}));i.push(...(u.Deleted??[]).flatMap(l=>l.Key?[l.Key]:[])),c.push(...(u.Errors??[]).map(l=>({key:l.Key??"",error:l.Message??l.Code??"S3 deletion failed"}))),await t.updated(n.filter(l=>l.status!=="failed").length+i.length,n.filter(l=>l.status==="failed").length+c.length);}let d=n.filter(u=>u.status==="failed").length+c.length;return {response:{schemaVersion:P,operation:"deploy-copy",jobId:e.jobId,taskId:e.taskId,status:d>0?"partial":"succeeded",completedItems:n.filter(u=>u.status!=="failed").length+i.length,failedItems:d,exporterVersion:$},detail:{objects:n,deletedKeys:i,deleteErrors:c,targetId:r.id}}}async function Ye(e,t,r){if(e.operation==="health")return {response:{schemaVersion:P,operation:"health",jobId:e.jobId,taskId:e.taskId,status:"succeeded",completedItems:1,failedItems:0,exporterVersion:$},detail:{allowedOperation:te,workspaceBucket:M,workspacePrefix:S,proxyConfigured:!!B}};if(te&&te!==e.operation)throw new Error(`Function is configured for ${te}, not ${e.operation}.`);if(!r)throw new Error("Remote worker progress reporter is required.");return e.operation==="render"?await br(e,t,r):e.operation==="asset"?await Rr(e,t,r):e.operation==="rewrite"?await Er(e,r):await kr(e,r)}async function Sn(e,t={}){let r=Pe(e),o=setInterval(()=>{},1e3),n={requestId:t.awsRequestId,jobId:r.jobId,taskId:r.taskId,operation:r.operation,remainingTimeMs:t.getRemainingTimeInMillis?.()};ee(n),await g("invocation.started",n,{exporterVersion:$});try{if(r.operation==="health"){let c=(await Ye(r,t)).response;return await g("invocation.completed",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()},{status:c.status}),c}ye();let s=v(z(S,r.jobId,r.taskId),"result.json"),a=await mr(s),i=new Y(r,t.awsRequestId);if(a)return await i.completed(a),await g("invocation.completed-from-existing-result",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()},{status:a.status}),a;await i.started();try{let c=await Ye(r,t,i),d={...c.response,resultKey:s};return await pr(s,{schemaVersion:P,response:d,detail:c.detail,completedAt:new Date().toISOString(),requestId:t.awsRequestId??null}),await i.completed(d),await g("invocation.completed",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()},{status:d.status,completedItems:d.completedItems,failedItems:d.failedItems}),d}catch(c){throw await i.failed(),c}}catch(s){throw await g("invocation.failed",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()},{errorName:s instanceof Error?s.name:"UnknownError",error:s instanceof Error?s.message:String(s)},"error"),s}finally{await g("invocation.cleanup-started",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()}),r.operation==="render"&&await tt({...n,remainingTimeMs:t.getRemainingTimeInMillis?.()}),await g("invocation.cleanup-finished",{...n,remainingTimeMs:t.getRemainingTimeInMillis?.()}),clearInterval(o),Ge();}}export{Sn as handler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/publisher-exporter",
3
- "version": "1.1.79",
3
+ "version": "1.1.80",
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.",