@smart-cloud/publisher-exporter 1.1.73 → 1.1.74
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 +9 -0
- package/dist/content-sync.js +15 -15
- package/dist/crawl.js +12 -12
- package/dist/deploy.js +4 -4
- package/dist/invalidate.js +1 -1
- package/dist/queue-runner.js +1 -1
- package/package.json +1 -1
- package/publisher.config.example.json +3 -0
package/dist/queue-runner.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {pathToFileURL}from'url';import P from'fs/promises';import {existsSync,createReadStream,createWriteStream}from'fs';import h from'path';import {spawn}from'child_process';import {randomUUID,createHash}from'crypto';import Ge from'http';import Se from'https';import {pipeline}from'stream/promises';import {createGzip}from'zlib';function he(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Y(e){return Array.isArray(e)?e.map(Y):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Y(n)])):e}function _e(e){return JSON.stringify(Y(e))}function J(e){return createHash("sha256").update(_e(e)).digest("hex")}function fe(e){return J({schemaVersion:1,wordpressFingerprint:e.wordpressFingerprint,targetFingerprint:e.targetFingerprint,sourceOrigin:e.sourceOrigin,sitemapPaths:[...e.sitemapPaths].sort(),blockedPathPrefixes:[...e.blockedPathPrefixes].sort(),assetPathPrefixes:[...e.assetPathPrefixes].sort(),noJavaScriptRenderPathPrefixes:[...e.noJavaScriptRenderPathPrefixes].sort(),urlRewriteMode:e.urlRewriteMode})}function He(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 Q(e){let t=he((e.postTypes??[]).map(i=>String(i).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let n=he((e.listingPaths??[]).map(i=>{let r=String(i).trim();if(!r)return "";let a=new URL(r,"https://content-sync.invalid/");if(a.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(r))throw new Error("Content-sync listing routes must be same-site paths.");let o=`/${a.pathname.replace(/^\/+|\/+$/g,"")}`;return o==="/"?"/":`${o}/`}));return {postTypes:t,listingPaths:n,includeSubsites:e.includeSubsites===true,includePostTypeArchives:e.includePostTypeArchives!==false,includeTaxonomyArchives:e.includeTaxonomyArchives!==false,includeAuthorArchives:e.includeAuthorArchives===true,includeDateArchives:e.includeDateArchives===true,includePostsPage:e.includePostsPage!==false,includeSitemapChain:e.includeSitemapChain!==false}}function Z(e,t,n){return J({schemaVersion:1,sourceOrigin:He(e),ruleId:t.trim(),scope:Q(n)})}function X(e){return J({schemaVersion:1,...e})}function be(e){return e.replace(/((?:x-static-publisher-token|authorization|proxy-authorization|x-api-key|aws-access-key-id|aws-secret-access-key|aws-session-token)\s*:\s*)[^\r\n]+/gi,"$1[REDACTED]").replace(/\b(Basic|Bearer)\s+[^\s]+/gi,"$1 [REDACTED]").replace(/([?&](?:token|access_token|refresh_token|api_key|key|nonce)=)[^&\s]+/gi,"$1[REDACTED]").replace(/((?:"|')?(?:runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken)(?:"|')?\s*[:=]\s*(?:"|'))[^"']+/gi,"$1[REDACTED]")}var ye=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";ye?h.join(ye,"current-progress.json"):"";Promise.resolve();var Ye="wp-json/smartcloud-static-publisher/v1/content-sync/",Ze=25*1024*1024,T=class extends Error{status;code;constructor(t,n,i){super(i),this.name="ContentSyncApiError",this.status=t,this.code=n;}},L=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,n="content-sync"){let i=this.options.sourceOrigin.replace(/\/+$/,"")+"/",r=n==="content-sync"?Ye:`wp-json/smartcloud-static-publisher/v1/${n}/`;return new URL(`${r}${t}`,i)}async post(t,n,i="content-sync"){let r=this.endpoint(t,i),a=Buffer.from(JSON.stringify(n),"utf8"),o=r.protocol==="https:"?Se:Ge,s=r.protocol==="https:"?new Se.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((c,u)=>{let g=o.request(r,{method:"POST",agent:s,headers:{"content-type":"application/json","content-length":String(a.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},d=>{let m=[],f=0;d.on("data",b=>{if(f+=b.byteLength,f>Ze){d.destroy(new Error("Content-sync API response exceeded the size limit."));return}m.push(b);}),d.on("error",u),d.on("end",()=>{let b=Buffer.concat(m).toString("utf8"),l;try{l=b?JSON.parse(b):{};}catch{u(new T(d.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let p=d.statusCode??500;if(p<200||p>=300){u(new T(p,String(l.code??"request-failed"),String(l.message??`Content-sync API request failed (${p}).`)));return}c(l);});});g.on("timeout",()=>g.destroy(new Error(`Content-sync API request timed out: ${t}`))),g.on("error",u),g.end(a);})}async head(t){return this.post("head",t)}async unboundHead(t,n){return this.post("head",{postTypes:t,includeSubsites:n})}async events(t){let n=[],i=t.afterSequence,r=new Set(t.postTypes);for(;i<t.throughSequence;){let a=await this.post("events",{...t,afterSequence:i,limit:250});if(a.fromSequence!==i||a.throughSequence!==t.throughSequence||a.nextSequence<i||a.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(a.items))throw new Error("Content-sync API returned a malformed event page.");let o=i;for(let s of a.items){if(!Number.isSafeInteger(s.sequence)||s.sequence<=o||s.sequence>t.throughSequence||!Number.isSafeInteger(s.postId)||s.postId<=0||!Number.isSafeInteger(s.blogId)||s.blogId<=0||!r.has(s.postType)||typeof s.operation!="string"||!s.operation)throw new Error("Content-sync API returned an invalid or out-of-scope journal event.");o=s.sequence;}if(a.items.length>0&&a.nextSequence!==o)throw new Error("Content-sync API event cursor does not match the final returned event.");if(n.push(...a.items),!a.hasMore)break;if(a.nextSequence===i)throw new Error("Content-sync API event pagination did not advance.");i=a.nextSequence;}if(t.throughSequence>t.afterSequence&&n.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return n}async resolveImpactFamilies(t,n){let i=await this.post("impact",{families:t,includeSubsites:n});return Array.isArray(i.families)?i.families:[]}async releaseFingerprint(t=false){let n=await this.post("fingerprint",{includeSubsites:t}),i=String(n.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(i))throw new Error("WordPress returned an invalid release fingerprint.");return i}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 Xe(e){return typeof e.subscriptionType=="string"&&e.subscriptionType.trim()!==""}function et(e,t){return {...e,...t??{}}}function tt(e,t){return {...e,...t??{},invalidationPaths:[...(t?.invalidationPaths??e.invalidationPaths)||[]]}}function ee(e,t){let n=String(t??e.deploymentTargetOverride??"").trim();if(!Xe(e)){if(n)throw new Error(`Deployment target "${n}" requires an active WPSuite subscription and remote publisher config.`);return {name:null,profile:null,config:e}}let i=String(n||e.defaultDeploymentProfile||"").trim();if(!i)return {name:null,profile:null,config:e};let r=e.deploymentProfiles?.[i];if(!r)throw new Error(`Unknown deployment profile "${i}". Check the linked WPSuite publisher configuration.`);return {name:i,profile:r,config:{...e,targetOrigin:r.targetOrigin??e.targetOrigin,s3:et(e.s3,r.s3),cloudFront:tt(e.cloudFront,r.cloudFront)}}}var te=["/sitemap_index.xml","/wp-sitemap.xml","/sitemap.xml"];function we(e){let t=new Set;for(let n of [...e,...te]){let i=String(n||"").trim();i&&t.add(i);}return [...t]}function Pe(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function ot(e){let t=String(e??"").trim();if(!t)return "";let n=t;if(/^https?:\/\//i.test(n))try{n=new URL(n).pathname;}catch{return ""}if(n=n.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!n)return "";let i=n.endsWith("/"),r=n.replace(/^\/+/,"").split("/").map(o=>o.replace(/[^A-Za-z0-9._-]/g,"")).filter(o=>o.length>0&&o!=="."&&o!=="..");if(r.length===0)return "";let a=`/${r.join("/")}`;return i&&h.extname(a)===""&&(a+="/"),a==="/"?"":a}function ne(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function st(e){if(!e||typeof e!="object")return {};let t={};for(let[n,i]of Object.entries(e)){let r=n.trim();if(!r||!i||typeof i!="object")continue;let a=i,o={};if(typeof a.targetOrigin=="string"){let c=Pe(a.targetOrigin);c&&(o.targetOrigin=c);}let s=ne(a.extraReplacements);if(Object.keys(s).length>0&&(o.extraReplacements=s),a.s3&&typeof a.s3=="object"){let c={},u=a.s3;typeof u.bucket=="string"&&(c.bucket=u.bucket.trim()),typeof u.prefix=="string"&&(c.prefix=u.prefix.trim()),typeof u.region=="string"&&(c.region=u.region.trim()),typeof u.htmlCacheControl=="string"&&(c.htmlCacheControl=u.htmlCacheControl.trim()),typeof u.assetCacheControl=="string"&&(c.assetCacheControl=u.assetCacheControl.trim()),Object.keys(c).length>0&&(o.s3=c);}if(a.cloudFront&&typeof a.cloudFront=="object"){let c={},u=a.cloudFront;typeof u.distributionId=="string"&&(c.distributionId=u.distributionId.trim()),Array.isArray(u.invalidationPaths)&&(c.invalidationPaths=u.invalidationPaths.map(g=>String(g??"").trim()).filter(g=>g.length>0)),Object.keys(c).length>0&&(o.cloudFront=c);}t[r]=o;}return t}function ie(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function at(e,t){if(!e||typeof e!="object")return null;let n=e,i=n.command;if(i!=="publish"&&i!=="crawl"&&i!=="deploy"&&i!=="invalidate"&&i!=="retry-timeouts"&&i!=="url"&&i!=="content-sync")return null;let r=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let a=String(n.id??`${i}-${t+1}`).trim();if(!a)return null;let o=String(n.deploymentProfile??"").trim(),s=String(n.url??"").trim(),c=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(g=>String(g??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],u=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(g=>String(g??"").trim()).filter(Boolean))]:[];return i==="content-sync"&&c.length===0?null:{id:a,enabled:n.enabled!==false,command:i,intervalMinutes:r,...i==="publish"||i==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(i==="publish"||i==="deploy"||i==="invalidate"||i==="content-sync")&&o?{deploymentProfile:o}:{},...s?{url:s}:{},...c.length>0?{postTypes:c}:{},...u.length>0?{listingPaths:u}:{},...typeof n.includeSubsites=="boolean"?{includeSubsites:n.includeSubsites}:{},...typeof n.includePostTypeArchives=="boolean"?{includePostTypeArchives:n.includePostTypeArchives}:{},...typeof n.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:n.includeTaxonomyArchives}:{},...typeof n.includeAuthorArchives=="boolean"?{includeAuthorArchives:n.includeAuthorArchives}:{},...typeof n.includeDateArchives=="boolean"?{includeDateArchives:n.includeDateArchives}:{},...typeof n.includePostsPage=="boolean"?{includePostsPage:n.includePostsPage}:{},...typeof n.includeSitemapChain=="boolean"?{includeSitemapChain:n.includeSitemapChain}:{}}}function Ce(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((i,r)=>at(i,r)).filter(i=>!!i):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function ct(e){let t=e&&typeof e=="object"?e:{},n=t.render&&typeof t.render=="object"?t.render:{},i=Number(n.concurrency??0),r=Number(n.batchSize??0),a=Number(n.maxAttempts??0),o=t.rewrite&&typeof t.rewrite=="object"?t.rewrite:{},s=t.deploy&&typeof t.deploy=="object"?t.deploy:{},c=(u,g)=>({enabled:typeof u.enabled=="boolean"?u.enabled:n.enabled===true,concurrency:Math.min(100,Math.max(1,Number(u.concurrency||g.concurrency))),batchSize:Math.min(500,Math.max(1,Number(u.batchSize||g.batchSize))),maxAttempts:Math.min(5,Math.max(1,Number(u.maxAttempts||2)))});return {render:{enabled:n.enabled===true,...Number.isInteger(i)&&i>0?{concurrency:i}:{},batchSize:Number.isInteger(r)&&r>0?Math.min(20,r):5,...Number.isInteger(a)&&a>0?{maxAttempts:Math.min(5,a)}:{}},rewrite:c(o,{concurrency:8,batchSize:25}),deploy:c(s,{concurrency:8,batchSize:50})}}function ut(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of ["accountId","siteId"]){let a=t[r];typeof a=="string"&&a.trim()!==""&&(n[r]=a.trim());}let i=Number(t.lastUpdate??0);return Number.isFinite(i)&&i>0&&(n.lastUpdate=Math.floor(i)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function oe(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),i=String(t.siteId??"").trim(),r=t.subscriber===true,a=ut(t.siteSettings),o={...a??{},...n?{accountId:a?.accountId??n}:{},...i?{siteId:a?.siteId??i}:{},...a?.subscriber===true||r?{subscriber:true}:{}},s={},c=String(t.apiBase??"").trim();c&&(s.apiBase=c);let u=String(t.runtimeToken??t.nonce??"").trim();u&&(s.runtimeToken=u);let g=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();g&&(s.virtualAssetBaseUrl=g),Object.keys(o).length>0&&(s.siteSettings=o);let d=ie(t.subscriptionType);return d&&(s.subscriptionType=d),s}function lt(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function Ae(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function dt(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[i,r]of new Headers(t.headers).entries())n.set(i,r);return n}async function Ie(e,t,n=5){let i=new URL(Ae(e)),r=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),a=i.protocol==="http:"?Ge:Se,o=dt(e,t);return await new Promise((s,c)=>{let u=a.request(i,{method:r,headers:Object.fromEntries(o.entries()),...i.protocol==="https:"?{rejectUnauthorized:false}:{}},g=>{let d=[];g.on("data",m=>{d.push(Buffer.isBuffer(m)?m:Buffer.from(m));}),g.on("error",c),g.on("end",()=>{let m=g.statusCode??0,f=g.headers.location;if(n>0&&f&&[301,302,303,307,308].includes(m)){s(Ie(new URL(f,i),{method:m===303?"GET":r},n-1));return}let b=new Headers;for(let[l,p]of Object.entries(g.headers))Array.isArray(p)?b.set(l,p.join(", ")):typeof p=="string"&&b.set(l,p);s(new Response(Buffer.concat(d),{status:m,statusText:g.statusMessage??"",headers:b}));});});u.on("error",c),u.end();})}function gt(e){let t=oe(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},i=String(n.accountId??"").trim(),r=String(n.siteId??"").trim(),a=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...a?{virtualAssetBaseUrl:a}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!i||!r||!a)return false;lt(e.sourceOrigin);let o=globalThis,c={...o.WpSuite??{},siteSettings:n,uploadUrl:a};return t.apiBase&&(c.apiBase=t.apiBase),o.WpSuite=c,true}async function pt(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!gt(e)){let r=e.wpsuite?.siteSettings,a=[String(r?.accountId??"").trim()?"":"accountId",String(r?.siteId??"").trim()?"":"siteId",t?"":"virtualAssetBaseUrl"].filter(Boolean);return {remote:null,diagnostic:{status:"invalid-runtime",virtualAssetBaseUrl:t,subscriptionType:null,error:`Missing WP Suite runtime field(s): ${a.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,i=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(c,u)=>{let g=Ae(c);if(g.startsWith(t)){let d=(()=>{try{return new URL(g).pathname}catch{return g}})();try{let m=e.ignoreHttpsErrors&&g.startsWith("https://")?await Ie(c,u):await n(c,u);return i.push({path:d,status:m.status,ok:m.ok,error:null}),m}catch(m){throw i.push({path:d,status:null,ok:!1,error:m instanceof Error?m.message:String(m)}),m}}return n(c,u)}));let{getConfig:r}=await import('@smart-cloud/wpsuite-core'),a=await r("publisher"),o=a&&typeof a=="object"?a:null,s=ie(o?.subscriptionType);return {remote:o,diagnostic:{status:o?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:s??null,error:o?null:"WP Suite publisher config loader returned no configuration.",requests:i}}}catch(r){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:r instanceof Error?r.message:String(r),requests:i}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function mt(e,t){let n=st(t?.deploymentProfiles),i=String(t?.defaultDeploymentProfile??"").trim(),r=n[i]?i:"",a=ie(t?.subscriptionType),o=oe(e.wpsuite);return {...e,scheduler:Ce(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:r,...a?{subscriptionType:a}:{},wpsuite:{...o,...o.siteSettings||a?{siteSettings:{...o.siteSettings??{},...o.siteSettings?.subscriber===true||a==="PROFESSIONAL"||a==="AGENCY"?{subscriber:true}:{}}}:{},...a?{subscriptionType:a}:{}}}}function re(e,t){let i=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!i)return t;let r=i.split("/").map(a=>a.trim()).filter(a=>a.length>0&&a!=="."&&a!=="..");return r.length>0?r.join("/"):t}function ht(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?h.resolve(e):""}function ve(e,t,n){let i=String(t||"").trim();return i&&h.isAbsolute(i)?h.resolve(i):h.resolve(e,re(i,n))}async function z(e,t={}){let n=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",i=await P.readFile(n,"utf8"),r=JSON.parse(i);r.sourceOrigin=r.sourceOrigin.replace(/\/$/,""),r.targetOrigin=Pe(r.targetOrigin),r.ignoreHttpsErrors??=false,r.outputDir=String(r.outputDir||"export").trim()||"export",r.urlRewriteMode||=r.targetOrigin==="."?"relative":"absolute",r.noJavaScriptRenderPathPrefixes||=[],r.seedPaths||=[],r.generated404RequestPath=ot(r.generated404RequestPath),r.sitemapPaths||=[...te],r.allowedAssetHosts||=[],r.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],r.blockedPathPrefixes||=[],r.blockedSearchFragments||=[];let a=Number(r.processingConcurrency)>0?Math.min(100,Math.max(1,Number(r.processingConcurrency))):null;r.concurrency=a??r.concurrency??1,r.maxPages||=0,r.extraReplacements=ne(r.extraReplacements),r.postCrawlCopyMap=ne(r.postCrawlCopyMap),r.logDir=String(r.logDir||"logs").trim()||"logs",r.verbose??=false,r.logLevel||=r.verbose?"debug":"info",r.s3SyncMode||="sdk-upload-delete",r.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},r.readiness.timeoutMs??=1500,r.readiness.fallbackWaitMs??=1500,r.viewport||={width:1440,height:1200},r.navigationTimeoutMs||=3e4,r.assetDownloadConcurrency=a??(Number(r.assetDownloadConcurrency)>0?Number(r.assetDownloadConcurrency):r.concurrency),r.rewriteConcurrency=a??(Number(r.rewriteConcurrency)>0?Number(r.rewriteConcurrency):r.assetDownloadConcurrency),r.wpsuite=oe(r.wpsuite),r.scheduler=Ce(void 0),r.remoteWorkers=ct(r.remoteWorkers),typeof r.lambdaDelegationEnabled=="boolean"&&(r.remoteWorkers.render??={},r.remoteWorkers.rewrite??={},r.remoteWorkers.deploy??={},r.remoteWorkers.render.enabled=r.lambdaDelegationEnabled,r.remoteWorkers.rewrite.enabled=r.lambdaDelegationEnabled,r.remoteWorkers.deploy.enabled=r.lambdaDelegationEnabled),a!==null&&(r.processingConcurrency=a,r.remoteWorkers.render??={},r.remoteWorkers.rewrite??={},r.remoteWorkers.deploy??={},r.remoteWorkers.render.concurrency=a,r.remoteWorkers.rewrite.concurrency=a,r.remoteWorkers.deploy.concurrency=a),r.deploymentProfiles={},r.defaultDeploymentProfile="",r.deploymentTargetOverride=String(r.deploymentTargetOverride??"").trim();let o=await pt(r);t.onRemotePublisherConfigDiagnostic?.(o.diagnostic);let s=mt(r,o.remote),c=ht(),u=c?h.resolve(c,".."):"";return u?(s.outputDir=ve(u,s.outputDir,"export"),s.logDir=ve(u,s.logDir,"logs")):(h.isAbsolute(s.outputDir)||(s.outputDir=re(s.outputDir,"export")),h.isAbsolute(s.logDir)||(s.logDir=re(s.logDir,"logs"))),s}function Re(e){let t=e.split(/\r?\n/).map(i=>i.trim()).filter(Boolean),n=[...t].reverse().find(i=>/^(?:Error|[A-Za-z][A-Za-z0-9]*Error):\s/.test(i));return n||(t.find(i=>!i.startsWith("at "))??"")}function se(e){let t=h.resolve(e);return {state:h.join(t,"content-sync-state.json"),current:h.join(t,"content-sync-current.json"),impact:h.join(t,"content-sync-impact-plan.json"),checkpoint:h.join(t,"content-sync-checkpoint.json"),baseline:h.join(t,"content-sync-baseline.json"),activeRules:h.join(t,"content-sync-active-rules.json"),releaseCutoff:h.join(t,"content-sync-release-cutoff.json"),candidateManifest:h.join(t,"content-sync-candidate-manifest.json"),trustedManifest:h.join(t,"crawl-manifest.json"),invalidation:h.join(t,"content-sync-invalidation.json"),deployPlan:h.join(t,"deploy-plan.json")}}async function M(e,t,n=[],i=[],r=false){await xe(e.activeRules,{contractVersion:1,evaluatedAt:new Date().toISOString(),discoveryReady:r,entries:t,targets:n,rules:i});}async function xe(e,t){await P.mkdir(h.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await P.writeFile(n,JSON.stringify(t,null,2),"utf8"),await P.rename(n,e);}async function ke(e){try{return JSON.parse(await P.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 ft(e){let t=await ke(e.current);if(t===null)return null;let n=t;if(n.schemaVersion!==1||typeof n.jobId!="string"||typeof n.phase!="string"||!Number.isSafeInteger(n.fromSequence)||!Number.isSafeInteger(n.toSequence))throw new Error("Invalid content-sync current-range state.");return n}async function qe(e){let t=await ke(e.state);if(t===null)return {schemaVersion:1,updatedAt:"",rules:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.rules||typeof n.rules!="object"||Array.isArray(n.rules))throw new Error("Invalid content-sync state store.");return n}async function De(e,t){await xe(e.state,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Te(e,t){let n=await ft(e);return !n||n.coalesceKey!==t?false:(await Promise.all([e.current,e.checkpoint,e.impact,e.candidateManifest,e.invalidation,e.deployPlan].map(async i=>{try{await P.unlink(i);}catch(r){if(r.code!=="ENOENT")throw r}})),true)}function Le(e){let t=String(e.command??"").trim();return (t==="publish"||t==="crawl")&&e.crawlMode==="incremental"||t==="content-sync"}var ae=new Map;async function Ee(e){let t=h.resolve(e),n=ae.get(t);if(n!==void 0)return n;try{let i=JSON.parse(await P.readFile(t,"utf8")),r=String(i.version??"").trim();return ae.set(t,r),r}catch{return ae.set(t,""),""}}var $=class extends Error{request;step;constructor(t,n){super(`Stop requested during ${n}.`),this.name="StopRequestedError",this.request=t,this.step=n;}},Pt="queue-mutation.lock",Ct=5e3,At=3e4;function It(e){let t=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",n=process.env.STATIC_PUBLISHER_EXPORTER_DIR||process.cwd(),i=process.env.PUBLISHER_CONFIG||"",r=1;for(let s=0;s<e.length;s++){let c=e[s];c==="--runtime-dir"?t=e[++s]||"":c.startsWith("--runtime-dir=")?t=c.slice(14):c==="--exporter-dir"?n=e[++s]||n:c.startsWith("--exporter-dir=")?n=c.slice(15):c==="--config"?i=e[++s]||"":c.startsWith("--config=")?i=c.slice(9):c==="--max-jobs"?r=Number.parseInt(e[++s]||"1",10):c.startsWith("--max-jobs=")&&(r=Number.parseInt(c.slice(11),10));}if(!t)throw new Error("Missing runtime dir. Use --runtime-dir or STATIC_PUBLISHER_RUNTIME_DIR.");let a=h.resolve(t),o=i?h.resolve(i):h.join(a,"config.json");return {runtimeDir:a,exporterDir:h.resolve(n),configPath:o,maxJobs:Number.isFinite(r)&&r>0?r:1}}async function w(e,t){try{let n=await P.readFile(e,"utf8");return JSON.parse(n)}catch(n){if((n&&typeof n=="object"&&"code"in n?String(n.code||""):"")!=="ENOENT"){let r=n instanceof Error?n.message:String(n);console.warn(`[queue-runner] failed to read JSON ${e}: ${r}`);}return t}}async function v(e,t){await P.mkdir(h.dirname(e),{recursive:true}),await P.writeFile(e,JSON.stringify(t,null,2),"utf8");}function Be(e){return h.join(e,Pt)}async function Rt(e){await new Promise(t=>setTimeout(t,e));}async function xt(e){let t=Be(e),n=Date.now()+Ct;for(;;)try{await P.mkdir(h.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()},null,2),{encoding:"utf8",flag:"wx"});return}catch(i){if((i&&typeof i=="object"&&"code"in i?String(i.code||""):"")!=="EEXIST")throw i;let a=await P.stat(t).catch(()=>null);if(a&&Date.now()-a.mtimeMs>At){await P.unlink(t).catch(()=>{});continue}if(Date.now()>=n)throw new Error("Timed out acquiring queue mutation lock.",{cause:i});await Rt(50);}}async function kt(e){await P.unlink(Be(e)).catch(()=>{});}async function F(e,t){await xt(e);try{return await t()}finally{await kt(e);}}function Me(e){return h.join(e,"queue-runner-heartbeat.json")}function ge(e){return h.join(e,"current-progress.json")}function ce(e){return h.join(e,"scheduler-state.json")}function qt(e,t){let i=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!i)return t;let r=i.split("/").map(a=>a.trim()).filter(a=>a.length>0&&a!=="."&&a!=="..");return r.length>0?r.join("/"):t}async function Ue(e){let t=await w(e.configPath||"",null),n=h.resolve(e.runtimeDir,".."),r=(typeof t?.logDir=="string"?t.logDir:"").trim();return r&&h.isAbsolute(r)?h.resolve(r):h.resolve(n,qt(r,"logs"))}function ue(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||t}function Dt(e){let t=e?new Date(e):new Date;return (Number.isNaN(t.getTime())?new Date:t).toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function Tt(e){return [Dt(e.endedAt||e.startedAt),ue(e.command||"job","job"),ue(e.id||"job","job"),ue(e.status||"finished","finished")].join("-")}function Et(e){return e.endsWith(".log.jsonl")||e.endsWith(".errors.jsonl")||e.endsWith(".rejected.jsonl")?true:["current-crawl-event.json","rejected.jsonl","ignored.jsonl","skipped-http.jsonl","errors.jsonl","timings.jsonl","rejected.json","ignored.json","skipped-http.json","errors.json","timings.json"].includes(e)}function Ft(e){return e==="errors.json"||e==="errors.jsonl"||e.endsWith(".errors.jsonl")?"errors":e==="ignored.json"||e==="ignored.jsonl"?"ignored":e==="rejected.json"||e==="rejected.jsonl"||e.endsWith(".rejected.jsonl")?"rejected":e==="skipped-http.json"||e==="skipped-http.jsonl"?"skipped-http":e==="timings.json"||e==="timings.jsonl"?"timings":e==="current-progress.json"?"current-progress":e==="current-crawl-event.json"?"current-crawl-event":e.endsWith(".log.jsonl")?e.replace(/\.log\.jsonl$/i,"-log"):e.replace(/\.[^.]+$/u,"")||"artifact"}function jt(e){return e.endsWith(".gz")?"application/gzip":e.endsWith(".jsonl")?"application/x-ndjson":e.endsWith(".json")?"application/json":"text/plain"}async function K(e,t,n){let i=`${n}.gz`,r=h.join(t,i);await pipeline(createReadStream(e),createGzip({level:9}),createWriteStream(r));let[a,o]=await Promise.all([P.stat(e),P.stat(r)]);return {role:Ft(n),originalFileName:n,storedFileName:i,compressed:true,compression:"gzip",contentType:jt(i),originalSize:a.size,storedSize:o.size}}async function _(e,t){let n=await Ue(t),i=new Date().toISOString(),r=Tt(e),a=h.join(n,"archive",r),o=[],s=[];await P.mkdir(a,{recursive:true});try{let d=await P.readdir(n,{withFileTypes:!0});for(let m of d){if(!m.isFile()||!Et(m.name))continue;let f=await K(h.join(n,m.name),a,m.name);s.push(f),o.push(f.storedFileName);}}catch(d){if((d&&typeof d=="object"&&"code"in d?String(d.code||""):"")!=="ENOENT")throw d}let c=ge(t.runtimeDir);if(existsSync(c)){let d=await K(c,a,"current-progress.json");s.push(d),o.push(d.storedFileName);}if(e.command==="content-sync")for(let d of ["content-sync-current.json","content-sync-impact-plan.json","content-sync-checkpoint.json","content-sync-state.json","content-sync-invalidation.json","deploy-plan.json"]){let m=h.join(t.runtimeDir,d);if(!existsSync(m))continue;let f=await K(m,a,d);s.push(f),o.push(f.storedFileName);}let u=h.join(t.runtimeDir,"privacy","cookie-observations.json");if(existsSync(u)){let d=await K(u,a,"cookie-observations.json");s.push(d),o.push(d.storedFileName);}let g=[...o,"job.json"];return await v(h.join(a,"job.json"),{manifestVersion:1,archivedAt:i,archiveKey:r,archiveDir:a,logDir:n,runtimeDir:t.runtimeDir,exporterDir:t.exporterDir,configPath:t.configPath||"",archivedFiles:g,artifacts:s,job:e}),{archiveKey:r,archiveDir:a,archiveCreatedAt:i,archivedFiles:g,artifacts:s}}function Ot(e){return h.join(e,"audit-events.jsonl")}function le(e){return h.join(e,"stop-request.json")}async function We(e){try{let t=await P.readFile(le(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}async function Fe(e,t){let n=await We(e);if(!n)return null;let i=String(n.targetJobId||"").trim();return i&&i!==t?null:n}async function W(e,t){if(!t){await P.unlink(le(e)).catch(()=>{});return}let n=await We(e);if(!n)return;let i=String(n.targetJobId||"").trim();(!i||i===t)&&await P.unlink(le(e)).catch(()=>{});}async function R(e,t){try{let n={occurredAt:t.occurredAt||new Date().toISOString(),status:t.status||"info",actorSource:t.actorSource||"queue-runner",...t};await P.mkdir(e,{recursive:!0}),await P.appendFile(Ot(e),`${JSON.stringify(n)}
|
|
1
|
+
import {pathToFileURL}from'url';import P from'fs/promises';import {existsSync,createReadStream,createWriteStream}from'fs';import h from'path';import {spawn}from'child_process';import {randomUUID,createHash}from'crypto';import Ge from'http';import Se from'https';import {pipeline}from'stream/promises';import {createGzip}from'zlib';function he(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Y(e){return Array.isArray(e)?e.map(Y):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Y(n)])):e}function _e(e){return JSON.stringify(Y(e))}function J(e){return createHash("sha256").update(_e(e)).digest("hex")}function fe(e){return J({schemaVersion:1,wordpressFingerprint:e.wordpressFingerprint,targetFingerprint:e.targetFingerprint,sourceOrigin:e.sourceOrigin,sitemapPaths:[...e.sitemapPaths].sort(),blockedPathPrefixes:[...e.blockedPathPrefixes].sort(),assetPathPrefixes:[...e.assetPathPrefixes].sort(),noJavaScriptRenderPathPrefixes:[...e.noJavaScriptRenderPathPrefixes].sort(),urlRewriteMode:e.urlRewriteMode})}function He(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 Q(e){let t=he((e.postTypes??[]).map(i=>String(i).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let n=he((e.listingPaths??[]).map(i=>{let r=String(i).trim();if(!r)return "";let a=new URL(r,"https://content-sync.invalid/");if(a.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(r))throw new Error("Content-sync listing routes must be same-site paths.");let o=`/${a.pathname.replace(/^\/+|\/+$/g,"")}`;return o==="/"?"/":`${o}/`}));return {postTypes:t,listingPaths:n,includeSubsites:e.includeSubsites===true,includePostTypeArchives:e.includePostTypeArchives!==false,includeTaxonomyArchives:e.includeTaxonomyArchives!==false,includeAuthorArchives:e.includeAuthorArchives===true,includeDateArchives:e.includeDateArchives===true,includePostsPage:e.includePostsPage!==false,includeSitemapChain:e.includeSitemapChain!==false}}function Z(e,t,n){return J({schemaVersion:1,sourceOrigin:He(e),ruleId:t.trim(),scope:Q(n)})}function X(e){return J({schemaVersion:1,...e})}function be(e){return e.replace(/((?:x-static-publisher-token|authorization|proxy-authorization|x-api-key|aws-access-key-id|aws-secret-access-key|aws-session-token)\s*:\s*)[^\r\n]+/gi,"$1[REDACTED]").replace(/\b(Basic|Bearer)\s+[^\s]+/gi,"$1 [REDACTED]").replace(/([?&](?:token|access_token|refresh_token|api_key|key|nonce)=)[^&\s]+/gi,"$1[REDACTED]").replace(/((?:"|')?(?:runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken)(?:"|')?\s*[:=]\s*(?:"|'))[^"']+/gi,"$1[REDACTED]")}var ye=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";ye?h.join(ye,"current-progress.json"):"";Promise.resolve();var Ye="wp-json/smartcloud-static-publisher/v1/content-sync/",Ze=25*1024*1024,T=class extends Error{status;code;constructor(t,n,i){super(i),this.name="ContentSyncApiError",this.status=t,this.code=n;}},L=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,n="content-sync"){let i=this.options.sourceOrigin.replace(/\/+$/,"")+"/",r=n==="content-sync"?Ye:`wp-json/smartcloud-static-publisher/v1/${n}/`;return new URL(`${r}${t}`,i)}async post(t,n,i="content-sync"){let r=this.endpoint(t,i),a=Buffer.from(JSON.stringify(n),"utf8"),o=r.protocol==="https:"?Se:Ge,s=r.protocol==="https:"?new Se.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((c,u)=>{let g=o.request(r,{method:"POST",agent:s,headers:{"content-type":"application/json","content-length":String(a.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},d=>{let m=[],f=0;d.on("data",b=>{if(f+=b.byteLength,f>Ze){d.destroy(new Error("Content-sync API response exceeded the size limit."));return}m.push(b);}),d.on("error",u),d.on("end",()=>{let b=Buffer.concat(m).toString("utf8"),l;try{l=b?JSON.parse(b):{};}catch{u(new T(d.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let p=d.statusCode??500;if(p<200||p>=300){u(new T(p,String(l.code??"request-failed"),String(l.message??`Content-sync API request failed (${p}).`)));return}c(l);});});g.on("timeout",()=>g.destroy(new Error(`Content-sync API request timed out: ${t}`))),g.on("error",u),g.end(a);})}async head(t){return this.post("head",t)}async unboundHead(t,n){return this.post("head",{postTypes:t,includeSubsites:n})}async events(t){let n=[],i=t.afterSequence,r=new Set(t.postTypes);for(;i<t.throughSequence;){let a=await this.post("events",{...t,afterSequence:i,limit:250});if(a.fromSequence!==i||a.throughSequence!==t.throughSequence||a.nextSequence<i||a.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(a.items))throw new Error("Content-sync API returned a malformed event page.");let o=i;for(let s of a.items){if(!Number.isSafeInteger(s.sequence)||s.sequence<=o||s.sequence>t.throughSequence||!Number.isSafeInteger(s.postId)||s.postId<=0||!Number.isSafeInteger(s.blogId)||s.blogId<=0||!r.has(s.postType)||typeof s.operation!="string"||!s.operation)throw new Error("Content-sync API returned an invalid or out-of-scope journal event.");o=s.sequence;}if(a.items.length>0&&a.nextSequence!==o)throw new Error("Content-sync API event cursor does not match the final returned event.");if(n.push(...a.items),!a.hasMore)break;if(a.nextSequence===i)throw new Error("Content-sync API event pagination did not advance.");i=a.nextSequence;}if(t.throughSequence>t.afterSequence&&n.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return n}async resolveImpactFamilies(t,n){let i=await this.post("impact",{families:t,includeSubsites:n});return Array.isArray(i.families)?i.families:[]}async releaseFingerprint(t=false){let n=await this.post("fingerprint",{includeSubsites:t}),i=String(n.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(i))throw new Error("WordPress returned an invalid release fingerprint.");return i}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 Xe(e){return typeof e.subscriptionType=="string"&&e.subscriptionType.trim()!==""}function et(e,t){return {...e,...t??{}}}function tt(e,t){return {...e,...t??{},invalidationPaths:[...(t?.invalidationPaths??e.invalidationPaths)||[]]}}function ee(e,t){let n=String(t??e.deploymentTargetOverride??"").trim();if(!Xe(e)){if(n)throw new Error(`Deployment target "${n}" requires an active WPSuite subscription and remote publisher config.`);return {name:null,profile:null,config:e}}let i=String(n||e.defaultDeploymentProfile||"").trim();if(!i)return {name:null,profile:null,config:e};let r=e.deploymentProfiles?.[i];if(!r)throw new Error(`Unknown deployment profile "${i}". Check the linked WPSuite publisher configuration.`);return {name:i,profile:r,config:{...e,targetOrigin:r.targetOrigin??e.targetOrigin,s3:et(e.s3,r.s3),cloudFront:tt(e.cloudFront,r.cloudFront)}}}var te=["/sitemap_index.xml","/wp-sitemap.xml","/sitemap.xml"];function we(e){let t=new Set;for(let n of [...e,...te]){let i=String(n||"").trim();i&&t.add(i);}return [...t]}function Pe(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function ot(e){let t=String(e??"").trim();if(!t)return "";let n=t;if(/^https?:\/\//i.test(n))try{n=new URL(n).pathname;}catch{return ""}if(n=n.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!n)return "";let i=n.endsWith("/"),r=n.replace(/^\/+/,"").split("/").map(o=>o.replace(/[^A-Za-z0-9._-]/g,"")).filter(o=>o.length>0&&o!=="."&&o!=="..");if(r.length===0)return "";let a=`/${r.join("/")}`;return i&&h.extname(a)===""&&(a+="/"),a==="/"?"":a}function ne(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function st(e){if(!e||typeof e!="object")return {};let t={};for(let[n,i]of Object.entries(e)){let r=n.trim();if(!r||!i||typeof i!="object")continue;let a=i,o={};if(typeof a.targetOrigin=="string"){let c=Pe(a.targetOrigin);c&&(o.targetOrigin=c);}let s=ne(a.extraReplacements);if(Object.keys(s).length>0&&(o.extraReplacements=s),a.s3&&typeof a.s3=="object"){let c={},u=a.s3;typeof u.bucket=="string"&&(c.bucket=u.bucket.trim()),typeof u.prefix=="string"&&(c.prefix=u.prefix.trim()),typeof u.region=="string"&&(c.region=u.region.trim()),typeof u.htmlCacheControl=="string"&&(c.htmlCacheControl=u.htmlCacheControl.trim()),typeof u.assetCacheControl=="string"&&(c.assetCacheControl=u.assetCacheControl.trim()),Object.keys(c).length>0&&(o.s3=c);}if(a.cloudFront&&typeof a.cloudFront=="object"){let c={},u=a.cloudFront;typeof u.distributionId=="string"&&(c.distributionId=u.distributionId.trim()),Array.isArray(u.invalidationPaths)&&(c.invalidationPaths=u.invalidationPaths.map(g=>String(g??"").trim()).filter(g=>g.length>0)),Object.keys(c).length>0&&(o.cloudFront=c);}t[r]=o;}return t}function ie(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function at(e,t){if(!e||typeof e!="object")return null;let n=e,i=n.command;if(i!=="publish"&&i!=="crawl"&&i!=="deploy"&&i!=="invalidate"&&i!=="retry-timeouts"&&i!=="url"&&i!=="content-sync")return null;let r=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let a=String(n.id??`${i}-${t+1}`).trim();if(!a)return null;let o=String(n.deploymentProfile??"").trim(),s=String(n.url??"").trim(),c=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(g=>String(g??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],u=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(g=>String(g??"").trim()).filter(Boolean))]:[];return i==="content-sync"&&c.length===0?null:{id:a,enabled:n.enabled!==false,command:i,intervalMinutes:r,...i==="publish"||i==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(i==="publish"||i==="deploy"||i==="invalidate"||i==="content-sync")&&o?{deploymentProfile:o}:{},...s?{url:s}:{},...c.length>0?{postTypes:c}:{},...u.length>0?{listingPaths:u}:{},...typeof n.includeSubsites=="boolean"?{includeSubsites:n.includeSubsites}:{},...typeof n.includePostTypeArchives=="boolean"?{includePostTypeArchives:n.includePostTypeArchives}:{},...typeof n.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:n.includeTaxonomyArchives}:{},...typeof n.includeAuthorArchives=="boolean"?{includeAuthorArchives:n.includeAuthorArchives}:{},...typeof n.includeDateArchives=="boolean"?{includeDateArchives:n.includeDateArchives}:{},...typeof n.includePostsPage=="boolean"?{includePostsPage:n.includePostsPage}:{},...typeof n.includeSitemapChain=="boolean"?{includeSitemapChain:n.includeSitemapChain}:{}}}function Ce(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((i,r)=>at(i,r)).filter(i=>!!i):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function ct(e){let t=e&&typeof e=="object"?e:{},n=t.render&&typeof t.render=="object"?t.render:{},i=Number(n.concurrency??0),r=Number(n.batchSize??0),a=Number(n.maxAttempts??0),o=t.rewrite&&typeof t.rewrite=="object"?t.rewrite:{},s=t.deploy&&typeof t.deploy=="object"?t.deploy:{},c=(u,g)=>({enabled:typeof u.enabled=="boolean"?u.enabled:n.enabled===true,concurrency:Math.min(100,Math.max(1,Number(u.concurrency||g.concurrency))),batchSize:Math.min(500,Math.max(1,Number(u.batchSize||g.batchSize))),maxAttempts:Math.min(5,Math.max(1,Number(u.maxAttempts||2)))});return {render:{enabled:n.enabled===true,...Number.isInteger(i)&&i>0?{concurrency:i}:{},batchSize:Number.isInteger(r)&&r>0?Math.min(20,r):5,...Number.isInteger(a)&&a>0?{maxAttempts:Math.min(5,a)}:{}},rewrite:c(o,{concurrency:8,batchSize:25}),deploy:c(s,{concurrency:8,batchSize:50})}}function ut(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of ["accountId","siteId"]){let a=t[r];typeof a=="string"&&a.trim()!==""&&(n[r]=a.trim());}let i=Number(t.lastUpdate??0);return Number.isFinite(i)&&i>0&&(n.lastUpdate=Math.floor(i)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function oe(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),i=String(t.siteId??"").trim(),r=t.subscriber===true,a=ut(t.siteSettings),o={...a??{},...n?{accountId:a?.accountId??n}:{},...i?{siteId:a?.siteId??i}:{},...a?.subscriber===true||r?{subscriber:true}:{}},s={},c=String(t.apiBase??"").trim();c&&(s.apiBase=c);let u=String(t.runtimeToken??t.nonce??"").trim();u&&(s.runtimeToken=u);let g=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();g&&(s.virtualAssetBaseUrl=g),Object.keys(o).length>0&&(s.siteSettings=o);let d=ie(t.subscriptionType);return d&&(s.subscriptionType=d),s}function lt(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function Ae(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function dt(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[i,r]of new Headers(t.headers).entries())n.set(i,r);return n}async function Ie(e,t,n=5){let i=new URL(Ae(e)),r=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),a=i.protocol==="http:"?Ge:Se,o=dt(e,t);return await new Promise((s,c)=>{let u=a.request(i,{method:r,headers:Object.fromEntries(o.entries()),...i.protocol==="https:"?{rejectUnauthorized:false}:{}},g=>{let d=[];g.on("data",m=>{d.push(Buffer.isBuffer(m)?m:Buffer.from(m));}),g.on("error",c),g.on("end",()=>{let m=g.statusCode??0,f=g.headers.location;if(n>0&&f&&[301,302,303,307,308].includes(m)){s(Ie(new URL(f,i),{method:m===303?"GET":r},n-1));return}let b=new Headers;for(let[l,p]of Object.entries(g.headers))Array.isArray(p)?b.set(l,p.join(", ")):typeof p=="string"&&b.set(l,p);s(new Response(Buffer.concat(d),{status:m,statusText:g.statusMessage??"",headers:b}));});});u.on("error",c),u.end();})}function gt(e){let t=oe(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},i=String(n.accountId??"").trim(),r=String(n.siteId??"").trim(),a=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...a?{virtualAssetBaseUrl:a}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!i||!r||!a)return false;lt(e.sourceOrigin);let o=globalThis,c={...o.WpSuite??{},siteSettings:n,uploadUrl:a};return t.apiBase&&(c.apiBase=t.apiBase),o.WpSuite=c,true}async function pt(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!gt(e)){let r=e.wpsuite?.siteSettings,a=[String(r?.accountId??"").trim()?"":"accountId",String(r?.siteId??"").trim()?"":"siteId",t?"":"virtualAssetBaseUrl"].filter(Boolean);return {remote:null,diagnostic:{status:"invalid-runtime",virtualAssetBaseUrl:t,subscriptionType:null,error:`Missing WP Suite runtime field(s): ${a.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,i=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(c,u)=>{let g=Ae(c);if(g.startsWith(t)){let d=(()=>{try{return new URL(g).pathname}catch{return g}})();try{let m=e.ignoreHttpsErrors&&g.startsWith("https://")?await Ie(c,u):await n(c,u);return i.push({path:d,status:m.status,ok:m.ok,error:null}),m}catch(m){throw i.push({path:d,status:null,ok:!1,error:m instanceof Error?m.message:String(m)}),m}}return n(c,u)}));let{getConfig:r}=await import('@smart-cloud/wpsuite-core'),a=await r("publisher"),o=a&&typeof a=="object"?a:null,s=ie(o?.subscriptionType);return {remote:o,diagnostic:{status:o?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:s??null,error:o?null:"WP Suite publisher config loader returned no configuration.",requests:i}}}catch(r){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:r instanceof Error?r.message:String(r),requests:i}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function mt(e,t){let n=st(t?.deploymentProfiles),i=String(t?.defaultDeploymentProfile??"").trim(),r=n[i]?i:"",a=ie(t?.subscriptionType),o=oe(e.wpsuite);return {...e,scheduler:Ce(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:r,...a?{subscriptionType:a}:{},wpsuite:{...o,...o.siteSettings||a?{siteSettings:{...o.siteSettings??{},...o.siteSettings?.subscriber===true||a==="PROFESSIONAL"||a==="AGENCY"?{subscriber:true}:{}}}:{},...a?{subscriptionType:a}:{}}}}function re(e,t){let i=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!i)return t;let r=i.split("/").map(a=>a.trim()).filter(a=>a.length>0&&a!=="."&&a!=="..");return r.length>0?r.join("/"):t}function ht(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?h.resolve(e):""}function ve(e,t,n){let i=String(t||"").trim();return i&&h.isAbsolute(i)?h.resolve(i):h.resolve(e,re(i,n))}async function z(e,t={}){let n=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",i=await P.readFile(n,"utf8"),r=JSON.parse(i);r.sourceOrigin=r.sourceOrigin.replace(/\/$/,""),r.targetOrigin=Pe(r.targetOrigin),r.ignoreHttpsErrors??=false,r.outputDir=String(r.outputDir||"export").trim()||"export",r.urlRewriteMode||=r.targetOrigin==="."?"relative":"absolute",r.noJavaScriptRenderPathPrefixes||=[],r.seedPaths||=[],r.generated404RequestPath=ot(r.generated404RequestPath),r.sitemapPaths||=[...te],r.allowedAssetHosts||=[],r.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],r.blockedPathPrefixes||=[],r.blockedSearchFragments||=[],r.pageCache={purgeBeforeCrawl:r.pageCache?.purgeBeforeCrawl===true};let a=Number(r.processingConcurrency)>0?Math.min(100,Math.max(1,Number(r.processingConcurrency))):null;r.concurrency=a??r.concurrency??1,r.maxPages||=0,r.extraReplacements=ne(r.extraReplacements),r.postCrawlCopyMap=ne(r.postCrawlCopyMap),r.logDir=String(r.logDir||"logs").trim()||"logs",r.verbose??=false,r.logLevel||=r.verbose?"debug":"info",r.s3SyncMode||="sdk-upload-delete",r.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},r.readiness.timeoutMs??=1500,r.readiness.fallbackWaitMs??=1500,r.viewport||={width:1440,height:1200},r.navigationTimeoutMs||=3e4,r.assetDownloadConcurrency=a??(Number(r.assetDownloadConcurrency)>0?Number(r.assetDownloadConcurrency):r.concurrency),r.rewriteConcurrency=a??(Number(r.rewriteConcurrency)>0?Number(r.rewriteConcurrency):r.assetDownloadConcurrency),r.wpsuite=oe(r.wpsuite),r.scheduler=Ce(void 0),r.remoteWorkers=ct(r.remoteWorkers),typeof r.lambdaDelegationEnabled=="boolean"&&(r.remoteWorkers.render??={},r.remoteWorkers.rewrite??={},r.remoteWorkers.deploy??={},r.remoteWorkers.render.enabled=r.lambdaDelegationEnabled,r.remoteWorkers.rewrite.enabled=r.lambdaDelegationEnabled,r.remoteWorkers.deploy.enabled=r.lambdaDelegationEnabled),a!==null&&(r.processingConcurrency=a,r.remoteWorkers.render??={},r.remoteWorkers.rewrite??={},r.remoteWorkers.deploy??={},r.remoteWorkers.render.concurrency=a,r.remoteWorkers.rewrite.concurrency=a,r.remoteWorkers.deploy.concurrency=a),r.deploymentProfiles={},r.defaultDeploymentProfile="",r.deploymentTargetOverride=String(r.deploymentTargetOverride??"").trim();let o=await pt(r);t.onRemotePublisherConfigDiagnostic?.(o.diagnostic);let s=mt(r,o.remote),c=ht(),u=c?h.resolve(c,".."):"";return u?(s.outputDir=ve(u,s.outputDir,"export"),s.logDir=ve(u,s.logDir,"logs")):(h.isAbsolute(s.outputDir)||(s.outputDir=re(s.outputDir,"export")),h.isAbsolute(s.logDir)||(s.logDir=re(s.logDir,"logs"))),s}function Re(e){let t=e.split(/\r?\n/).map(i=>i.trim()).filter(Boolean),n=[...t].reverse().find(i=>/^(?:Error|[A-Za-z][A-Za-z0-9]*Error):\s/.test(i));return n||(t.find(i=>!i.startsWith("at "))??"")}function se(e){let t=h.resolve(e);return {state:h.join(t,"content-sync-state.json"),current:h.join(t,"content-sync-current.json"),impact:h.join(t,"content-sync-impact-plan.json"),checkpoint:h.join(t,"content-sync-checkpoint.json"),baseline:h.join(t,"content-sync-baseline.json"),activeRules:h.join(t,"content-sync-active-rules.json"),releaseCutoff:h.join(t,"content-sync-release-cutoff.json"),candidateManifest:h.join(t,"content-sync-candidate-manifest.json"),trustedManifest:h.join(t,"crawl-manifest.json"),invalidation:h.join(t,"content-sync-invalidation.json"),deployPlan:h.join(t,"deploy-plan.json")}}async function M(e,t,n=[],i=[],r=false){await xe(e.activeRules,{contractVersion:1,evaluatedAt:new Date().toISOString(),discoveryReady:r,entries:t,targets:n,rules:i});}async function xe(e,t){await P.mkdir(h.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await P.writeFile(n,JSON.stringify(t,null,2),"utf8"),await P.rename(n,e);}async function ke(e){try{return JSON.parse(await P.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 ft(e){let t=await ke(e.current);if(t===null)return null;let n=t;if(n.schemaVersion!==1||typeof n.jobId!="string"||typeof n.phase!="string"||!Number.isSafeInteger(n.fromSequence)||!Number.isSafeInteger(n.toSequence))throw new Error("Invalid content-sync current-range state.");return n}async function qe(e){let t=await ke(e.state);if(t===null)return {schemaVersion:1,updatedAt:"",rules:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.rules||typeof n.rules!="object"||Array.isArray(n.rules))throw new Error("Invalid content-sync state store.");return n}async function De(e,t){await xe(e.state,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Te(e,t){let n=await ft(e);return !n||n.coalesceKey!==t?false:(await Promise.all([e.current,e.checkpoint,e.impact,e.candidateManifest,e.invalidation,e.deployPlan].map(async i=>{try{await P.unlink(i);}catch(r){if(r.code!=="ENOENT")throw r}})),true)}function Le(e){let t=String(e.command??"").trim();return (t==="publish"||t==="crawl")&&e.crawlMode==="incremental"||t==="content-sync"}var ae=new Map;async function Ee(e){let t=h.resolve(e),n=ae.get(t);if(n!==void 0)return n;try{let i=JSON.parse(await P.readFile(t,"utf8")),r=String(i.version??"").trim();return ae.set(t,r),r}catch{return ae.set(t,""),""}}var $=class extends Error{request;step;constructor(t,n){super(`Stop requested during ${n}.`),this.name="StopRequestedError",this.request=t,this.step=n;}},Pt="queue-mutation.lock",Ct=5e3,At=3e4;function It(e){let t=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",n=process.env.STATIC_PUBLISHER_EXPORTER_DIR||process.cwd(),i=process.env.PUBLISHER_CONFIG||"",r=1;for(let s=0;s<e.length;s++){let c=e[s];c==="--runtime-dir"?t=e[++s]||"":c.startsWith("--runtime-dir=")?t=c.slice(14):c==="--exporter-dir"?n=e[++s]||n:c.startsWith("--exporter-dir=")?n=c.slice(15):c==="--config"?i=e[++s]||"":c.startsWith("--config=")?i=c.slice(9):c==="--max-jobs"?r=Number.parseInt(e[++s]||"1",10):c.startsWith("--max-jobs=")&&(r=Number.parseInt(c.slice(11),10));}if(!t)throw new Error("Missing runtime dir. Use --runtime-dir or STATIC_PUBLISHER_RUNTIME_DIR.");let a=h.resolve(t),o=i?h.resolve(i):h.join(a,"config.json");return {runtimeDir:a,exporterDir:h.resolve(n),configPath:o,maxJobs:Number.isFinite(r)&&r>0?r:1}}async function w(e,t){try{let n=await P.readFile(e,"utf8");return JSON.parse(n)}catch(n){if((n&&typeof n=="object"&&"code"in n?String(n.code||""):"")!=="ENOENT"){let r=n instanceof Error?n.message:String(n);console.warn(`[queue-runner] failed to read JSON ${e}: ${r}`);}return t}}async function v(e,t){await P.mkdir(h.dirname(e),{recursive:true}),await P.writeFile(e,JSON.stringify(t,null,2),"utf8");}function Be(e){return h.join(e,Pt)}async function Rt(e){await new Promise(t=>setTimeout(t,e));}async function xt(e){let t=Be(e),n=Date.now()+Ct;for(;;)try{await P.mkdir(h.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()},null,2),{encoding:"utf8",flag:"wx"});return}catch(i){if((i&&typeof i=="object"&&"code"in i?String(i.code||""):"")!=="EEXIST")throw i;let a=await P.stat(t).catch(()=>null);if(a&&Date.now()-a.mtimeMs>At){await P.unlink(t).catch(()=>{});continue}if(Date.now()>=n)throw new Error("Timed out acquiring queue mutation lock.",{cause:i});await Rt(50);}}async function kt(e){await P.unlink(Be(e)).catch(()=>{});}async function F(e,t){await xt(e);try{return await t()}finally{await kt(e);}}function Me(e){return h.join(e,"queue-runner-heartbeat.json")}function ge(e){return h.join(e,"current-progress.json")}function ce(e){return h.join(e,"scheduler-state.json")}function qt(e,t){let i=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!i)return t;let r=i.split("/").map(a=>a.trim()).filter(a=>a.length>0&&a!=="."&&a!=="..");return r.length>0?r.join("/"):t}async function Ue(e){let t=await w(e.configPath||"",null),n=h.resolve(e.runtimeDir,".."),r=(typeof t?.logDir=="string"?t.logDir:"").trim();return r&&h.isAbsolute(r)?h.resolve(r):h.resolve(n,qt(r,"logs"))}function ue(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||t}function Dt(e){let t=e?new Date(e):new Date;return (Number.isNaN(t.getTime())?new Date:t).toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function Tt(e){return [Dt(e.endedAt||e.startedAt),ue(e.command||"job","job"),ue(e.id||"job","job"),ue(e.status||"finished","finished")].join("-")}function Et(e){return e.endsWith(".log.jsonl")||e.endsWith(".errors.jsonl")||e.endsWith(".rejected.jsonl")?true:["current-crawl-event.json","rejected.jsonl","ignored.jsonl","skipped-http.jsonl","errors.jsonl","timings.jsonl","rejected.json","ignored.json","skipped-http.json","errors.json","timings.json"].includes(e)}function Ft(e){return e==="errors.json"||e==="errors.jsonl"||e.endsWith(".errors.jsonl")?"errors":e==="ignored.json"||e==="ignored.jsonl"?"ignored":e==="rejected.json"||e==="rejected.jsonl"||e.endsWith(".rejected.jsonl")?"rejected":e==="skipped-http.json"||e==="skipped-http.jsonl"?"skipped-http":e==="timings.json"||e==="timings.jsonl"?"timings":e==="current-progress.json"?"current-progress":e==="current-crawl-event.json"?"current-crawl-event":e.endsWith(".log.jsonl")?e.replace(/\.log\.jsonl$/i,"-log"):e.replace(/\.[^.]+$/u,"")||"artifact"}function jt(e){return e.endsWith(".gz")?"application/gzip":e.endsWith(".jsonl")?"application/x-ndjson":e.endsWith(".json")?"application/json":"text/plain"}async function K(e,t,n){let i=`${n}.gz`,r=h.join(t,i);await pipeline(createReadStream(e),createGzip({level:9}),createWriteStream(r));let[a,o]=await Promise.all([P.stat(e),P.stat(r)]);return {role:Ft(n),originalFileName:n,storedFileName:i,compressed:true,compression:"gzip",contentType:jt(i),originalSize:a.size,storedSize:o.size}}async function _(e,t){let n=await Ue(t),i=new Date().toISOString(),r=Tt(e),a=h.join(n,"archive",r),o=[],s=[];await P.mkdir(a,{recursive:true});try{let d=await P.readdir(n,{withFileTypes:!0});for(let m of d){if(!m.isFile()||!Et(m.name))continue;let f=await K(h.join(n,m.name),a,m.name);s.push(f),o.push(f.storedFileName);}}catch(d){if((d&&typeof d=="object"&&"code"in d?String(d.code||""):"")!=="ENOENT")throw d}let c=ge(t.runtimeDir);if(existsSync(c)){let d=await K(c,a,"current-progress.json");s.push(d),o.push(d.storedFileName);}if(e.command==="content-sync")for(let d of ["content-sync-current.json","content-sync-impact-plan.json","content-sync-checkpoint.json","content-sync-state.json","content-sync-invalidation.json","deploy-plan.json"]){let m=h.join(t.runtimeDir,d);if(!existsSync(m))continue;let f=await K(m,a,d);s.push(f),o.push(f.storedFileName);}let u=h.join(t.runtimeDir,"privacy","cookie-observations.json");if(existsSync(u)){let d=await K(u,a,"cookie-observations.json");s.push(d),o.push(d.storedFileName);}let g=[...o,"job.json"];return await v(h.join(a,"job.json"),{manifestVersion:1,archivedAt:i,archiveKey:r,archiveDir:a,logDir:n,runtimeDir:t.runtimeDir,exporterDir:t.exporterDir,configPath:t.configPath||"",archivedFiles:g,artifacts:s,job:e}),{archiveKey:r,archiveDir:a,archiveCreatedAt:i,archivedFiles:g,artifacts:s}}function Ot(e){return h.join(e,"audit-events.jsonl")}function le(e){return h.join(e,"stop-request.json")}async function We(e){try{let t=await P.readFile(le(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}async function Fe(e,t){let n=await We(e);if(!n)return null;let i=String(n.targetJobId||"").trim();return i&&i!==t?null:n}async function W(e,t){if(!t){await P.unlink(le(e)).catch(()=>{});return}let n=await We(e);if(!n)return;let i=String(n.targetJobId||"").trim();(!i||i===t)&&await P.unlink(le(e)).catch(()=>{});}async function R(e,t){try{let n={occurredAt:t.occurredAt||new Date().toISOString(),status:t.status||"info",actorSource:t.actorSource||"queue-runner",...t};await P.mkdir(e,{recursive:!0}),await P.appendFile(Ot(e),`${JSON.stringify(n)}
|
|
2
2
|
`,"utf8");}catch{}}async function C(e,t,n){let[i,r]=await Promise.all([Ee(h.join(e.exporterDir,"package.json")),Ee(h.join(e.exporterDir,"node_modules","@smart-cloud","wpsuite-core","package.json"))]),a={checkedAt:new Date().toISOString(),status:t,pid:process.pid,nodePath:process.execPath,nodeVersion:process.version,exporterVersion:i,wpsuiteCoreVersion:r,runtimeDir:e.runtimeDir,exporterDir:e.exporterDir,...n??{}};try{await v(Me(e.runtimeDir),a);}catch{}}async function E(e){try{await P.unlink(ge(e));}catch{}}function Jt(e,t){let n=e.command;if(n!=="publish"&&n!=="crawl"&&n!=="deploy"&&n!=="invalidate"&&n!=="retry-timeouts"&&n!=="url"&&n!=="content-sync")return null;let i=Number.parseInt(String(e.intervalMinutes??"0"),10);if(!Number.isFinite(i)||i<1)return null;let r=(e.id||`${n}-${t+1}`).trim();if(!r)return null;let a=e.enabled!==false,o=typeof e.url=="string"?e.url.trim():"",s=typeof e.deploymentProfile=="string"?e.deploymentProfile.trim():"",c=Array.isArray(e.postTypes)?[...new Set(e.postTypes.map(d=>String(d).trim()).filter(Boolean))]:[],u=Array.isArray(e.listingPaths)?[...new Set(e.listingPaths.map(d=>String(d).trim()).filter(Boolean))]:[],g=(n==="publish"||n==="crawl")&&e.crawlMode==="incremental"?"incremental":"full";return n==="url"&&!o||n==="content-sync"&&c.length===0?null:{id:r,enabled:a,command:n,intervalMinutes:i,...n==="publish"||n==="crawl"?{crawlMode:g}:{},...(n==="publish"||n==="deploy"||n==="invalidate"||n==="content-sync")&&s?{deploymentProfile:s}:{},...o?{url:o}:{},...c.length>0?{postTypes:c}:{},...u.length>0?{listingPaths:u}:{},...typeof e.includeSubsites=="boolean"?{includeSubsites:e.includeSubsites}:{},...typeof e.includePostTypeArchives=="boolean"?{includePostTypeArchives:e.includePostTypeArchives}:{},...typeof e.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:e.includeTaxonomyArchives}:{},...typeof e.includeAuthorArchives=="boolean"?{includeAuthorArchives:e.includeAuthorArchives}:{},...typeof e.includeDateArchives=="boolean"?{includeDateArchives:e.includeDateArchives}:{},...typeof e.includePostsPage=="boolean"?{includePostsPage:e.includePostsPage}:{},...typeof e.includeSitemapChain=="boolean"?{includeSitemapChain:e.includeSitemapChain}:{}}}async function Lt(e){let t=await z(e.configPath).catch(()=>null),n=t?.scheduler,i=Array.isArray(n?.rules)?n.rules.map((r,a)=>Jt(r,a)).filter(r=>!!r):[];return {enabled:!!n?.enabled,timezone:typeof n?.timezone=="string"&&n.timezone.trim()?n.timezone.trim():"UTC",rules:i,wpsuite:t?.wpsuite,publisherConfig:t}}function N(e,t){if(!t)throw new Error("Content-sync scheduler requires a valid publisher config.");let n=Q({postTypes:e.postTypes??[],listingPaths:e.listingPaths??[],includeSubsites:e.includeSubsites,includePostTypeArchives:e.includePostTypeArchives,includeTaxonomyArchives:e.includeTaxonomyArchives,includeAuthorArchives:e.includeAuthorArchives,includeDateArchives:e.includeDateArchives,includePostsPage:e.includePostsPage,includeSitemapChain:e.includeSitemapChain}),i=Z(t.sourceOrigin,e.id,n),r=ee(t,e.deploymentProfile),a=X({sourceOrigin:t.sourceOrigin,targetOrigin:r.config.targetOrigin,deploymentProfile:r.name||"",s3Bucket:r.config.s3.bucket,s3Prefix:r.config.s3.prefix,cloudFrontDistributionId:r.config.cloudFront.distributionId,urlRewriteMode:r.config.urlRewriteMode,extraReplacements:r.profile?.extraReplacements??{}});return `content-sync:${e.id}:${J({scopeFingerprint:i,targetFingerprint:a}).slice(0,32)}`}function Bt(e,t,n,i){let r=[n[t],i[t]].filter(o=>!!o).filter(o=>o.coalesceKey===t&&o.ruleId===e.id).map(o=>String(o.consumerId??"").trim()).filter(Boolean),a=[...new Set(r)];return a.length===1?a[0]:""}async function je(e,t){let n=se(e.runtimeDir);if(await M(n,[]),!t?.publisherConfig)return;let i=t.publisherConfig,r=i.deploymentProfiles??{},a=String(i.defaultDeploymentProfile??"").trim(),o=a?r[a]:void 0,s=[{target:"default",resolvedDeploymentProfile:o?a:"",targetOrigin:String(o?.targetOrigin??i.targetOrigin??"").trim()},...Object.keys(r).sort((p,S)=>p.localeCompare(S)).map(p=>({target:p,resolvedDeploymentProfile:p,targetOrigin:String(r[p]?.targetOrigin??i.targetOrigin??"").trim()}))],c=t.rules.filter(p=>p.command==="content-sync"),u=c.map(p=>({ruleId:p.id,coalesceKey:N(p,i),target:String(p.deploymentProfile??"").trim()||"default",effectiveTarget:String(p.deploymentProfile??i.defaultDeploymentProfile??"").trim()||"default",enabled:p.enabled,active:t.enabled&&p.enabled,intervalMinutes:p.intervalMinutes,postTypes:[...p.postTypes??[]],listingPaths:[...p.listingPaths??[]]}));if(!t.enabled){await M(n,[],s,u,true);return}let g=c.filter(p=>p.enabled);if(g.length===0){await M(n,[],s,u,true);return}let[d,m]=await Promise.all([w(n.state,{}),w(n.baseline,{})]),f=d.rules??{},b=m.entries??{},l=[];for(let p of g){let S=N(p,i),x=Bt(p,S,f,b);x&&l.push({ruleId:p.id,coalesceKey:S,consumerId:x});}await M(n,l,s,u,true);}async function Mt(e,t,n,i,r){let o=(await w(h.join(e.runtimeDir,"content-sync-baseline.json"),{})).entries?.[i];if(!o?.consumerId||!o.scopeFingerprint||!o.baselineId)return {status:"baseline-required",reason:"No verified normal-release baseline exists for this rule scope."};try{let s=t.publisherConfig;if(!s)throw new Error("Publisher configuration is unavailable.");let c=Q({postTypes:n.postTypes??[],listingPaths:n.listingPaths??[],includeSubsites:n.includeSubsites,includePostTypeArchives:n.includePostTypeArchives,includeTaxonomyArchives:n.includeTaxonomyArchives,includeAuthorArchives:n.includeAuthorArchives,includeDateArchives:n.includeDateArchives,includePostsPage:n.includePostsPage,includeSitemapChain:n.includeSitemapChain}),u=Z(s.sourceOrigin,n.id,c),g=ee(s,n.deploymentProfile),d=X({sourceOrigin:s.sourceOrigin,targetOrigin:g.config.targetOrigin,deploymentProfile:g.name||"",s3Bucket:g.config.s3.bucket,s3Prefix:g.config.s3.prefix,cloudFrontDistributionId:g.config.cloudFront.distributionId,urlRewriteMode:g.config.urlRewriteMode,extraReplacements:g.profile?.extraReplacements??{}});if(o.scopeFingerprint!==u||o.targetFingerprint!==d||!o.releaseFingerprint)return {status:"baseline-required",reason:"The verified content-sync baseline does not match the active scope or deployment target. Run a successful full or incremental publish to establish a new baseline."};let m=new L({sourceOrigin:s.sourceOrigin,runtimeToken:String(s.wpsuite?.runtimeToken||""),ignoreHttpsErrors:s.ignoreHttpsErrors}),f=await m.releaseFingerprint(c.includeSubsites),b=fe({wordpressFingerprint:f,targetFingerprint:d,sourceOrigin:s.sourceOrigin,sitemapPaths:we(s.sitemapPaths),blockedPathPrefixes:s.blockedPathPrefixes,assetPathPrefixes:s.assetPathPrefixes,noJavaScriptRenderPathPrefixes:s.noJavaScriptRenderPathPrefixes,urlRewriteMode:s.urlRewriteMode});if(o.releaseFingerprint!==b)return {status:"baseline-required",reason:"The installed WordPress release changed after the last verified content-sync baseline. Run a successful full or incremental publish to establish a new baseline."};let l=await m.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:o.baselineId,postTypes:c.postTypes,includeSubsites:c.includeSubsites}),p=l.committedSequence;if(r?.command==="content-sync"&&r.coalesceKey===i){let S=await w(h.join(e.runtimeDir,"content-sync-current.json"),null);S?.coalesceKey===i&&Number.isSafeInteger(S.toSequence)&&(p=Math.max(p,Number(S.toSequence)));}return {status:l.headSequence>p?"pending":"current",headSequence:l.headSequence,committedSequence:l.committedSequence}}catch(s){return s instanceof T&&s.code==="baseline-required"?{status:"baseline-required",reason:s.message}:{status:"unavailable",reason:s instanceof Error?s.message:String(s)}}}async function Ne(e,t,n,i,r,a){let o=h.join(e.runtimeDir,"content-sync-state.json"),c=(await w(o,{})).rules??{},u=c[n]??{};c[n]={...u,ruleId:t,coalesceKey:n,...Number.isSafeInteger(r)?{observedHeadSequence:r}:{},...Number.isSafeInteger(a)?{committedSequence:a}:{},retryAttempt:0,nextRetryAt:null,lastError:i,baselineStatus:"required",baselineReason:i,trailingWorkDetected:Number.isSafeInteger(r)&&Number.isSafeInteger(a)?Number(r)>Number(a):!!u.trailingWorkDetected},await v(o,{schemaVersion:1,updatedAt:new Date().toISOString(),rules:c});}function de(e,t){let n=(t.url||"").trim(),i=t.crawlMode||"full",r=(t.deploymentProfile||"").trim(),a=(t.coalesceKey||"").trim();return e.some(o=>o.command===t.command&&(t.command!=="content-sync"||(o.coalesceKey||"").trim()===a)&&(o.url||"").trim()===n&&(o.crawlMode||"full")===i&&(o.deploymentProfile||"").trim()===r&&(o.status===void 0||o.status==="queued"||o.status==="retry-wait"||o.status==="running"))}async function Ut(e,t,n){if(!t.allowSchedulerAutoEnqueue)return await je(e,null),0;let i=await Lt(e);if(await je(e,i),!i.enabled||i.rules.length===0)return 0;if(t.assertActiveSubscriptionForIdentity)try{await t.assertActiveSubscriptionForIdentity(i.wpsuite??null);}catch(l){let p=l instanceof Error?l.message:String(l);return console.warn(`[queue-runner] scheduler auto-enqueue skipped: ${p}`),0}let r=h.join(e.runtimeDir,"queue.json"),a=h.join(e.runtimeDir,"current-run.json"),o=Date.now(),s=0,c=[],u=[],g=[],d=new Map,[m,f,b]=await Promise.all([w(r,[]),w(a,null),w(ce(e.runtimeDir),{lastEnqueuedBucketByRuleId:{},lastEvaluatedBucketByRuleId:{},lastCreatedBucketByRuleId:{},coalescedCountByRuleId:{}})]);for(let l of i.rules){if(!l.enabled||l.command!=="content-sync")continue;let p=Math.floor(o/(l.intervalMinutes*60*1e3)),S=b.lastEvaluatedBucketByRuleId?.[l.id]??b.lastEnqueuedBucketByRuleId?.[l.id]??-1;if(p<=S)continue;let x=N(l,i.publisherConfig);de(m,{command:l.command,deploymentProfile:l.deploymentProfile,coalesceKey:x})||d.set(l.id,await Mt(e,i,l,x,f));}await F(e.runtimeDir,async()=>{let l=await w(r,[]),p=await w(a,null),S=await w(ce(e.runtimeDir),{lastEnqueuedBucketByRuleId:{},lastEvaluatedBucketByRuleId:{},lastCreatedBucketByRuleId:{},coalescedCountByRuleId:{}});S.lastEnqueuedBucketByRuleId??={},S.lastEvaluatedBucketByRuleId??={...S.lastEnqueuedBucketByRuleId},S.lastCreatedBucketByRuleId??={...S.lastEnqueuedBucketByRuleId},S.coalescedCountByRuleId??={};let x=[...l];p&&p.status==="running"&&x.unshift(p);for(let y of i.rules){if(!y.enabled)continue;let A=y.intervalMinutes*60*1e3,q=Math.floor(o/A),j=S.lastEvaluatedBucketByRuleId[y.id]??S.lastEnqueuedBucketByRuleId[y.id]??-1;if(q<=j)continue;let O=y.command==="content-sync"?N(y,i.publisherConfig):"";S.lastEvaluatedBucketByRuleId[y.id]=q;let ze=y.command==="content-sync"?l:x;if(de(ze,{command:y.command,url:y.url,crawlMode:y.crawlMode,deploymentProfile:y.deploymentProfile,coalesceKey:O})){S.coalescedCountByRuleId[y.id]=(S.coalescedCountByRuleId[y.id]??0)+1,u.push(y);continue}if(y.command==="content-sync"){let G=d.get(y.id);if(!G||G.status!=="pending"){let me=G??{status:"unavailable",reason:"Content-sync demand was not checked."};me.status!=="current"&&g.push({rule:y,check:me});continue}}let V={id:randomUUID(),command:y.command,...y.command==="content-sync"?{ruleId:y.id,coalesceKey:O,attempt:0}:{},...(y.command==="publish"||y.command==="crawl")&&y.crawlMode?{crawlMode:y.crawlMode}:{},...(y.command==="publish"||y.command==="deploy"||y.command==="invalidate"||y.command==="content-sync")&&y.deploymentProfile?{deploymentProfile:y.deploymentProfile}:{},...y.url?{url:y.url}:{},enqueueSource:"scheduler",...i.wpsuite?{wpsuite:i.wpsuite}:{},status:"queued",createdAt:new Date().toISOString(),createdBy:0};l.push(V),x.push(V),c.push({job:V,rule:y}),S.lastEnqueuedBucketByRuleId[y.id]=q,S.lastCreatedBucketByRuleId[y.id]=q,s+=1;}s>0&&await v(r,l),await v(ce(e.runtimeDir),S);});for(let l of c){if(l.rule.command==="content-sync"){let p=d.get(l.rule.id);await R(e.runtimeDir,{eventType:"content-sync-demand-detected",status:"queued",actorSource:"queue-runner-scheduler",jobId:l.job.id,command:l.job.command,message:"Pending journal changes require a content-sync job.",details:{ruleId:l.rule.id,headSequence:p?.headSequence??0,committedSequence:p?.committedSequence??0}});}await R(e.runtimeDir,{eventType:"job-created",status:"queued",actorSource:"queue-runner-scheduler",jobId:l.job.id,command:l.job.command,message:"Scheduler auto-enqueued a job.",details:{ruleId:l.rule.id,intervalMinutes:l.rule.intervalMinutes,timezone:i.timezone,deploymentProfile:l.rule.deploymentProfile||"",url:l.rule.url||""}});}for(let l of u)await R(e.runtimeDir,{eventType:"content-sync-coalesced",status:"queued",actorSource:"queue-runner-scheduler",command:l.command,message:"Scheduler demand was coalesced into an existing content-sync job.",details:{ruleId:l.id}});for(let l of g){if(l.check.status==="baseline-required"){let p=N(l.rule,i.publisherConfig);await Ne(e,l.rule.id,p,l.check.reason||"A successful full or incremental publish must establish a new content-sync baseline.",l.check.headSequence,l.check.committedSequence);}await R(e.runtimeDir,{eventType:l.check.status==="baseline-required"?"content-sync-baseline-required":"content-sync-demand-check-failed",status:l.check.status==="unavailable"?"failed":"info",actorSource:"queue-runner-scheduler",command:"content-sync",message:l.check.reason||"The content-sync consumer is already at the current journal head.",details:{ruleId:l.rule.id,headSequence:l.check.headSequence??0,committedSequence:l.check.committedSequence??0}});}return s}async function Wt(e){let t={pid:process.pid,startedAt:new Date().toISOString()};await P.writeFile(e,JSON.stringify(t,null,2),{encoding:"utf8",flag:"wx"});}async function Nt(e){try{await P.unlink(e);}catch{}}function $t(e,t){let n=[h.join(e,"dist",`${t}.js`),h.join(e,`${t}.js`)];for(let i of n)if(existsSync(i))return i;throw new Error(`Cannot find ${t}.js in ${h.join(e,"dist")} or ${e}`)}async function k(e,t,n,i,r,a,o){if(o){let u=await Fe(t,o);if(u)throw new $(u,n)}let s=$t(e,n),c={...process.env,...a??{}};return c.STATIC_PUBLISHER_RUNTIME_DIR=t,r&&(c.PUBLISHER_CONFIG=r),await new Promise((u,g)=>{let d=null,m=null,f=null,b=null,l=false,p="",S=spawn(process.execPath,[s,...i],{cwd:e,env:c,stdio:["inherit","inherit","pipe"]});S.stderr?.on("data",A=>{p+=A.toString("utf8");});let x=()=>{m&&clearInterval(m),f&&clearInterval(f),b&&clearTimeout(b);},y=async()=>{if(!(!o||d||l)){l=true;try{let A=await Fe(t,o);if(!A)return;d=A,S.kill("SIGTERM"),b=setTimeout(()=>{S.kill("SIGKILL");},1e4);}finally{l=false;}}};o&&(m=setInterval(()=>{y();},1e3),f=setInterval(()=>{(async()=>{let A=Me(t),q=await w(A,{});await v(A,{...q,checkedAt:new Date().toISOString(),status:"running",currentJobId:o||q.currentJobId||"",currentStep:n});})().catch(()=>{});},15e3)),S.on("error",A=>{x(),g(A);}),S.on("close",(A,q)=>{x();let j=be(p).trim();if(j&&process.stderr.write(`${j}
|
|
3
3
|
`),d){g(new $(d,n));return}if(A===0)u();else {let O=Re(j);g(new Error(`${n} exited with code ${A??-1}${q?` (signal ${q})`:""}${O?`: ${O}`:""}`));}});}),0}function Qt(e){let t=e.awsTempCreds;if(!t)return {};let n={};return typeof t.accessKeyId=="string"&&t.accessKeyId.trim()!==""&&(n.AWS_ACCESS_KEY_ID=t.accessKeyId.trim()),typeof t.secretAccessKey=="string"&&t.secretAccessKey.trim()!==""&&(n.AWS_SECRET_ACCESS_KEY=t.secretAccessKey.trim()),typeof t.sessionToken=="string"&&t.sessionToken.trim()!==""&&(n.AWS_SESSION_TOKEN=t.sessionToken.trim()),n}async function zt(e,t){let n=o=>{if(!o||typeof o!="object")return null;let s=o,c={...s.siteSettings??{},...String(s.accountId??"").trim()&&!s.siteSettings?.accountId?{accountId:String(s.accountId).trim()}:{},...String(s.siteId??"").trim()&&!s.siteSettings?.siteId?{siteId:String(s.siteId).trim()}:{},...s.siteSettings?.subscriber===true||s.subscriber===true?{subscriber:true}:{}},u={...String(s.apiBase??"").trim()?{apiBase:String(s.apiBase).trim()}:{},...String(s.runtimeToken??s.nonce??"").trim()?{runtimeToken:String(s.runtimeToken??s.nonce).trim()}:{},...String(s.virtualAssetBaseUrl??s.uploadUrl??"").trim()?{virtualAssetBaseUrl:String(s.virtualAssetBaseUrl??s.uploadUrl).trim()}:{},...Object.keys(c).length>0?{siteSettings:c}:{},...s.subscriptionType?{subscriptionType:s.subscriptionType}:{}};return Object.keys(u).length>0?u:null},i=await z(t.configPath).catch(()=>null),r=n(i?.wpsuite);if(r)return r;let a=n(e.wpsuite);return a||null}async function Kt(e,t){return await zt(e,t)}function pe(e){let t={...e,status:"queued"};return delete t.startedAt,delete t.endedAt,delete t.exitCode,delete t.error,delete t.stopRequestedAt,delete t.stopRequestedByUserId,delete t.stopRequestedByLogin,delete t.stopMode,delete t.stoppedStep,t}async function _t(e,t){let n=await w(ge(e.runtimeDir),null),i=n&&n.details&&typeof n.details.phase=="string"?n.details.phase.trim():"";if(i)return i;let r=n&&typeof n.currentStep=="string"?n.currentStep.trim():"";if(r)return r;let a=await Ue(e).catch(()=>"");if(a){let o=await w(h.join(a,"current-crawl-event.json"),null),s=o&&typeof o.currentStep=="string"?o.currentStep.trim():"";if(s)return s}return t}function Ht(e,t){if((e.command==="publish"||e.command==="crawl")&&t==="rewrite-text")return "rewrite-text"}async function Vt(e){let t=h.join(e.runtimeDir,"queue.json"),n=h.join(e.runtimeDir,"current-run.json"),i=await F(e.runtimeDir,async()=>{let r=await w(n,null);if(!r||r.status!=="running"&&r.status!=="queued")return null;let a=await w(t,[]),o=Array.isArray(a)?a.filter(c=>c?.id!==r.id):[],s=pe(r);return await v(t,[s,...o]),await v(n,null),s});i&&(await W(e.runtimeDir,i.id),await R(e.runtimeDir,{eventType:"job-recovered",status:"queued",actorSource:"queue-runner",jobId:i.id,command:i.command,message:"Recovered stale current-run entry back into queue."}));}async function U(e,t){if(e.resumeFromStep==="rewrite-text")return;let n=h.join(t.runtimeDir,"privacy","cookie-observations.json"),i;try{let s=await P.stat(n);if(!s.isFile()||s.size>5*1024*1024)throw new Error("Cookie observation artifact is missing or exceeds 5 MiB.");i=JSON.parse(await P.readFile(n,"utf8"));}catch(s){if((s&&typeof s=="object"&&"code"in s?String(s.code||""):"")==="ENOENT")return;throw s}let r=await z(t.configPath),a=String(r.wpsuite?.runtimeToken||"").trim();if(!a)return;await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"consent-cookie-observations"}),await new L({sourceOrigin:r.sourceOrigin,runtimeToken:a,ignoreHttpsErrors:!!r.ignoreHttpsErrors}).importCookieObservations(i);}async function Gt(e,t,n){try{if((n.shouldEnforceSubscriptionOnJobExecution?.(e)??n.enforceSubscriptionOnJobExecution)&&n.assertActiveSubscriptionForIdentity){let s=await Kt(e,t);await n.assertActiveSubscriptionForIdentity(s);}let r=Qt(e),a=e.resumeFromStep==="rewrite-text"?["--resume-rewrite"]:e.crawlMode==="incremental"?["--crawl-mode","incremental"]:[],o=e.deploymentProfile?["--profile",e.deploymentProfile]:[];if(e.command==="publish")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync-release-cutoff"}),await k(t.exporterDir,t.runtimeDir,"content-sync",["--capture-baseline-cutoffs",e.id],t.configPath,r,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await k(t.exporterDir,t.runtimeDir,"crawl",a,t.configPath,r,e.id),await U(e,t),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await k(t.exporterDir,t.runtimeDir,"deploy",o,t.configPath,r,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await k(t.exporterDir,t.runtimeDir,"invalidate",o,t.configPath,r,e.id),await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync-baseline"}),await k(t.exporterDir,t.runtimeDir,"content-sync",["--establish-baselines",e.id],t.configPath,r,e.id),{exitCode:0};if(e.command==="crawl")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await k(t.exporterDir,t.runtimeDir,"crawl",a,t.configPath,r,e.id),await U(e,t),{exitCode:0};if(e.command==="deploy")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await k(t.exporterDir,t.runtimeDir,"deploy",o,t.configPath,r,e.id),{exitCode:0};if(e.command==="invalidate")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await k(t.exporterDir,t.runtimeDir,"invalidate",o,t.configPath,r,e.id),{exitCode:0};if(e.command==="retry-timeouts")return await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"retry-timeouts"}),await k(t.exporterDir,t.runtimeDir,"crawl",["--retry-timeouts"],t.configPath,r,e.id),await U(e,t),{exitCode:0};if(e.command==="url"){let s=(e.url||"").trim();return s?(await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"url"}),await k(t.exporterDir,t.runtimeDir,"crawl",["--url",s],t.configPath,r,e.id),await U(e,t),{exitCode:0}):{exitCode:2,error:"Missing url for command 'url'"}}return e.command==="content-sync"?!e.ruleId||!e.coalesceKey?{exitCode:2,error:"Content-sync queue jobs require ruleId and coalesceKey."}:(await C(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync"}),await k(t.exporterDir,t.runtimeDir,"content-sync",["--job-id",e.id],t.configPath,r,e.id),await U(e,t),{exitCode:0}):{exitCode:2,error:`Unsupported command: ${e.command}`}}catch(i){return i instanceof $?{exitCode:130,error:"Job stop requested.",stopped:true,stopRequest:i.request,stoppedStep:i.step}:{exitCode:1,error:i instanceof Error?i.message:String(i)}}}function $e(e){return async function(n=process.argv.slice(2)){let i=It(n),r=h.join(i.runtimeDir,"export.lock"),a=h.join(i.runtimeDir,"last-run.json");await E(i.runtimeDir),await C(i,"starting",{message:"queue-runner starting"});try{await Wt(r);}catch(o){if((o&&typeof o=="object"&&"code"in o?String(o.code||""):"")!=="EEXIST")throw o;console.log("[queue-runner] lock active, skipping"),await C(i,"lock-active",{message:"lock active, skipped this cron tick"});return}try{await Vt(i);let o=await Ut(i,e),s=0;for(let c=0;c<i.maxJobs;c++){let u=await en(i,e);if(u==="none"||(s+=1,u==="stopped"))break}if(s===0)await E(i.runtimeDir),await C(i,"idle",{processedJobs:s,schedulerEnqueued:o,message:"no queued jobs"});else {await E(i.runtimeDir);let c=await w(a,null),u=String(c?.status||"").trim();await C(i,u==="success"?"job-success":u==="stopped"?"job-stopped":"job-failed",{processedJobs:s,schedulerEnqueued:o,lastJobId:c?.id,lastJobCommand:c?.command,lastJobStatus:c?.status,lastJobExitCode:c?.exitCode,lastJobError:c?.error,...u==="stopped"?{currentStep:c?.stoppedStep,stopRequestedAt:c?.stopRequestedAt,stopRequestedByLogin:c?.stopRequestedByLogin,stopRequestedMode:c?.stopMode,lastStoppedStep:c?.stoppedStep,message:c?.stopMode==="requeue"?`Job stopped during ${c?.stoppedStep||c?.command||"active step"} and requeued.`:`Job stopped during ${c?.stoppedStep||c?.command||"active step"} and left out of queue.`}:{}});}}catch(o){let s=o instanceof Error?o.message:String(o);throw await C(i,"error",{message:s}),await R(i.runtimeDir,{eventType:"queue-runner-error",status:"failed",actorSource:"queue-runner",message:"Unhandled queue-runner error.",details:{error:s}}),o}finally{await Nt(r);}}}async function Oe(e,t){if(t.command!=="content-sync"||!t.coalesceKey)return false;let n=se(e.runtimeDir),i=await Te(n,t.coalesceKey),r=await qe(n),a=r.rules[t.coalesceKey];return a&&(r.rules[t.coalesceKey]={...a,trailingWorkDetected:true,retryAttempt:0,nextRetryAt:null,lastError:null},await De(n,r)),i}async function Yt(e,t,n){let i=h.join(e.runtimeDir,"queue.json"),r=h.join(e.runtimeDir,"current-run.json");await F(e.runtimeDir,async()=>{let a=await w(i,[]),o=Array.isArray(a)?a.filter(u=>u?.id!==t.id):[],s=pe(t),c=Ht(t,n);c?s.resumeFromStep=c:delete s.resumeFromStep,await v(i,[s,...o]),await v(r,null);});}async function Zt(e,t,n){let i=Math.max(0,t.attempt??0)+1,r=Math.min(3600*1e3,6e4*2**(i-1)),a=Math.floor(r*.2*Math.random()),o=new Date(Date.now()+r+a).toISOString(),s={...pe(t),status:"retry-wait",attempt:i,nextAttemptAt:o,error:n};if(await F(e.runtimeDir,async()=>{let c=h.join(e.runtimeDir,"queue.json"),u=h.join(e.runtimeDir,"current-run.json"),d=(await w(c,[])).filter(m=>m.id!==t.id);await v(c,[s,...d]),await v(u,null);}),t.coalesceKey){let c=h.join(e.runtimeDir,"content-sync-state.json"),g=(await w(c,{})).rules??{};g[t.coalesceKey]={...g[t.coalesceKey]??{},ruleId:t.ruleId||"",coalesceKey:t.coalesceKey,retryAttempt:i,nextRetryAt:o,lastError:n,trailingWorkDetected:true},await v(c,{schemaVersion:1,updatedAt:new Date().toISOString(),rules:g});}return s}async function Xt(e,t){if(!t.coalesceKey||!t.ruleId||!(await w(h.join(e.runtimeDir,"content-sync-state.json"),null))?.rules?.[t.coalesceKey]?.trailingWorkDetected)return null;let i=null;await F(e.runtimeDir,async()=>{let a=h.join(e.runtimeDir,"queue.json"),o=await w(a,[]);de(o,{command:"content-sync",coalesceKey:t.coalesceKey,deploymentProfile:t.deploymentProfile})||(i={id:randomUUID(),command:"content-sync",ruleId:t.ruleId,coalesceKey:t.coalesceKey,deploymentProfile:t.deploymentProfile,enqueueSource:"scheduler",wpsuite:t.wpsuite,status:"queued",attempt:0,createdAt:new Date().toISOString(),createdBy:0},await v(a,[...o,i]));});let r=i;return r&&await R(e.runtimeDir,{eventType:"content-sync-trailing-job-created",status:"queued",actorSource:"queue-runner",jobId:r.id,command:r.command,message:"Content changes after the stable cutoff created one trailing job.",details:{predecessorJobId:t.id,ruleId:t.ruleId,coalesceKey:t.coalesceKey}}),r}async function en(e,t){let n=h.join(e.runtimeDir,"queue.json"),i=h.join(e.runtimeDir,"current-run.json"),r=h.join(e.runtimeDir,"last-run.json"),a=new Date().toISOString(),o=await F(e.runtimeDir,async()=>{let d=await w(n,[]);if(!Array.isArray(d)||d.length===0)return null;let m=Date.parse(String(d[0]?.nextAttemptAt||""));if(Number.isFinite(m)&&m>Date.now())return null;let f={...d[0],status:"running",startedAt:a};return delete f.nextAttemptAt,await v(n,d.slice(1)),await v(i,f),f});if(!o)return "none";await E(e.runtimeDir),await R(e.runtimeDir,{eventType:"job-run-started",status:"running",actorSource:"queue-runner",jobId:o.id,command:o.command,message:"Job execution started.",details:{createdAt:o.createdAt||"",startedAt:a,createdBy:o.createdBy??null,deploymentProfile:o.deploymentProfile||"",queuedWithTempAwsCreds:!!o.awsTempCreds}}),await C(e,"running",{currentJobId:o.id,currentJobCommand:o.command,currentStep:o.command});let s=await Gt(o,e,t),c=new Date().toISOString();if(s.stopped){let d=await _t(e,s.stoppedStep||o.command),m=s.stopRequest?.mode==="requeue"?"requeue":"stop",f={...o,status:"stopped",endedAt:c,exitCode:s.exitCode,...s.error?{error:s.error}:{},stopRequestedAt:s.stopRequest?.requestedAt||"",stopRequestedByUserId:typeof s.stopRequest?.requestedByUserId=="number"?s.stopRequest.requestedByUserId:null,stopRequestedByLogin:s.stopRequest?.requestedByLogin||"",stopMode:m,stoppedStep:d},b=false;m==="requeue"?await Yt(e,o,d):(await v(i,null),b=await Oe(e,o));try{let l=await _(f,e);f.logArchiveDir=l.archiveDir,f.logArchiveCreatedAt=l.archiveCreatedAt,f.logArchiveFileCount=l.archivedFiles.length;}catch(l){f.logArchiveError=l instanceof Error?l.message:String(l);}return await v(r,f),await W(e.runtimeDir,o.id),await E(e.runtimeDir),await R(e.runtimeDir,{eventType:"job-run-stopped",status:"stopped",actorSource:"queue-runner",jobId:o.id,command:o.command,message:m==="requeue"?"Job stop requested and requeued.":"Job stop requested and removed from active execution without requeue.",details:{startedAt:o.startedAt||"",endedAt:c,deploymentProfile:o.deploymentProfile||"",stopMode:m,stopRequestedAt:s.stopRequest?.requestedAt||"",stopRequestedByLogin:s.stopRequest?.requestedByLogin||"",stopRequestedByUserId:typeof s.stopRequest?.requestedByUserId=="number"?s.stopRequest.requestedByUserId:null,stoppedStep:d,logArchiveKey:f.logArchiveError||!f.logArchiveDir?"":h.basename(f.logArchiveDir),logArchiveDir:f.logArchiveDir||"",logArchiveCreatedAt:f.logArchiveCreatedAt||"",logArchiveFileCount:f.logArchiveFileCount??0,logArchiveError:f.logArchiveError||"",contentSyncAbandoned:b,journalCursorPreserved:b}}),"stopped"}if(o.command==="content-sync"&&s.exitCode!==0){if(/baseline (?:is missing or stale|required)|verified content-sync baseline|new baseline/i.test(s.error||"")){let b="The installed release no longer matches the verified content-sync baseline. Run a successful full or incremental publish to establish a new baseline.";o.ruleId&&o.coalesceKey&&await Ne(e,o.ruleId,o.coalesceKey,b);let l={...o,status:"failed",endedAt:c,exitCode:s.exitCode,error:b};await v(i,null),await E(e.runtimeDir),await Oe(e,o);try{let p=await _(l,e);l.logArchiveDir=p.archiveDir,l.logArchiveCreatedAt=p.archiveCreatedAt,l.logArchiveFileCount=p.archivedFiles.length;}catch(p){l.logArchiveError=p instanceof Error?p.message:String(p);}return await v(r,l),await W(e.runtimeDir,o.id),await R(e.runtimeDir,{eventType:"content-sync-baseline-required",status:"failed",actorSource:"queue-runner",jobId:o.id,command:o.command,message:b,details:{ruleId:o.ruleId||"",retryScheduled:false}}),"processed"}await R(e.runtimeDir,{eventType:"content-sync-failed",status:"failed",actorSource:"queue-runner",jobId:o.id,command:o.command,message:"Content-sync execution failed before cursor acknowledgement.",details:{attempt:o.attempt??0,error:s.error||"Content-sync execution failed."}});let m=await Zt(e,o,s.error||"Content-sync execution failed."),f={...o,status:"retry-wait",endedAt:c,exitCode:s.exitCode,error:m.error,attempt:m.attempt,nextAttemptAt:m.nextAttemptAt};try{let b=await _(f,e);f.logArchiveDir=b.archiveDir,f.logArchiveCreatedAt=b.archiveCreatedAt,f.logArchiveFileCount=b.archivedFiles.length;}catch(b){f.logArchiveError=b instanceof Error?b.message:String(b);}return await v(r,f),await W(e.runtimeDir,o.id),await R(e.runtimeDir,{eventType:"content-sync-retry-scheduled",status:"retry-wait",actorSource:"queue-runner",jobId:o.id,command:o.command,message:"Content-sync retry was scheduled with bounded backoff.",details:{attempt:m.attempt??0,nextAttemptAt:m.nextAttemptAt||"",error:m.error||""}}),"processed"}let u={...o,status:s.exitCode===0?"success":"failed",endedAt:c,exitCode:s.exitCode,...s.error?{error:s.error}:{}};await v(i,null),u.status==="success"&&u.command==="content-sync"&&await Xt(e,u),await W(e.runtimeDir,o.id);try{let d=await _(u,e);u.logArchiveDir=d.archiveDir,u.logArchiveCreatedAt=d.archiveCreatedAt,u.logArchiveFileCount=d.archivedFiles.length;}catch(d){u.logArchiveError=d instanceof Error?d.message:String(d);}await v(r,u);let g=o.startedAt&&u.endedAt?Math.max(0,Math.round((new Date(u.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)):void 0;return await R(e.runtimeDir,{eventType:"job-run-finished",status:u.status==="success"?"success":"failed",actorSource:"queue-runner",jobId:u.id,command:u.command,message:u.status==="success"?"Job execution finished successfully.":"Job execution finished with failure.",details:{startedAt:o.startedAt||"",endedAt:u.endedAt||"",durationSec:g,deploymentProfile:u.deploymentProfile||"",exitCode:u.exitCode??null,error:u.error||"",logArchiveKey:u.logArchiveError||!u.logArchiveDir?"":h.basename(u.logArchiveDir),logArchiveDir:u.logArchiveDir||"",logArchiveCreatedAt:u.logArchiveCreatedAt||"",logArchiveFileCount:u.logArchiveFileCount??0,logArchiveError:u.logArchiveError||""}}),"processed"}async function nn(e){if(!e)throw new Error("Missing remote WPSuite publisher state. Refresh the runtime config before running subscription-gated jobs.");if(e.subscriptionType!=="PROFESSIONAL"&&e.subscriptionType!=="AGENCY")throw new Error("This job requires an active WPSuite publisher subscription in the remote site configuration.")}var rn={allowSchedulerAutoEnqueue:true,enforceSubscriptionOnJobExecution:false,shouldEnforceSubscriptionOnJobExecution:e=>Le(e)||e.enqueueSource==="scheduler"||e.createdBy===0,assertActiveSubscriptionForIdentity:nn},Qe=$e(rn),on=Qe,Vn=Qe;process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href&&on().catch(e=>{console.error(e),process.exit(1);});export{Vn as default,on as main,Qe as runQueueRunner};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@smart-cloud/publisher-exporter",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.74",
|
|
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.",
|