@donotdev/core 0.0.30 → 0.0.32

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/next/index.js CHANGED
@@ -1,11 +1,10 @@
1
- var ra=Object.create;var Lr=Object.defineProperty;var sa=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var na=Object.getPrototypeOf,aa=Object.prototype.hasOwnProperty;var I=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var x=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var oa=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ia(e))!aa.call(t,i)&&i!==r&&Lr(t,i,{get:()=>e[i],enumerable:!(s=sa(e,i))||s.enumerable});return t};var la=(t,e,r)=>(r=t!=null?ra(na(t)):{},oa(e||!t||!t.__esModule?Lr(r,"default",{value:t,enumerable:!0}):r,t));var ie=x((Uu,os)=>{var as=t=>typeof t<"u"&&t!==null,Pa=t=>typeof t=="object",xa=t=>Object.prototype.toString.call(t)==="[object Object]",Ra=t=>typeof t=="function",$a=t=>typeof t=="boolean",Sa=t=>t instanceof Buffer,ka=t=>{if(as(t))switch(t.constructor){case Uint8Array:case Uint8ClampedArray:case Int8Array:case Uint16Array:case Int16Array:case Uint32Array:case Int32Array:case Float32Array:case Float64Array:return!0}return!1},Aa=t=>t instanceof ArrayBuffer,_a=t=>typeof t=="string"&&t.length>0,Na=t=>typeof t=="number"&&!Number.isNaN(t),Ia=t=>Number.isInteger(t),Fa=(t,e,r)=>t>=e&&t<=r,Ca=(t,e)=>e.includes(t),Da=(t,e,r)=>new Error(`Expected ${e} for ${t} but received ${r} of type ${typeof r}`),ja=(t,e)=>(e.message=t.message,e);os.exports={defined:as,object:Pa,plainObject:xa,fn:Ra,bool:$a,buffer:Sa,typedArray:ka,arrayBuffer:Aa,string:_a,number:Na,integer:Ia,inRange:Fa,inArray:Ca,invalidParameterError:Da,nativeError:ja}});var hs=x((qu,cs)=>{"use strict";var ls=()=>process.platform==="linux",yt=null,Ta=()=>{if(!yt)if(ls()&&process.report){let t=process.report.excludeNetwork;process.report.excludeNetwork=!0,yt=process.report.getReport(),process.report.excludeNetwork=t}else yt={};return yt};cs.exports={isLinux:ls,getReport:Ta}});var fs=x((Gu,us)=>{"use strict";var Ge=I("fs"),La="/usr/bin/ldd",Oa="/proc/self/exe",Et=2048,Ma=t=>{let e=Ge.openSync(t,"r"),r=Buffer.alloc(Et),s=Ge.readSync(e,r,0,Et,0);return Ge.close(e,()=>{}),r.subarray(0,s)},za=t=>new Promise((e,r)=>{Ge.open(t,"r",(s,i)=>{if(s)r(s);else{let n=Buffer.alloc(Et);Ge.read(i,n,0,Et,0,(a,o)=>{e(n.subarray(0,o)),Ge.close(i,()=>{})})}})});us.exports={LDD_PATH:La,SELF_PATH:Oa,readFileSync:Ma,readFile:za}});var gs=x((Hu,ds)=>{"use strict";var Ba=t=>{if(t.length<64||t.readUInt32BE(0)!==2135247942||t.readUInt8(4)!==2||t.readUInt8(5)!==1)return null;let e=t.readUInt32LE(32),r=t.readUInt16LE(54),s=t.readUInt16LE(56);for(let i=0;i<s;i++){let n=e+i*r;if(t.readUInt32LE(n)===3){let o=t.readUInt32LE(n+8),c=t.readUInt32LE(n+32);return t.subarray(o,o+c).toString().replace(/\0.*$/g,"")}}return null};ds.exports={interpreterPath:Ba}});var xt=x((Wu,Fs)=>{"use strict";var ms=I("child_process"),{isLinux:He,getReport:bs}=hs(),{LDD_PATH:Pt,SELF_PATH:vs,readFile:Zt,readFileSync:er}=fs(),{interpreterPath:ws}=gs(),ne,ae,oe,ys="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",$e="",Es=()=>$e||new Promise(t=>{ms.exec(ys,(e,r)=>{$e=e?" ":r,t($e)})}),Ps=()=>{if(!$e)try{$e=ms.execSync(ys,{encoding:"utf8"})}catch{$e=" "}return $e},ve="glibc",xs=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,je="musl",Ua=t=>t.includes("libc.musl-")||t.includes("ld-musl-"),Rs=()=>{let t=bs();return t.header&&t.header.glibcVersionRuntime?ve:Array.isArray(t.sharedObjects)&&t.sharedObjects.some(Ua)?je:null},$s=t=>{let[e,r]=t.split(/[\r\n]+/);return e&&e.includes(ve)?ve:r&&r.includes(je)?je:null},Ss=t=>{if(t){if(t.includes("/ld-musl-"))return je;if(t.includes("/ld-linux-"))return ve}return null},ks=t=>(t=t.toString(),t.includes("musl")?je:t.includes("GNU C Library")?ve:null),qa=async()=>{if(ae!==void 0)return ae;ae=null;try{let t=await Zt(Pt);ae=ks(t)}catch{}return ae},Ga=()=>{if(ae!==void 0)return ae;ae=null;try{let t=er(Pt);ae=ks(t)}catch{}return ae},Ha=async()=>{if(ne!==void 0)return ne;ne=null;try{let t=await Zt(vs),e=ws(t);ne=Ss(e)}catch{}return ne},Wa=()=>{if(ne!==void 0)return ne;ne=null;try{let t=er(vs),e=ws(t);ne=Ss(e)}catch{}return ne},As=async()=>{let t=null;if(He()&&(t=await Ha(),!t&&(t=await qa(),t||(t=Rs()),!t))){let e=await Es();t=$s(e)}return t},_s=()=>{let t=null;if(He()&&(t=Wa(),!t&&(t=Ga(),t||(t=Rs()),!t))){let e=Ps();t=$s(e)}return t},Va=async()=>He()&&await As()!==ve,Ja=()=>He()&&_s()!==ve,Xa=async()=>{if(oe!==void 0)return oe;oe=null;try{let e=(await Zt(Pt)).match(xs);e&&(oe=e[1])}catch{}return oe},Ya=()=>{if(oe!==void 0)return oe;oe=null;try{let e=er(Pt).match(xs);e&&(oe=e[1])}catch{}return oe},Ns=()=>{let t=bs();return t.header&&t.header.glibcVersionRuntime?t.header.glibcVersionRuntime:null},ps=t=>t.trim().split(/\s+/)[1],Is=t=>{let[e,r,s]=t.split(/[\r\n]+/);return e&&e.includes(ve)?ps(e):r&&s&&r.includes(je)?ps(s):null},Ka=async()=>{let t=null;if(He()&&(t=await Xa(),t||(t=Ns()),!t)){let e=await Es();t=Is(e)}return t},Qa=()=>{let t=null;if(He()&&(t=Ya(),t||(t=Ns()),!t)){let e=Ps();t=Is(e)}return t};Fs.exports={GLIBC:ve,MUSL:je,family:As,familySync:_s,isNonGlibcLinux:Va,isNonGlibcLinuxSync:Ja,version:Ka,versionSync:Qa}});var lt=x((Vu,Cs)=>{"use strict";var Za=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>{}:()=>{};Cs.exports=Za});var Rt=x((Ju,Ds)=>{"use strict";var eo="2.0.0",to=Number.MAX_SAFE_INTEGER||9007199254740991,ro=16,so=250,io=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ds.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ro,MAX_SAFE_BUILD_LENGTH:so,MAX_SAFE_INTEGER:to,RELEASE_TYPES:io,SEMVER_SPEC_VERSION:eo,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var ct=x((le,js)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:tr,MAX_SAFE_BUILD_LENGTH:no,MAX_LENGTH:ao}=Rt(),oo=lt();le=js.exports={};var lo=le.re=[],co=le.safeRe=[],v=le.src=[],ho=le.safeSrc=[],w=le.t={},uo=0,rr="[a-zA-Z0-9-]",fo=[["\\s",1],["\\d",ao],[rr,no]],go=t=>{for(let[e,r]of fo)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},P=(t,e,r)=>{let s=go(e),i=uo++;oo(t,i,e),w[t]=i,v[i]=e,ho[i]=s,lo[i]=new RegExp(e,r?"g":void 0),co[i]=new RegExp(s,r?"g":void 0)};P("NUMERICIDENTIFIER","0|[1-9]\\d*");P("NUMERICIDENTIFIERLOOSE","\\d+");P("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${rr}*`);P("MAINVERSION",`(${v[w.NUMERICIDENTIFIER]})\\.(${v[w.NUMERICIDENTIFIER]})\\.(${v[w.NUMERICIDENTIFIER]})`);P("MAINVERSIONLOOSE",`(${v[w.NUMERICIDENTIFIERLOOSE]})\\.(${v[w.NUMERICIDENTIFIERLOOSE]})\\.(${v[w.NUMERICIDENTIFIERLOOSE]})`);P("PRERELEASEIDENTIFIER",`(?:${v[w.NONNUMERICIDENTIFIER]}|${v[w.NUMERICIDENTIFIER]})`);P("PRERELEASEIDENTIFIERLOOSE",`(?:${v[w.NONNUMERICIDENTIFIER]}|${v[w.NUMERICIDENTIFIERLOOSE]})`);P("PRERELEASE",`(?:-(${v[w.PRERELEASEIDENTIFIER]}(?:\\.${v[w.PRERELEASEIDENTIFIER]})*))`);P("PRERELEASELOOSE",`(?:-?(${v[w.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${v[w.PRERELEASEIDENTIFIERLOOSE]})*))`);P("BUILDIDENTIFIER",`${rr}+`);P("BUILD",`(?:\\+(${v[w.BUILDIDENTIFIER]}(?:\\.${v[w.BUILDIDENTIFIER]})*))`);P("FULLPLAIN",`v?${v[w.MAINVERSION]}${v[w.PRERELEASE]}?${v[w.BUILD]}?`);P("FULL",`^${v[w.FULLPLAIN]}$`);P("LOOSEPLAIN",`[v=\\s]*${v[w.MAINVERSIONLOOSE]}${v[w.PRERELEASELOOSE]}?${v[w.BUILD]}?`);P("LOOSE",`^${v[w.LOOSEPLAIN]}$`);P("GTLT","((?:<|>)?=?)");P("XRANGEIDENTIFIERLOOSE",`${v[w.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);P("XRANGEIDENTIFIER",`${v[w.NUMERICIDENTIFIER]}|x|X|\\*`);P("XRANGEPLAIN",`[v=\\s]*(${v[w.XRANGEIDENTIFIER]})(?:\\.(${v[w.XRANGEIDENTIFIER]})(?:\\.(${v[w.XRANGEIDENTIFIER]})(?:${v[w.PRERELEASE]})?${v[w.BUILD]}?)?)?`);P("XRANGEPLAINLOOSE",`[v=\\s]*(${v[w.XRANGEIDENTIFIERLOOSE]})(?:\\.(${v[w.XRANGEIDENTIFIERLOOSE]})(?:\\.(${v[w.XRANGEIDENTIFIERLOOSE]})(?:${v[w.PRERELEASELOOSE]})?${v[w.BUILD]}?)?)?`);P("XRANGE",`^${v[w.GTLT]}\\s*${v[w.XRANGEPLAIN]}$`);P("XRANGELOOSE",`^${v[w.GTLT]}\\s*${v[w.XRANGEPLAINLOOSE]}$`);P("COERCEPLAIN",`(^|[^\\d])(\\d{1,${tr}})(?:\\.(\\d{1,${tr}}))?(?:\\.(\\d{1,${tr}}))?`);P("COERCE",`${v[w.COERCEPLAIN]}(?:$|[^\\d])`);P("COERCEFULL",v[w.COERCEPLAIN]+`(?:${v[w.PRERELEASE]})?(?:${v[w.BUILD]})?(?:$|[^\\d])`);P("COERCERTL",v[w.COERCE],!0);P("COERCERTLFULL",v[w.COERCEFULL],!0);P("LONETILDE","(?:~>?)");P("TILDETRIM",`(\\s*)${v[w.LONETILDE]}\\s+`,!0);le.tildeTrimReplace="$1~";P("TILDE",`^${v[w.LONETILDE]}${v[w.XRANGEPLAIN]}$`);P("TILDELOOSE",`^${v[w.LONETILDE]}${v[w.XRANGEPLAINLOOSE]}$`);P("LONECARET","(?:\\^)");P("CARETTRIM",`(\\s*)${v[w.LONECARET]}\\s+`,!0);le.caretTrimReplace="$1^";P("CARET",`^${v[w.LONECARET]}${v[w.XRANGEPLAIN]}$`);P("CARETLOOSE",`^${v[w.LONECARET]}${v[w.XRANGEPLAINLOOSE]}$`);P("COMPARATORLOOSE",`^${v[w.GTLT]}\\s*(${v[w.LOOSEPLAIN]})$|^$`);P("COMPARATOR",`^${v[w.GTLT]}\\s*(${v[w.FULLPLAIN]})$|^$`);P("COMPARATORTRIM",`(\\s*)${v[w.GTLT]}\\s*(${v[w.LOOSEPLAIN]}|${v[w.XRANGEPLAIN]})`,!0);le.comparatorTrimReplace="$1$2$3";P("HYPHENRANGE",`^\\s*(${v[w.XRANGEPLAIN]})\\s+-\\s+(${v[w.XRANGEPLAIN]})\\s*$`);P("HYPHENRANGELOOSE",`^\\s*(${v[w.XRANGEPLAINLOOSE]})\\s+-\\s+(${v[w.XRANGEPLAINLOOSE]})\\s*$`);P("STAR","(<|>)?=?\\s*\\*");P("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");P("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var $t=x((Xu,Ts)=>{"use strict";var po=Object.freeze({loose:!0}),mo=Object.freeze({}),bo=t=>t?typeof t!="object"?po:t:mo;Ts.exports=bo});var zs=x((Yu,Ms)=>{"use strict";var Ls=/^[0-9]+$/,Os=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let r=Ls.test(t),s=Ls.test(e);return r&&s&&(t=+t,e=+e),t===e?0:r&&!s?-1:s&&!r?1:t<e?-1:1},vo=(t,e)=>Os(e,t);Ms.exports={compareIdentifiers:Os,rcompareIdentifiers:vo}});var We=x((Ku,Us)=>{"use strict";var St=lt(),{MAX_LENGTH:Bs,MAX_SAFE_INTEGER:kt}=Rt(),{safeRe:At,t:_t}=ct(),wo=$t(),{compareIdentifiers:sr}=zs(),ir=class t{constructor(e,r){if(r=wo(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Bs)throw new TypeError(`version is longer than ${Bs} characters`);St("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let s=e.trim().match(r.loose?At[_t.LOOSE]:At[_t.FULL]);if(!s)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>kt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>kt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>kt||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let n=+i;if(n>=0&&n<kt)return n}return i}):this.prerelease=[],this.build=s[5]?s[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(St("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let s=this.prerelease[r],i=e.prerelease[r];if(St("prerelease compare",r,s,i),s===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(s===void 0)return-1;if(s===i)continue;return sr(s,i)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let s=this.build[r],i=e.build[r];if(St("build compare",r,s,i),s===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(s===void 0)return-1;if(s===i)continue;return sr(s,i)}while(++r)}inc(e,r,s){if(e.startsWith("pre")){if(!r&&s===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let i=`-${r}`.match(this.options.loose?At[_t.PRERELEASELOOSE]:At[_t.PRERELEASE]);if(!i||i[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,s);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,s);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,s),this.inc("pre",r,s);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,s),this.inc("pre",r,s);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(s)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(r===this.prerelease.join(".")&&s===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(r){let n=[r,i];s===!1&&(n=[r]),sr(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Us.exports=ir});var Hs=x((Qu,Gs)=>{"use strict";var qs=We(),yo=(t,e,r=!1)=>{if(t instanceof qs)return t;try{return new qs(t,e)}catch(s){if(!r)return null;throw s}};Gs.exports=yo});var Vs=x((Zu,Ws)=>{"use strict";var Eo=We(),Po=Hs(),{safeRe:Nt,t:It}=ct(),xo=(t,e)=>{if(t instanceof Eo)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?Nt[It.COERCEFULL]:Nt[It.COERCE]);else{let c=e.includePrerelease?Nt[It.COERCERTLFULL]:Nt[It.COERCERTL],h;for(;(h=c.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||h.index+h[0].length!==r.index+r[0].length)&&(r=h),c.lastIndex=h.index+h[1].length+h[2].length;c.lastIndex=-1}if(r===null)return null;let s=r[2],i=r[3]||"0",n=r[4]||"0",a=e.includePrerelease&&r[5]?`-${r[5]}`:"",o=e.includePrerelease&&r[6]?`+${r[6]}`:"";return Po(`${s}.${i}.${n}${a}${o}`,e)};Ws.exports=xo});var Te=x((ef,Xs)=>{"use strict";var Js=We(),Ro=(t,e,r)=>new Js(t,r).compare(new Js(e,r));Xs.exports=Ro});var nr=x((tf,Ys)=>{"use strict";var $o=Te(),So=(t,e,r)=>$o(t,e,r)>=0;Ys.exports=So});var Qs=x((rf,Ks)=>{"use strict";var ar=class{constructor(){this.max=1e3,this.map=new Map}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,r)}return this}};Ks.exports=ar});var ei=x((sf,Zs)=>{"use strict";var ko=Te(),Ao=(t,e,r)=>ko(t,e,r)===0;Zs.exports=Ao});var ri=x((nf,ti)=>{"use strict";var _o=Te(),No=(t,e,r)=>_o(t,e,r)!==0;ti.exports=No});var ii=x((af,si)=>{"use strict";var Io=Te(),Fo=(t,e,r)=>Io(t,e,r)>0;si.exports=Fo});var ai=x((of,ni)=>{"use strict";var Co=Te(),Do=(t,e,r)=>Co(t,e,r)<0;ni.exports=Do});var li=x((lf,oi)=>{"use strict";var jo=Te(),To=(t,e,r)=>jo(t,e,r)<=0;oi.exports=To});var hi=x((cf,ci)=>{"use strict";var Lo=ei(),Oo=ri(),Mo=ii(),zo=nr(),Bo=ai(),Uo=li(),qo=(t,e,r,s)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Lo(t,r,s);case"!=":return Oo(t,r,s);case">":return Mo(t,r,s);case">=":return zo(t,r,s);case"<":return Bo(t,r,s);case"<=":return Uo(t,r,s);default:throw new TypeError(`Invalid operator: ${e}`)}};ci.exports=qo});var bi=x((hf,mi)=>{"use strict";var ht=Symbol("SemVer ANY"),cr=class t{static get ANY(){return ht}constructor(e,r){if(r=ui(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),lr("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===ht?this.value="":this.value=this.operator+this.semver.version,lr("comp",this)}parse(e){let r=this.options.loose?fi[di.COMPARATORLOOSE]:fi[di.COMPARATOR],s=e.match(r);if(!s)throw new TypeError(`Invalid comparator: ${e}`);this.operator=s[1]!==void 0?s[1]:"",this.operator==="="&&(this.operator=""),s[2]?this.semver=new gi(s[2],this.options.loose):this.semver=ht}toString(){return this.value}test(e){if(lr("Comparator.test",e,this.options.loose),this.semver===ht||e===ht)return!0;if(typeof e=="string")try{e=new gi(e,this.options)}catch{return!1}return or(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new pi(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new pi(this.value,r).test(e.semver):(r=ui(r),r.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||or(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||or(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};mi.exports=cr;var ui=$t(),{safeRe:fi,t:di}=ct(),or=hi(),lr=lt(),gi=We(),pi=hr()});var hr=x((uf,Ei)=>{"use strict";var Go=/\s+/g,ur=class t{constructor(e,r){if(r=Wo(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof fr)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().replace(Go," "),this.set=this.raw.split("||").map(s=>this.parseRange(s.trim())).filter(s=>s.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let s=this.set[0];if(this.set=this.set.filter(i=>!wi(i[0])),this.set.length===0)this.set=[s];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&Zo(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let r=this.set[e];for(let s=0;s<r.length;s++)s>0&&(this.formatted+=" "),this.formatted+=r[s].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let s=((this.options.includePrerelease&&Ko)|(this.options.loose&&Qo))+":"+e,i=vi.get(s);if(i)return i;let n=this.options.loose,a=n?M[O.HYPHENRANGELOOSE]:M[O.HYPHENRANGE];e=e.replace(a,cl(this.options.includePrerelease)),N("hyphen replace",e),e=e.replace(M[O.COMPARATORTRIM],Jo),N("comparator trim",e),e=e.replace(M[O.TILDETRIM],Xo),N("tilde trim",e),e=e.replace(M[O.CARETTRIM],Yo),N("caret trim",e);let o=e.split(" ").map(g=>el(g,this.options)).join(" ").split(/\s+/).map(g=>ll(g,this.options));n&&(o=o.filter(g=>(N("loose invalid filter",g,this.options),!!g.match(M[O.COMPARATORLOOSE])))),N("range list",o);let c=new Map,h=o.map(g=>new fr(g,this.options));for(let g of h){if(wi(g))return[g];c.set(g.value,g)}c.size>1&&c.has("")&&c.delete("");let f=[...c.values()];return vi.set(s,f),f}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(s=>yi(s,r)&&e.set.some(i=>yi(i,r)&&s.every(n=>i.every(a=>n.intersects(a,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Vo(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(hl(this.set[r],e,this.options))return!0;return!1}};Ei.exports=ur;var Ho=Qs(),vi=new Ho,Wo=$t(),fr=bi(),N=lt(),Vo=We(),{safeRe:M,t:O,comparatorTrimReplace:Jo,tildeTrimReplace:Xo,caretTrimReplace:Yo}=ct(),{FLAG_INCLUDE_PRERELEASE:Ko,FLAG_LOOSE:Qo}=Rt(),wi=t=>t.value==="<0.0.0-0",Zo=t=>t.value==="",yi=(t,e)=>{let r=!0,s=t.slice(),i=s.pop();for(;r&&s.length;)r=s.every(n=>i.intersects(n,e)),i=s.pop();return r},el=(t,e)=>(t=t.replace(M[O.BUILD],""),N("comp",t,e),t=sl(t,e),N("caret",t),t=tl(t,e),N("tildes",t),t=nl(t,e),N("xrange",t),t=ol(t,e),N("stars",t),t),z=t=>!t||t.toLowerCase()==="x"||t==="*",tl=(t,e)=>t.trim().split(/\s+/).map(r=>rl(r,e)).join(" "),rl=(t,e)=>{let r=e.loose?M[O.TILDELOOSE]:M[O.TILDE];return t.replace(r,(s,i,n,a,o)=>{N("tilde",t,s,i,n,a,o);let c;return z(i)?c="":z(n)?c=`>=${i}.0.0 <${+i+1}.0.0-0`:z(a)?c=`>=${i}.${n}.0 <${i}.${+n+1}.0-0`:o?(N("replaceTilde pr",o),c=`>=${i}.${n}.${a}-${o} <${i}.${+n+1}.0-0`):c=`>=${i}.${n}.${a} <${i}.${+n+1}.0-0`,N("tilde return",c),c})},sl=(t,e)=>t.trim().split(/\s+/).map(r=>il(r,e)).join(" "),il=(t,e)=>{N("caret",t,e);let r=e.loose?M[O.CARETLOOSE]:M[O.CARET],s=e.includePrerelease?"-0":"";return t.replace(r,(i,n,a,o,c)=>{N("caret",t,i,n,a,o,c);let h;return z(n)?h="":z(a)?h=`>=${n}.0.0${s} <${+n+1}.0.0-0`:z(o)?n==="0"?h=`>=${n}.${a}.0${s} <${n}.${+a+1}.0-0`:h=`>=${n}.${a}.0${s} <${+n+1}.0.0-0`:c?(N("replaceCaret pr",c),n==="0"?a==="0"?h=`>=${n}.${a}.${o}-${c} <${n}.${a}.${+o+1}-0`:h=`>=${n}.${a}.${o}-${c} <${n}.${+a+1}.0-0`:h=`>=${n}.${a}.${o}-${c} <${+n+1}.0.0-0`):(N("no pr"),n==="0"?a==="0"?h=`>=${n}.${a}.${o}${s} <${n}.${a}.${+o+1}-0`:h=`>=${n}.${a}.${o}${s} <${n}.${+a+1}.0-0`:h=`>=${n}.${a}.${o} <${+n+1}.0.0-0`),N("caret return",h),h})},nl=(t,e)=>(N("replaceXRanges",t,e),t.split(/\s+/).map(r=>al(r,e)).join(" ")),al=(t,e)=>{t=t.trim();let r=e.loose?M[O.XRANGELOOSE]:M[O.XRANGE];return t.replace(r,(s,i,n,a,o,c)=>{N("xRange",t,s,i,n,a,o,c);let h=z(n),f=h||z(a),g=f||z(o),m=g;return i==="="&&m&&(i=""),c=e.includePrerelease?"-0":"",h?i===">"||i==="<"?s="<0.0.0-0":s="*":i&&m?(f&&(a=0),o=0,i===">"?(i=">=",f?(n=+n+1,a=0,o=0):(a=+a+1,o=0)):i==="<="&&(i="<",f?n=+n+1:a=+a+1),i==="<"&&(c="-0"),s=`${i+n}.${a}.${o}${c}`):f?s=`>=${n}.0.0${c} <${+n+1}.0.0-0`:g&&(s=`>=${n}.${a}.0${c} <${n}.${+a+1}.0-0`),N("xRange return",s),s})},ol=(t,e)=>(N("replaceStars",t,e),t.trim().replace(M[O.STAR],"")),ll=(t,e)=>(N("replaceGTE0",t,e),t.trim().replace(M[e.includePrerelease?O.GTE0PRE:O.GTE0],"")),cl=t=>(e,r,s,i,n,a,o,c,h,f,g,m)=>(z(s)?r="":z(i)?r=`>=${s}.0.0${t?"-0":""}`:z(n)?r=`>=${s}.${i}.0${t?"-0":""}`:a?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,z(h)?c="":z(f)?c=`<${+h+1}.0.0-0`:z(g)?c=`<${h}.${+f+1}.0-0`:m?c=`<=${h}.${f}.${g}-${m}`:t?c=`<${h}.${f}.${+g+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),hl=(t,e,r)=>{for(let s=0;s<t.length;s++)if(!t[s].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let s=0;s<t.length;s++)if(N(t[s].semver),t[s].semver!==fr.ANY&&t[s].semver.prerelease.length>0){let i=t[s].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var xi=x((ff,Pi)=>{"use strict";var ul=hr(),fl=(t,e,r)=>{try{e=new ul(e,r)}catch{return!1}return e.test(t)};Pi.exports=fl});var dr=x((df,dl)=>{dl.exports={name:"sharp",description:"High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",version:"0.34.5",author:"Lovell Fuller <npm@lovell.info>",homepage:"https://sharp.pixelplumbing.com",contributors:["Pierre Inglebert <pierre.inglebert@gmail.com>","Jonathan Ong <jonathanrichardong@gmail.com>","Chanon Sajjamanochai <chanon.s@gmail.com>","Juliano Julio <julianojulio@gmail.com>","Daniel Gasienica <daniel@gasienica.ch>","Julian Walker <julian@fiftythree.com>","Amit Pitaru <pitaru.amit@gmail.com>","Brandon Aaron <hello.brandon@aaron.sh>","Andreas Lind <andreas@one.com>","Maurus Cuelenaere <mcuelenaere@gmail.com>","Linus Unneb\xE4ck <linus@folkdatorn.se>","Victor Mateevitsi <mvictoras@gmail.com>","Alaric Holloway <alaric.holloway@gmail.com>","Bernhard K. Weisshuhn <bkw@codingforce.com>","Chris Riley <criley@primedia.com>","David Carley <dacarley@gmail.com>","John Tobin <john@limelightmobileinc.com>","Kenton Gray <kentongray@gmail.com>","Felix B\xFCnemann <Felix.Buenemann@gmail.com>","Samy Al Zahrani <samyalzahrany@gmail.com>","Chintan Thakkar <lemnisk8@gmail.com>","F. Orlando Galashan <frulo@gmx.de>","Kleis Auke Wolthuizen <info@kleisauke.nl>","Matt Hirsch <mhirsch@media.mit.edu>","Matthias Thoemmes <thoemmes@gmail.com>","Patrick Paskaris <patrick@paskaris.gr>","J\xE9r\xE9my Lal <kapouer@melix.org>","Rahul Nanwani <r.nanwani@gmail.com>","Alice Monday <alice0meta@gmail.com>","Kristo Jorgenson <kristo.jorgenson@gmail.com>","YvesBos <yves_bos@outlook.com>","Guy Maliar <guy@tailorbrands.com>","Nicolas Coden <nicolas@ncoden.fr>","Matt Parrish <matt.r.parrish@gmail.com>","Marcel Bretschneider <marcel.bretschneider@gmail.com>","Matthew McEachen <matthew+github@mceachen.org>","Jarda Kot\u011B\u0161ovec <jarda.kotesovec@gmail.com>","Kenric D'Souza <kenric.dsouza@gmail.com>","Oleh Aleinyk <oleg.aleynik@gmail.com>","Marcel Bretschneider <marcel.bretschneider@gmail.com>","Andrea Bianco <andrea.bianco@unibas.ch>","Rik Heywood <rik@rik.org>","Thomas Parisot <hi@oncletom.io>","Nathan Graves <nathanrgraves+github@gmail.com>","Tom Lokhorst <tom@lokhorst.eu>","Espen Hovlandsdal <espen@hovlandsdal.com>","Sylvain Dumont <sylvain.dumont35@gmail.com>","Alun Davies <alun.owain.davies@googlemail.com>","Aidan Hoolachan <ajhoolachan21@gmail.com>","Axel Eirola <axel.eirola@iki.fi>","Freezy <freezy@xbmc.org>","Daiz <taneli.vatanen@gmail.com>","Julian Aubourg <j@ubourg.net>","Keith Belovay <keith@picthrive.com>","Michael B. Klein <mbklein@gmail.com>","Jordan Prudhomme <jordan@raboland.fr>","Ilya Ovdin <iovdin@gmail.com>","Andargor <andargor@yahoo.com>","Paul Neave <paul.neave@gmail.com>","Brendan Kennedy <brenwken@gmail.com>","Brychan Bennett-Odlum <git@brychan.io>","Edward Silverton <e.silverton@gmail.com>","Roman Malieiev <aromaleev@gmail.com>","Tomas Szabo <tomas.szabo@deftomat.com>","Robert O'Rourke <robert@o-rourke.org>","Guillermo Alfonso Varela Chouci\xF1o <guillevch@gmail.com>","Christian Flintrup <chr@gigahost.dk>","Manan Jadhav <manan@motionden.com>","Leon Radley <leon@radley.se>","alza54 <alza54@thiocod.in>","Jacob Smith <jacob@frende.me>","Michael Nutt <michael@nutt.im>","Brad Parham <baparham@gmail.com>","Taneli Vatanen <taneli.vatanen@gmail.com>","Joris Dugu\xE9 <zaruike10@gmail.com>","Chris Banks <christopher.bradley.banks@gmail.com>","Ompal Singh <ompal.hitm09@gmail.com>","Brodan <christopher.hranj@gmail.com>","Ankur Parihar <ankur.github@gmail.com>","Brahim Ait elhaj <brahima@gmail.com>","Mart Jansink <m.jansink@gmail.com>","Lachlan Newman <lachnewman007@gmail.com>","Dennis Beatty <dennis@dcbeatty.com>","Ingvar Stepanyan <me@rreverser.com>","Don Denton <don@happycollision.com>"],scripts:{build:"node install/build.js",install:"node install/check.js || npm run build",clean:"rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*",test:"npm run lint && npm run test-unit",lint:"npm run lint-cpp && npm run lint-js && npm run lint-types","lint-cpp":"cpplint --quiet src/*.h src/*.cc","lint-js":"biome lint","lint-types":"tsd --files ./test/types/sharp.test-d.ts","test-leak":"./test/leak/leak.sh","test-unit":"node --experimental-test-coverage test/unit.mjs","package-from-local-build":"node npm/from-local-build.js","package-release-notes":"node npm/release-notes.js","docs-build":"node docs/build.mjs","docs-serve":"cd docs && npm start","docs-publish":"cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"},type:"commonjs",main:"lib/index.js",types:"lib/index.d.ts",files:["install","lib","src/*.{cc,h,gyp}"],repository:{type:"git",url:"git://github.com/lovell/sharp.git"},keywords:["jpeg","png","webp","avif","tiff","gif","svg","jp2","dzi","image","resize","thumbnail","crop","embed","libvips","vips"],dependencies:{"@img/colour":"^1.0.0","detect-libc":"^2.1.2",semver:"^7.7.3"},optionalDependencies:{"@img/sharp-darwin-arm64":"0.34.5","@img/sharp-darwin-x64":"0.34.5","@img/sharp-libvips-darwin-arm64":"1.2.4","@img/sharp-libvips-darwin-x64":"1.2.4","@img/sharp-libvips-linux-arm":"1.2.4","@img/sharp-libvips-linux-arm64":"1.2.4","@img/sharp-libvips-linux-ppc64":"1.2.4","@img/sharp-libvips-linux-riscv64":"1.2.4","@img/sharp-libvips-linux-s390x":"1.2.4","@img/sharp-libvips-linux-x64":"1.2.4","@img/sharp-libvips-linuxmusl-arm64":"1.2.4","@img/sharp-libvips-linuxmusl-x64":"1.2.4","@img/sharp-linux-arm":"0.34.5","@img/sharp-linux-arm64":"0.34.5","@img/sharp-linux-ppc64":"0.34.5","@img/sharp-linux-riscv64":"0.34.5","@img/sharp-linux-s390x":"0.34.5","@img/sharp-linux-x64":"0.34.5","@img/sharp-linuxmusl-arm64":"0.34.5","@img/sharp-linuxmusl-x64":"0.34.5","@img/sharp-wasm32":"0.34.5","@img/sharp-win32-arm64":"0.34.5","@img/sharp-win32-ia32":"0.34.5","@img/sharp-win32-x64":"0.34.5"},devDependencies:{"@biomejs/biome":"^2.3.4","@cpplint/cli":"^0.1.0","@emnapi/runtime":"^1.7.0","@img/sharp-libvips-dev":"1.2.4","@img/sharp-libvips-dev-wasm32":"1.2.4","@img/sharp-libvips-win32-arm64":"1.2.4","@img/sharp-libvips-win32-ia32":"1.2.4","@img/sharp-libvips-win32-x64":"1.2.4","@types/node":"*",emnapi:"^1.7.0","exif-reader":"^2.0.2","extract-zip":"^2.0.1",icc:"^3.0.0","jsdoc-to-markdown":"^9.1.3","node-addon-api":"^8.5.0","node-gyp":"^11.5.0","tar-fs":"^3.1.1",tsd:"^0.33.0"},license:"Apache-2.0",engines:{node:"^18.17.0 || ^20.3.0 || >=21.0.0"},config:{libvips:">=8.17.3"},funding:{url:"https://opencollective.com/libvips"}}});var pr=x((gf,Ci)=>{var{spawnSync:Ft}=I("node:child_process"),{createHash:gl}=I("node:crypto"),ki=Vs(),pl=nr(),ml=xi(),Ri=xt(),{config:bl,engines:$i,optionalDependencies:vl}=dr(),wl=process.env.npm_package_config_libvips||bl.libvips,Ai=ki(wl).version,yl=["darwin-arm64","darwin-x64","linux-arm","linux-arm64","linux-ppc64","linux-riscv64","linux-s390x","linux-x64","linuxmusl-arm64","linuxmusl-x64","win32-arm64","win32-ia32","win32-x64"],Ct={encoding:"utf8",shell:!0},El=t=>{t instanceof Error},_i=()=>Ri.isNonGlibcLinuxSync()?Ri.familySync():"",Pl=()=>`${process.platform}${_i()}-${process.arch}`,Ve=()=>{if(Ni())return"wasm32";let{npm_config_arch:t,npm_config_platform:e,npm_config_libc:r}=process.env,s=typeof r=="string"?r:_i();return`${e||process.platform}${s}-${t||process.arch}`},xl=()=>{try{return I(`@img/sharp-libvips-dev-${Ve()}/include`)}catch{try{return I("@img/sharp-libvips-dev/include")}catch{}}return""},Rl=()=>{try{return I("@img/sharp-libvips-dev/cplusplus")}catch{}return""},$l=()=>{try{return I(`@img/sharp-libvips-dev-${Ve()}/lib`)}catch{try{return I(`@img/sharp-libvips-${Ve()}/lib`)}catch{}}return""},Sl=()=>{if(process.release?.name==="node"&&process.versions&&!ml(process.versions.node,$i.node))return{found:process.versions.node,expected:$i.node}},Ni=()=>{let{CC:t}=process.env;return!!t?.endsWith("/emcc")},kl=()=>process.platform==="darwin"&&process.arch==="x64"?(Ft("sysctl sysctl.proc_translated",Ct).stdout||"").trim()==="sysctl.proc_translated: 1":!1,Si=t=>gl("sha512").update(t).digest("hex"),Al=()=>{try{let t=Si(`imgsharp-libvips-${Ve()}`),e=ki(vl[`@img/sharp-libvips-${Ve()}`],{includePrerelease:!0}).version;return Si(`${t}npm:${e}`).slice(0,10)}catch{}return""},_l=()=>Ft(`node-gyp rebuild --directory=src ${Ni()?"--nodedir=emscripten":""}`,{...Ct,stdio:"inherit"}).status,Ii=()=>process.platform!=="win32"?(Ft("pkg-config --modversion vips-cpp",{...Ct,env:{...process.env,PKG_CONFIG_PATH:Fi()}}).stdout||"").trim():"",Fi=()=>process.platform!=="win32"?[(Ft('which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',Ct).stdout||"").trim(),process.env.PKG_CONFIG_PATH,"/usr/local/lib/pkgconfig","/usr/lib/pkgconfig","/usr/local/libdata/pkgconfig","/usr/libdata/pkgconfig"].filter(Boolean).join(":"):"",gr=(t,e,r)=>(r&&r(`Detected ${e}, skipping search for globally-installed libvips`),t),Nl=t=>{if(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS)return gr(!1,"SHARP_IGNORE_GLOBAL_LIBVIPS",t);if(process.env.SHARP_FORCE_GLOBAL_LIBVIPS)return gr(!0,"SHARP_FORCE_GLOBAL_LIBVIPS",t);if(kl())return gr(!1,"Rosetta",t);let e=Ii();return!!e&&pl(e,Ai)};Ci.exports={minimumLibvipsVersion:Ai,prebuiltPlatforms:yl,buildPlatformArch:Ve,buildSharpLibvipsIncludeDir:xl,buildSharpLibvipsCPlusPlusDir:Rl,buildSharpLibvipsLibDir:$l,isUnsupportedNodeRuntime:Sl,runtimePlatformArch:Pl,log:El,yarnLocator:Al,spawnRebuild:_l,globalLibvipsVersion:Ii,pkgConfigPath:Fi,useGlobalLibvips:Nl}});var ft=x((mf,ji)=>{var{familySync:Il,versionSync:Fl}=xt(),{runtimePlatformArch:Cl,isUnsupportedNodeRuntime:Di,prebuiltPlatforms:Dl,minimumLibvipsVersion:jl}=pr(),Le=Cl(),Tl=[`../src/build/Release/sharp-${Le}.node`,"../src/build/Release/sharp-wasm32.node",`@img/sharp-${Le}/sharp.node`,"@img/sharp-wasm32/sharp.node"],mr,Je,ut=[];for(mr of Tl)try{Je=I(mr);break}catch(t){ut.push(t)}if(Je&&mr.startsWith("@img/sharp-linux-x64")&&!Je._isUsingX64V2()){let t=new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");t.code="Unsupported CPU",ut.push(t),Je=null}if(Je)ji.exports=Je;else{let[t,e,r]=["linux","darwin","win32"].map(n=>Le.startsWith(n)),s=[`Could not load the "sharp" module using the ${Le} runtime`];ut.forEach(n=>{n.code!=="MODULE_NOT_FOUND"&&s.push(`${n.code}: ${n.message}`)});let i=ut.map(n=>n.message).join(" ");if(s.push("Possible solutions:"),Di()){let{found:n,expected:a}=Di();s.push("- Please upgrade Node.js:",` Found ${n}`,` Requires ${a}`)}else if(Dl.includes(Le)){let[n,a]=Le.split("-"),o=n.endsWith("musl")?" --libc=musl":"";s.push("- Ensure optional dependencies can be installed:"," npm install --include=optional sharp","- Ensure your package manager supports multi-platform installation:"," See https://sharp.pixelplumbing.com/install#cross-platform","- Add platform-specific dependencies:",` npm install --os=${n.replace("musl","")}${o} --cpu=${a} sharp`)}else s.push(`- Manually install libvips >= ${jl}`,"- Add experimental WebAssembly-based dependencies:"," npm install --cpu=wasm32 sharp"," npm install @img/sharp-wasm32");if(t&&/(symbol not found|CXXABI_)/i.test(i))try{let{config:n}=I(`@img/sharp-libvips-${Le}/package`),a=`${Il()} ${Fl()}`,o=`${n.musl?"musl":"glibc"} ${n.musl||n.glibc}`;s.push("- Update your OS:",` Found ${a}`,` Requires ${o}`)}catch{}throw t&&/\/snap\/core[0-9]{2}/.test(i)&&s.push("- Remove the Node.js Snap, which does not support native modules"," snap remove node"),e&&/Incompatible library version/.test(i)&&s.push("- Update Homebrew:"," brew update && brew upgrade vips"),ut.some(n=>n.code==="ERR_DLOPEN_DISABLED")&&s.push("- Run Node.js without using the --no-addons flag"),r&&/The specified procedure could not be found/.test(i)&&s.push("- Using the canvas package on Windows?"," See https://sharp.pixelplumbing.com/install#canvas-and-windows","- Check for outdated versions of sharp in the dependency tree:"," npm ls sharp"),s.push("- Consult the installation documentation:"," See https://sharp.pixelplumbing.com/install"),new Error(s.join(`
2
- `))}});var Li=x((vf,Ti)=>{var Ll=I("node:util"),br=I("node:stream"),Ol=ie();ft();var Ml=Ll.debuglog("sharp"),zl=t=>{Oe.queue.emit("change",t)},Oe=function(t,e){if(arguments.length===1&&!Ol.defined(t))throw new Error("Invalid input");return this instanceof Oe?(br.Duplex.call(this),this.options={topOffsetPre:-1,leftOffsetPre:-1,widthPre:-1,heightPre:-1,topOffsetPost:-1,leftOffsetPost:-1,widthPost:-1,heightPost:-1,width:-1,height:-1,canvas:"crop",position:0,resizeBackground:[0,0,0,255],angle:0,rotationAngle:0,rotationBackground:[0,0,0,255],rotateBefore:!1,orientBefore:!1,flip:!1,flop:!1,extendTop:0,extendBottom:0,extendLeft:0,extendRight:0,extendBackground:[0,0,0,255],extendWith:"background",withoutEnlargement:!1,withoutReduction:!1,affineMatrix:[],affineBackground:[0,0,0,255],affineIdx:0,affineIdy:0,affineOdx:0,affineOdy:0,affineInterpolator:this.constructor.interpolators.bilinear,kernel:"lanczos3",fastShrinkOnLoad:!0,tint:[-1,0,0,0],flatten:!1,flattenBackground:[0,0,0],unflatten:!1,negate:!1,negateAlpha:!0,medianSize:0,blurSigma:0,precision:"integer",minAmpl:.2,sharpenSigma:0,sharpenM1:1,sharpenM2:2,sharpenX1:2,sharpenY2:10,sharpenY3:20,threshold:0,thresholdGrayscale:!0,trimBackground:[],trimThreshold:-1,trimLineArt:!1,dilateWidth:0,erodeWidth:0,gamma:0,gammaOut:0,greyscale:!1,normalise:!1,normaliseLower:1,normaliseUpper:99,claheWidth:0,claheHeight:0,claheMaxSlope:3,brightness:1,saturation:1,hue:0,lightness:0,booleanBufferIn:null,booleanFileIn:"",joinChannelIn:[],extractChannel:-1,removeAlpha:!1,ensureAlpha:-1,colourspace:"srgb",colourspacePipeline:"last",composite:[],fileOut:"",formatOut:"input",streamOut:!1,keepMetadata:0,withMetadataOrientation:-1,withMetadataDensity:0,withIccProfile:"",withExif:{},withExifMerge:!0,withXmp:"",resolveWithObject:!1,loop:-1,delay:[],jpegQuality:80,jpegProgressive:!1,jpegChromaSubsampling:"4:2:0",jpegTrellisQuantisation:!1,jpegOvershootDeringing:!1,jpegOptimiseScans:!1,jpegOptimiseCoding:!0,jpegQuantisationTable:0,pngProgressive:!1,pngCompressionLevel:6,pngAdaptiveFiltering:!1,pngPalette:!1,pngQuality:100,pngEffort:7,pngBitdepth:8,pngDither:1,jp2Quality:80,jp2TileHeight:512,jp2TileWidth:512,jp2Lossless:!1,jp2ChromaSubsampling:"4:4:4",webpQuality:80,webpAlphaQuality:100,webpLossless:!1,webpNearLossless:!1,webpSmartSubsample:!1,webpSmartDeblock:!1,webpPreset:"default",webpEffort:4,webpMinSize:!1,webpMixed:!1,gifBitdepth:8,gifEffort:7,gifDither:1,gifInterFrameMaxError:0,gifInterPaletteMaxError:3,gifKeepDuplicateFrames:!1,gifReuse:!0,gifProgressive:!1,tiffQuality:80,tiffCompression:"jpeg",tiffBigtiff:!1,tiffPredictor:"horizontal",tiffPyramid:!1,tiffMiniswhite:!1,tiffBitdepth:8,tiffTile:!1,tiffTileHeight:256,tiffTileWidth:256,tiffXres:1,tiffYres:1,tiffResolutionUnit:"inch",heifQuality:50,heifLossless:!1,heifCompression:"av1",heifEffort:4,heifChromaSubsampling:"4:4:4",heifBitdepth:8,jxlDistance:1,jxlDecodingTier:0,jxlEffort:7,jxlLossless:!1,rawDepth:"uchar",tileSize:256,tileOverlap:0,tileContainer:"fs",tileLayout:"dz",tileFormat:"last",tileDepth:"last",tileAngle:0,tileSkipBlanks:-1,tileBackground:[255,255,255,255],tileCentre:!1,tileId:"https://example.com/iiif",tileBasename:"",timeoutSeconds:0,linearA:[],linearB:[],pdfBackground:[255,255,255,255],debuglog:r=>{this.emit("warning",r),Ml(r)},queueListener:zl},this.options.input=this._createInputDescriptor(t,e,{allowStream:!0}),this):new Oe(t,e)};Object.setPrototypeOf(Oe.prototype,br.Duplex.prototype);Object.setPrototypeOf(Oe,br.Duplex);function Bl(){let t=this.constructor.call(),{debuglog:e,queueListener:r,...s}=this.options;return t.options=structuredClone(s),t.options.debuglog=e,t.options.queueListener=r,this._isStreamInput()&&this.on("finish",()=>{this._flattenBufferIn(),t.options.input.buffer=this.options.input.buffer,t.emit("finish")}),t}Object.assign(Oe.prototype,{clone:Bl});Ti.exports=Oe});var zi=x((wf,Mi)=>{var u=ie(),Se=ft(),Ul={left:"low",top:"low",low:"low",center:"centre",centre:"centre",right:"high",bottom:"high",high:"high"},ql=["failOn","limitInputPixels","unlimited","animated","autoOrient","density","ignoreIcc","page","pages","sequentialRead","jp2","openSlide","pdf","raw","svg","tiff","failOnError","openSlideLevel","pdfBackground","tiffSubifd"];function Oi(t){let e=ql.filter(r=>u.defined(t[r])).map(r=>[r,t[r]]);return e.length?Object.fromEntries(e):void 0}function Gl(t,e,r){let s={autoOrient:!1,failOn:"warning",limitInputPixels:268402689,ignoreIcc:!1,unlimited:!1,sequentialRead:!0};if(u.string(t))s.file=t;else if(u.buffer(t)){if(t.length===0)throw Error("Input Buffer is empty");s.buffer=t}else if(u.arrayBuffer(t)){if(t.byteLength===0)throw Error("Input bit Array is empty");s.buffer=Buffer.from(t,0,t.byteLength)}else if(u.typedArray(t)){if(t.length===0)throw Error("Input Bit Array is empty");s.buffer=Buffer.from(t.buffer,t.byteOffset,t.byteLength)}else if(u.plainObject(t)&&!u.defined(e))e=t,Oi(e)&&(s.buffer=[]);else if(!u.defined(t)&&!u.defined(e)&&u.object(r)&&r.allowStream)s.buffer=[];else if(Array.isArray(t))if(t.length>1)if(!this.options.joining)this.options.joining=!0,this.options.join=t.map(i=>this._createInputDescriptor(i));else throw new Error("Recursive join is unsupported");else throw new Error("Expected at least two images to join");else throw new Error(`Unsupported input '${t}' of type ${typeof t}${u.defined(e)?` when also providing options of type ${typeof e}`:""}`);if(u.object(e)){if(u.defined(e.failOnError))if(u.bool(e.failOnError))s.failOn=e.failOnError?"warning":"none";else throw u.invalidParameterError("failOnError","boolean",e.failOnError);if(u.defined(e.failOn))if(u.string(e.failOn)&&u.inArray(e.failOn,["none","truncated","error","warning"]))s.failOn=e.failOn;else throw u.invalidParameterError("failOn","one of: none, truncated, error, warning",e.failOn);if(u.defined(e.autoOrient))if(u.bool(e.autoOrient))s.autoOrient=e.autoOrient;else throw u.invalidParameterError("autoOrient","boolean",e.autoOrient);if(u.defined(e.density))if(u.inRange(e.density,1,1e5))s.density=e.density;else throw u.invalidParameterError("density","number between 1 and 100000",e.density);if(u.defined(e.ignoreIcc))if(u.bool(e.ignoreIcc))s.ignoreIcc=e.ignoreIcc;else throw u.invalidParameterError("ignoreIcc","boolean",e.ignoreIcc);if(u.defined(e.limitInputPixels))if(u.bool(e.limitInputPixels))s.limitInputPixels=e.limitInputPixels?16383**2:0;else if(u.integer(e.limitInputPixels)&&u.inRange(e.limitInputPixels,0,Number.MAX_SAFE_INTEGER))s.limitInputPixels=e.limitInputPixels;else throw u.invalidParameterError("limitInputPixels","positive integer",e.limitInputPixels);if(u.defined(e.unlimited))if(u.bool(e.unlimited))s.unlimited=e.unlimited;else throw u.invalidParameterError("unlimited","boolean",e.unlimited);if(u.defined(e.sequentialRead))if(u.bool(e.sequentialRead))s.sequentialRead=e.sequentialRead;else throw u.invalidParameterError("sequentialRead","boolean",e.sequentialRead);if(u.defined(e.raw)){if(u.object(e.raw)&&u.integer(e.raw.width)&&e.raw.width>0&&u.integer(e.raw.height)&&e.raw.height>0&&u.integer(e.raw.channels)&&u.inRange(e.raw.channels,1,4))switch(s.rawWidth=e.raw.width,s.rawHeight=e.raw.height,s.rawChannels=e.raw.channels,t.constructor){case Uint8Array:case Uint8ClampedArray:s.rawDepth="uchar";break;case Int8Array:s.rawDepth="char";break;case Uint16Array:s.rawDepth="ushort";break;case Int16Array:s.rawDepth="short";break;case Uint32Array:s.rawDepth="uint";break;case Int32Array:s.rawDepth="int";break;case Float32Array:s.rawDepth="float";break;case Float64Array:s.rawDepth="double";break;default:s.rawDepth="uchar";break}else throw new Error("Expected width, height and channels for raw pixel input");if(s.rawPremultiplied=!1,u.defined(e.raw.premultiplied))if(u.bool(e.raw.premultiplied))s.rawPremultiplied=e.raw.premultiplied;else throw u.invalidParameterError("raw.premultiplied","boolean",e.raw.premultiplied);if(s.rawPageHeight=0,u.defined(e.raw.pageHeight))if(u.integer(e.raw.pageHeight)&&e.raw.pageHeight>0&&e.raw.pageHeight<=e.raw.height){if(e.raw.height%e.raw.pageHeight!==0)throw new Error(`Expected raw.height ${e.raw.height} to be a multiple of raw.pageHeight ${e.raw.pageHeight}`);s.rawPageHeight=e.raw.pageHeight}else throw u.invalidParameterError("raw.pageHeight","positive integer",e.raw.pageHeight)}if(u.defined(e.animated))if(u.bool(e.animated))s.pages=e.animated?-1:1;else throw u.invalidParameterError("animated","boolean",e.animated);if(u.defined(e.pages))if(u.integer(e.pages)&&u.inRange(e.pages,-1,1e5))s.pages=e.pages;else throw u.invalidParameterError("pages","integer between -1 and 100000",e.pages);if(u.defined(e.page))if(u.integer(e.page)&&u.inRange(e.page,0,1e5))s.page=e.page;else throw u.invalidParameterError("page","integer between 0 and 100000",e.page);if(u.object(e.openSlide)&&u.defined(e.openSlide.level))if(u.integer(e.openSlide.level)&&u.inRange(e.openSlide.level,0,256))s.openSlideLevel=e.openSlide.level;else throw u.invalidParameterError("openSlide.level","integer between 0 and 256",e.openSlide.level);else if(u.defined(e.level))if(u.integer(e.level)&&u.inRange(e.level,0,256))s.openSlideLevel=e.level;else throw u.invalidParameterError("level","integer between 0 and 256",e.level);if(u.object(e.tiff)&&u.defined(e.tiff.subifd))if(u.integer(e.tiff.subifd)&&u.inRange(e.tiff.subifd,-1,1e5))s.tiffSubifd=e.tiff.subifd;else throw u.invalidParameterError("tiff.subifd","integer between -1 and 100000",e.tiff.subifd);else if(u.defined(e.subifd))if(u.integer(e.subifd)&&u.inRange(e.subifd,-1,1e5))s.tiffSubifd=e.subifd;else throw u.invalidParameterError("subifd","integer between -1 and 100000",e.subifd);if(u.object(e.svg)){if(u.defined(e.svg.stylesheet))if(u.string(e.svg.stylesheet))s.svgStylesheet=e.svg.stylesheet;else throw u.invalidParameterError("svg.stylesheet","string",e.svg.stylesheet);if(u.defined(e.svg.highBitdepth))if(u.bool(e.svg.highBitdepth))s.svgHighBitdepth=e.svg.highBitdepth;else throw u.invalidParameterError("svg.highBitdepth","boolean",e.svg.highBitdepth)}if(u.object(e.pdf)&&u.defined(e.pdf.background)?s.pdfBackground=this._getBackgroundColourOption(e.pdf.background):u.defined(e.pdfBackground)&&(s.pdfBackground=this._getBackgroundColourOption(e.pdfBackground)),u.object(e.jp2)&&u.defined(e.jp2.oneshot))if(u.bool(e.jp2.oneshot))s.jp2Oneshot=e.jp2.oneshot;else throw u.invalidParameterError("jp2.oneshot","boolean",e.jp2.oneshot);if(u.defined(e.create))if(u.object(e.create)&&u.integer(e.create.width)&&e.create.width>0&&u.integer(e.create.height)&&e.create.height>0&&u.integer(e.create.channels)){if(s.createWidth=e.create.width,s.createHeight=e.create.height,s.createChannels=e.create.channels,s.createPageHeight=0,u.defined(e.create.pageHeight))if(u.integer(e.create.pageHeight)&&e.create.pageHeight>0&&e.create.pageHeight<=e.create.height){if(e.create.height%e.create.pageHeight!==0)throw new Error(`Expected create.height ${e.create.height} to be a multiple of create.pageHeight ${e.create.pageHeight}`);s.createPageHeight=e.create.pageHeight}else throw u.invalidParameterError("create.pageHeight","positive integer",e.create.pageHeight);if(u.defined(e.create.noise)){if(!u.object(e.create.noise))throw new Error("Expected noise to be an object");if(e.create.noise.type!=="gaussian")throw new Error("Only gaussian noise is supported at the moment");if(s.createNoiseType=e.create.noise.type,!u.inRange(e.create.channels,1,4))throw u.invalidParameterError("create.channels","number between 1 and 4",e.create.channels);if(s.createNoiseMean=128,u.defined(e.create.noise.mean))if(u.number(e.create.noise.mean)&&u.inRange(e.create.noise.mean,0,1e4))s.createNoiseMean=e.create.noise.mean;else throw u.invalidParameterError("create.noise.mean","number between 0 and 10000",e.create.noise.mean);if(s.createNoiseSigma=30,u.defined(e.create.noise.sigma))if(u.number(e.create.noise.sigma)&&u.inRange(e.create.noise.sigma,0,1e4))s.createNoiseSigma=e.create.noise.sigma;else throw u.invalidParameterError("create.noise.sigma","number between 0 and 10000",e.create.noise.sigma)}else if(u.defined(e.create.background)){if(!u.inRange(e.create.channels,3,4))throw u.invalidParameterError("create.channels","number between 3 and 4",e.create.channels);s.createBackground=this._getBackgroundColourOption(e.create.background)}else throw new Error("Expected valid noise or background to create a new input image");delete s.buffer}else throw new Error("Expected valid width, height and channels to create a new input image");if(u.defined(e.text))if(u.object(e.text)&&u.string(e.text.text)){if(s.textValue=e.text.text,u.defined(e.text.height)&&u.defined(e.text.dpi))throw new Error("Expected only one of dpi or height");if(u.defined(e.text.font))if(u.string(e.text.font))s.textFont=e.text.font;else throw u.invalidParameterError("text.font","string",e.text.font);if(u.defined(e.text.fontfile))if(u.string(e.text.fontfile))s.textFontfile=e.text.fontfile;else throw u.invalidParameterError("text.fontfile","string",e.text.fontfile);if(u.defined(e.text.width))if(u.integer(e.text.width)&&e.text.width>0)s.textWidth=e.text.width;else throw u.invalidParameterError("text.width","positive integer",e.text.width);if(u.defined(e.text.height))if(u.integer(e.text.height)&&e.text.height>0)s.textHeight=e.text.height;else throw u.invalidParameterError("text.height","positive integer",e.text.height);if(u.defined(e.text.align))if(u.string(e.text.align)&&u.string(this.constructor.align[e.text.align]))s.textAlign=this.constructor.align[e.text.align];else throw u.invalidParameterError("text.align","valid alignment",e.text.align);if(u.defined(e.text.justify))if(u.bool(e.text.justify))s.textJustify=e.text.justify;else throw u.invalidParameterError("text.justify","boolean",e.text.justify);if(u.defined(e.text.dpi))if(u.integer(e.text.dpi)&&u.inRange(e.text.dpi,1,1e6))s.textDpi=e.text.dpi;else throw u.invalidParameterError("text.dpi","integer between 1 and 1000000",e.text.dpi);if(u.defined(e.text.rgba))if(u.bool(e.text.rgba))s.textRgba=e.text.rgba;else throw u.invalidParameterError("text.rgba","bool",e.text.rgba);if(u.defined(e.text.spacing))if(u.integer(e.text.spacing)&&u.inRange(e.text.spacing,-1e6,1e6))s.textSpacing=e.text.spacing;else throw u.invalidParameterError("text.spacing","integer between -1000000 and 1000000",e.text.spacing);if(u.defined(e.text.wrap))if(u.string(e.text.wrap)&&u.inArray(e.text.wrap,["word","char","word-char","none"]))s.textWrap=e.text.wrap;else throw u.invalidParameterError("text.wrap","one of: word, char, word-char, none",e.text.wrap);delete s.buffer}else throw new Error("Expected a valid string to create an image with text.");if(u.defined(e.join))if(u.defined(this.options.join)){if(u.defined(e.join.animated))if(u.bool(e.join.animated))s.joinAnimated=e.join.animated;else throw u.invalidParameterError("join.animated","boolean",e.join.animated);if(u.defined(e.join.across))if(u.integer(e.join.across)&&u.inRange(e.join.across,1,1e6))s.joinAcross=e.join.across;else throw u.invalidParameterError("join.across","integer between 1 and 100000",e.join.across);if(u.defined(e.join.shim))if(u.integer(e.join.shim)&&u.inRange(e.join.shim,0,1e6))s.joinShim=e.join.shim;else throw u.invalidParameterError("join.shim","integer between 0 and 100000",e.join.shim);if(u.defined(e.join.background)&&(s.joinBackground=this._getBackgroundColourOption(e.join.background)),u.defined(e.join.halign))if(u.string(e.join.halign)&&u.string(this.constructor.align[e.join.halign]))s.joinHalign=this.constructor.align[e.join.halign];else throw u.invalidParameterError("join.halign","valid alignment",e.join.halign);if(u.defined(e.join.valign))if(u.string(e.join.valign)&&u.string(this.constructor.align[e.join.valign]))s.joinValign=this.constructor.align[e.join.valign];else throw u.invalidParameterError("join.valign","valid alignment",e.join.valign)}else throw new Error("Expected input to be an array of images to join")}else if(u.defined(e))throw new Error(`Invalid input options ${e}`);return s}function Hl(t,e,r){Array.isArray(this.options.input.buffer)?u.buffer(t)?(this.options.input.buffer.length===0&&this.on("finish",()=>{this.streamInFinished=!0}),this.options.input.buffer.push(t),r()):r(new Error("Non-Buffer data on Writable Stream")):r(new Error("Unexpected data on Writable Stream"))}function Wl(){this._isStreamInput()&&(this.options.input.buffer=Buffer.concat(this.options.input.buffer))}function Vl(){return Array.isArray(this.options.input.buffer)}function Jl(t){let e=Error();return u.fn(t)?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),Se.metadata(this.options,(r,s)=>{r?t(u.nativeError(r,e)):t(null,s)})}):Se.metadata(this.options,(r,s)=>{r?t(u.nativeError(r,e)):t(null,s)}),this):this._isStreamInput()?new Promise((r,s)=>{let i=()=>{this._flattenBufferIn(),Se.metadata(this.options,(n,a)=>{n?s(u.nativeError(n,e)):r(a)})};this.writableFinished?i():this.once("finish",i)}):new Promise((r,s)=>{Se.metadata(this.options,(i,n)=>{i?s(u.nativeError(i,e)):r(n)})})}function Xl(t){let e=Error();return u.fn(t)?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),Se.stats(this.options,(r,s)=>{r?t(u.nativeError(r,e)):t(null,s)})}):Se.stats(this.options,(r,s)=>{r?t(u.nativeError(r,e)):t(null,s)}),this):this._isStreamInput()?new Promise((r,s)=>{this.on("finish",function(){this._flattenBufferIn(),Se.stats(this.options,(i,n)=>{i?s(u.nativeError(i,e)):r(n)})})}):new Promise((r,s)=>{Se.stats(this.options,(i,n)=>{i?s(u.nativeError(i,e)):r(n)})})}Mi.exports=t=>{Object.assign(t.prototype,{_inputOptionsFromObject:Oi,_createInputDescriptor:Gl,_write:Hl,_flattenBufferIn:Wl,_isStreamInput:Vl,metadata:Jl,stats:Xl}),t.align=Ul}});var Wi=x((yf,Hi)=>{var E=ie(),Ui={center:0,centre:0,north:1,east:2,south:3,west:4,northeast:5,southeast:6,southwest:7,northwest:8},qi={top:1,right:2,bottom:3,left:4,"right top":5,"right bottom":6,"left bottom":7,"left top":8},Bi={background:"background",copy:"copy",repeat:"repeat",mirror:"mirror"},Gi={entropy:16,attention:17},vr={nearest:"nearest",linear:"linear",cubic:"cubic",mitchell:"mitchell",lanczos2:"lanczos2",lanczos3:"lanczos3",mks2013:"mks2013",mks2021:"mks2021"},Yl={contain:"contain",cover:"cover",fill:"fill",inside:"inside",outside:"outside"},Kl={contain:"embed",cover:"crop",fill:"ignore_aspect",inside:"max",outside:"min"};function wr(t){return t.angle%360!==0||t.rotationAngle!==0}function Dt(t){return t.width!==-1||t.height!==-1}function Ql(t,e,r){if(Dt(this.options)&&this.options.debuglog("ignoring previous resize options"),this.options.widthPost!==-1&&this.options.debuglog("operation order will be: extract, resize, extract"),E.defined(t))if(E.object(t)&&!E.defined(r))r=t;else if(E.integer(t)&&t>0)this.options.width=t;else throw E.invalidParameterError("width","positive integer",t);else this.options.width=-1;if(E.defined(e))if(E.integer(e)&&e>0)this.options.height=e;else throw E.invalidParameterError("height","positive integer",e);else this.options.height=-1;if(E.object(r)){if(E.defined(r.width))if(E.integer(r.width)&&r.width>0)this.options.width=r.width;else throw E.invalidParameterError("width","positive integer",r.width);if(E.defined(r.height))if(E.integer(r.height)&&r.height>0)this.options.height=r.height;else throw E.invalidParameterError("height","positive integer",r.height);if(E.defined(r.fit)){let s=Kl[r.fit];if(E.string(s))this.options.canvas=s;else throw E.invalidParameterError("fit","valid fit",r.fit)}if(E.defined(r.position)){let s=E.integer(r.position)?r.position:Gi[r.position]||qi[r.position]||Ui[r.position];if(E.integer(s)&&(E.inRange(s,0,8)||E.inRange(s,16,17)))this.options.position=s;else throw E.invalidParameterError("position","valid position/gravity/strategy",r.position)}if(this._setBackgroundColourOption("resizeBackground",r.background),E.defined(r.kernel))if(E.string(vr[r.kernel]))this.options.kernel=vr[r.kernel];else throw E.invalidParameterError("kernel","valid kernel name",r.kernel);E.defined(r.withoutEnlargement)&&this._setBooleanOption("withoutEnlargement",r.withoutEnlargement),E.defined(r.withoutReduction)&&this._setBooleanOption("withoutReduction",r.withoutReduction),E.defined(r.fastShrinkOnLoad)&&this._setBooleanOption("fastShrinkOnLoad",r.fastShrinkOnLoad)}return wr(this.options)&&Dt(this.options)&&(this.options.rotateBefore=!0),this}function Zl(t){if(E.integer(t)&&t>0)this.options.extendTop=t,this.options.extendBottom=t,this.options.extendLeft=t,this.options.extendRight=t;else if(E.object(t)){if(E.defined(t.top))if(E.integer(t.top)&&t.top>=0)this.options.extendTop=t.top;else throw E.invalidParameterError("top","positive integer",t.top);if(E.defined(t.bottom))if(E.integer(t.bottom)&&t.bottom>=0)this.options.extendBottom=t.bottom;else throw E.invalidParameterError("bottom","positive integer",t.bottom);if(E.defined(t.left))if(E.integer(t.left)&&t.left>=0)this.options.extendLeft=t.left;else throw E.invalidParameterError("left","positive integer",t.left);if(E.defined(t.right))if(E.integer(t.right)&&t.right>=0)this.options.extendRight=t.right;else throw E.invalidParameterError("right","positive integer",t.right);if(this._setBackgroundColourOption("extendBackground",t.background),E.defined(t.extendWith))if(E.string(Bi[t.extendWith]))this.options.extendWith=Bi[t.extendWith];else throw E.invalidParameterError("extendWith","one of: background, copy, repeat, mirror",t.extendWith)}else throw E.invalidParameterError("extend","integer or object",t);return this}function ec(t){let e=Dt(this.options)||this.options.widthPre!==-1?"Post":"Pre";return this.options[`width${e}`]!==-1&&this.options.debuglog("ignoring previous extract options"),["left","top","width","height"].forEach(function(r){let s=t[r];if(E.integer(s)&&s>=0)this.options[r+(r==="left"||r==="top"?"Offset":"")+e]=s;else throw E.invalidParameterError(r,"integer",s)},this),wr(this.options)&&!Dt(this.options)&&(this.options.widthPre===-1||this.options.widthPost===-1)&&(this.options.rotateBefore=!0),this.options.input.autoOrient&&(this.options.orientBefore=!0),this}function tc(t){if(this.options.trimThreshold=10,E.defined(t))if(E.object(t)){if(E.defined(t.background)&&this._setBackgroundColourOption("trimBackground",t.background),E.defined(t.threshold))if(E.number(t.threshold)&&t.threshold>=0)this.options.trimThreshold=t.threshold;else throw E.invalidParameterError("threshold","positive number",t.threshold);E.defined(t.lineArt)&&this._setBooleanOption("trimLineArt",t.lineArt)}else throw E.invalidParameterError("trim","object",t);return wr(this.options)&&(this.options.rotateBefore=!0),this}Hi.exports=t=>{Object.assign(t.prototype,{resize:Ql,extend:Zl,extract:ec,trim:tc}),t.gravity=Ui,t.strategy=Gi,t.kernel=vr,t.fit=Yl,t.position=qi}});var Ji=x((Ef,Vi)=>{var _=ie(),yr={clear:"clear",source:"source",over:"over",in:"in",out:"out",atop:"atop",dest:"dest","dest-over":"dest-over","dest-in":"dest-in","dest-out":"dest-out","dest-atop":"dest-atop",xor:"xor",add:"add",saturate:"saturate",multiply:"multiply",screen:"screen",overlay:"overlay",darken:"darken",lighten:"lighten","colour-dodge":"colour-dodge","color-dodge":"colour-dodge","colour-burn":"colour-burn","color-burn":"colour-burn","hard-light":"hard-light","soft-light":"soft-light",difference:"difference",exclusion:"exclusion"};function rc(t){if(!Array.isArray(t))throw _.invalidParameterError("images to composite","array",t);return this.options.composite=t.map(e=>{if(!_.object(e))throw _.invalidParameterError("image to composite","object",e);let r=this._inputOptionsFromObject(e),s={input:this._createInputDescriptor(e.input,r,{allowStream:!1}),blend:"over",tile:!1,left:0,top:0,hasOffset:!1,gravity:0,premultiplied:!1};if(_.defined(e.blend))if(_.string(yr[e.blend]))s.blend=yr[e.blend];else throw _.invalidParameterError("blend","valid blend name",e.blend);if(_.defined(e.tile))if(_.bool(e.tile))s.tile=e.tile;else throw _.invalidParameterError("tile","boolean",e.tile);if(_.defined(e.left))if(_.integer(e.left))s.left=e.left;else throw _.invalidParameterError("left","integer",e.left);if(_.defined(e.top))if(_.integer(e.top))s.top=e.top;else throw _.invalidParameterError("top","integer",e.top);if(_.defined(e.top)!==_.defined(e.left))throw new Error("Expected both left and top to be set");if(s.hasOffset=_.integer(e.top)&&_.integer(e.left),_.defined(e.gravity))if(_.integer(e.gravity)&&_.inRange(e.gravity,0,8))s.gravity=e.gravity;else if(_.string(e.gravity)&&_.integer(this.constructor.gravity[e.gravity]))s.gravity=this.constructor.gravity[e.gravity];else throw _.invalidParameterError("gravity","valid gravity",e.gravity);if(_.defined(e.premultiplied))if(_.bool(e.premultiplied))s.premultiplied=e.premultiplied;else throw _.invalidParameterError("premultiplied","boolean",e.premultiplied);return s}),this}Vi.exports=t=>{t.prototype.composite=rc,t.blend=yr}});var Zi=x((Pf,Qi)=>{var d=ie(),Xi={integer:"integer",float:"float",approximate:"approximate"};function sc(t,e){if(!d.defined(t))return this.autoOrient();if((this.options.angle||this.options.rotationAngle)&&(this.options.debuglog("ignoring previous rotate options"),this.options.angle=0,this.options.rotationAngle=0),d.integer(t)&&!(t%90))this.options.angle=t;else if(d.number(t))this.options.rotationAngle=t,d.object(e)&&e.background&&this._setBackgroundColourOption("rotationBackground",e.background);else throw d.invalidParameterError("angle","numeric",t);return this}function ic(){return this.options.input.autoOrient=!0,this}function nc(t){return this.options.flip=d.bool(t)?t:!0,this}function ac(t){return this.options.flop=d.bool(t)?t:!0,this}function oc(t,e){let r=[].concat(...t);if(r.length===4&&r.every(d.number))this.options.affineMatrix=r;else throw d.invalidParameterError("matrix","1x4 or 2x2 array",t);if(d.defined(e))if(d.object(e)){if(this._setBackgroundColourOption("affineBackground",e.background),d.defined(e.idx))if(d.number(e.idx))this.options.affineIdx=e.idx;else throw d.invalidParameterError("options.idx","number",e.idx);if(d.defined(e.idy))if(d.number(e.idy))this.options.affineIdy=e.idy;else throw d.invalidParameterError("options.idy","number",e.idy);if(d.defined(e.odx))if(d.number(e.odx))this.options.affineOdx=e.odx;else throw d.invalidParameterError("options.odx","number",e.odx);if(d.defined(e.ody))if(d.number(e.ody))this.options.affineOdy=e.ody;else throw d.invalidParameterError("options.ody","number",e.ody);if(d.defined(e.interpolator))if(d.inArray(e.interpolator,Object.values(this.constructor.interpolators)))this.options.affineInterpolator=e.interpolator;else throw d.invalidParameterError("options.interpolator","valid interpolator name",e.interpolator)}else throw d.invalidParameterError("options","object",e);return this}function lc(t,e,r){if(!d.defined(t))this.options.sharpenSigma=-1;else if(d.bool(t))this.options.sharpenSigma=t?-1:0;else if(d.number(t)&&d.inRange(t,.01,1e4)){if(this.options.sharpenSigma=t,d.defined(e))if(d.number(e)&&d.inRange(e,0,1e4))this.options.sharpenM1=e;else throw d.invalidParameterError("flat","number between 0 and 10000",e);if(d.defined(r))if(d.number(r)&&d.inRange(r,0,1e4))this.options.sharpenM2=r;else throw d.invalidParameterError("jagged","number between 0 and 10000",r)}else if(d.plainObject(t)){if(d.number(t.sigma)&&d.inRange(t.sigma,1e-6,10))this.options.sharpenSigma=t.sigma;else throw d.invalidParameterError("options.sigma","number between 0.000001 and 10",t.sigma);if(d.defined(t.m1))if(d.number(t.m1)&&d.inRange(t.m1,0,1e6))this.options.sharpenM1=t.m1;else throw d.invalidParameterError("options.m1","number between 0 and 1000000",t.m1);if(d.defined(t.m2))if(d.number(t.m2)&&d.inRange(t.m2,0,1e6))this.options.sharpenM2=t.m2;else throw d.invalidParameterError("options.m2","number between 0 and 1000000",t.m2);if(d.defined(t.x1))if(d.number(t.x1)&&d.inRange(t.x1,0,1e6))this.options.sharpenX1=t.x1;else throw d.invalidParameterError("options.x1","number between 0 and 1000000",t.x1);if(d.defined(t.y2))if(d.number(t.y2)&&d.inRange(t.y2,0,1e6))this.options.sharpenY2=t.y2;else throw d.invalidParameterError("options.y2","number between 0 and 1000000",t.y2);if(d.defined(t.y3))if(d.number(t.y3)&&d.inRange(t.y3,0,1e6))this.options.sharpenY3=t.y3;else throw d.invalidParameterError("options.y3","number between 0 and 1000000",t.y3)}else throw d.invalidParameterError("sigma","number between 0.01 and 10000",t);return this}function cc(t){if(!d.defined(t))this.options.medianSize=3;else if(d.integer(t)&&d.inRange(t,1,1e3))this.options.medianSize=t;else throw d.invalidParameterError("size","integer between 1 and 1000",t);return this}function hc(t){let e;if(d.number(t))e=t;else if(d.plainObject(t)){if(!d.number(t.sigma))throw d.invalidParameterError("options.sigma","number between 0.3 and 1000",e);if(e=t.sigma,"precision"in t)if(d.string(Xi[t.precision]))this.options.precision=Xi[t.precision];else throw d.invalidParameterError("precision","one of: integer, float, approximate",t.precision);if("minAmplitude"in t)if(d.number(t.minAmplitude)&&d.inRange(t.minAmplitude,.001,1))this.options.minAmpl=t.minAmplitude;else throw d.invalidParameterError("minAmplitude","number between 0.001 and 1",t.minAmplitude)}if(!d.defined(t))this.options.blurSigma=-1;else if(d.bool(t))this.options.blurSigma=t?-1:0;else if(d.number(e)&&d.inRange(e,.3,1e3))this.options.blurSigma=e;else throw d.invalidParameterError("sigma","number between 0.3 and 1000",e);return this}function Yi(t){if(!d.defined(t))this.options.dilateWidth=1;else if(d.integer(t)&&t>0)this.options.dilateWidth=t;else throw d.invalidParameterError("dilate","positive integer",Yi);return this}function Ki(t){if(!d.defined(t))this.options.erodeWidth=1;else if(d.integer(t)&&t>0)this.options.erodeWidth=t;else throw d.invalidParameterError("erode","positive integer",Ki);return this}function uc(t){return this.options.flatten=d.bool(t)?t:!0,d.object(t)&&this._setBackgroundColourOption("flattenBackground",t.background),this}function fc(){return this.options.unflatten=!0,this}function dc(t,e){if(!d.defined(t))this.options.gamma=2.2;else if(d.number(t)&&d.inRange(t,1,3))this.options.gamma=t;else throw d.invalidParameterError("gamma","number between 1.0 and 3.0",t);if(!d.defined(e))this.options.gammaOut=this.options.gamma;else if(d.number(e)&&d.inRange(e,1,3))this.options.gammaOut=e;else throw d.invalidParameterError("gammaOut","number between 1.0 and 3.0",e);return this}function gc(t){if(this.options.negate=d.bool(t)?t:!0,d.plainObject(t)&&"alpha"in t)if(d.bool(t.alpha))this.options.negateAlpha=t.alpha;else throw d.invalidParameterError("alpha","should be boolean value",t.alpha);return this}function pc(t){if(d.plainObject(t)){if(d.defined(t.lower))if(d.number(t.lower)&&d.inRange(t.lower,0,99))this.options.normaliseLower=t.lower;else throw d.invalidParameterError("lower","number between 0 and 99",t.lower);if(d.defined(t.upper))if(d.number(t.upper)&&d.inRange(t.upper,1,100))this.options.normaliseUpper=t.upper;else throw d.invalidParameterError("upper","number between 1 and 100",t.upper)}if(this.options.normaliseLower>=this.options.normaliseUpper)throw d.invalidParameterError("range","lower to be less than upper",`${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);return this.options.normalise=!0,this}function mc(t){return this.normalise(t)}function bc(t){if(d.plainObject(t)){if(d.integer(t.width)&&t.width>0)this.options.claheWidth=t.width;else throw d.invalidParameterError("width","integer greater than zero",t.width);if(d.integer(t.height)&&t.height>0)this.options.claheHeight=t.height;else throw d.invalidParameterError("height","integer greater than zero",t.height);if(d.defined(t.maxSlope))if(d.integer(t.maxSlope)&&d.inRange(t.maxSlope,0,100))this.options.claheMaxSlope=t.maxSlope;else throw d.invalidParameterError("maxSlope","integer between 0 and 100",t.maxSlope)}else throw d.invalidParameterError("options","plain object",t);return this}function vc(t){if(!d.object(t)||!Array.isArray(t.kernel)||!d.integer(t.width)||!d.integer(t.height)||!d.inRange(t.width,3,1001)||!d.inRange(t.height,3,1001)||t.height*t.width!==t.kernel.length)throw new Error("Invalid convolution kernel");return d.integer(t.scale)||(t.scale=t.kernel.reduce((e,r)=>e+r,0)),t.scale<1&&(t.scale=1),d.integer(t.offset)||(t.offset=0),this.options.convKernel=t,this}function wc(t,e){if(!d.defined(t))this.options.threshold=128;else if(d.bool(t))this.options.threshold=t?128:0;else if(d.integer(t)&&d.inRange(t,0,255))this.options.threshold=t;else throw d.invalidParameterError("threshold","integer between 0 and 255",t);return!d.object(e)||e.greyscale===!0||e.grayscale===!0?this.options.thresholdGrayscale=!0:this.options.thresholdGrayscale=!1,this}function yc(t,e,r){if(this.options.boolean=this._createInputDescriptor(t,r),d.string(e)&&d.inArray(e,["and","or","eor"]))this.options.booleanOp=e;else throw d.invalidParameterError("operator","one of: and, or, eor",e);return this}function Ec(t,e){if(!d.defined(t)&&d.number(e)?t=1:d.number(t)&&!d.defined(e)&&(e=0),!d.defined(t))this.options.linearA=[];else if(d.number(t))this.options.linearA=[t];else if(Array.isArray(t)&&t.length&&t.every(d.number))this.options.linearA=t;else throw d.invalidParameterError("a","number or array of numbers",t);if(!d.defined(e))this.options.linearB=[];else if(d.number(e))this.options.linearB=[e];else if(Array.isArray(e)&&e.length&&e.every(d.number))this.options.linearB=e;else throw d.invalidParameterError("b","number or array of numbers",e);if(this.options.linearA.length!==this.options.linearB.length)throw new Error("Expected a and b to be arrays of the same length");return this}function Pc(t){if(!Array.isArray(t))throw d.invalidParameterError("inputMatrix","array",t);if(t.length!==3&&t.length!==4)throw d.invalidParameterError("inputMatrix","3x3 or 4x4 array",t.length);let e=t.flat().map(Number);if(e.length!==9&&e.length!==16)throw d.invalidParameterError("inputMatrix","cardinality of 9 or 16",e.length);return this.options.recombMatrix=e,this}function xc(t){if(!d.plainObject(t))throw d.invalidParameterError("options","plain object",t);if("brightness"in t)if(d.number(t.brightness)&&t.brightness>=0)this.options.brightness=t.brightness;else throw d.invalidParameterError("brightness","number above zero",t.brightness);if("saturation"in t)if(d.number(t.saturation)&&t.saturation>=0)this.options.saturation=t.saturation;else throw d.invalidParameterError("saturation","number above zero",t.saturation);if("hue"in t)if(d.integer(t.hue))this.options.hue=t.hue%360;else throw d.invalidParameterError("hue","number",t.hue);if("lightness"in t)if(d.number(t.lightness))this.options.lightness=t.lightness;else throw d.invalidParameterError("lightness","number",t.lightness);return this}Qi.exports=t=>{Object.assign(t.prototype,{autoOrient:ic,rotate:sc,flip:nc,flop:ac,affine:oc,sharpen:lc,erode:Ki,dilate:Yi,median:cc,blur:hc,flatten:uc,unflatten:fc,gamma:dc,negate:gc,normalise:pc,normalize:mc,clahe:bc,convolve:vc,threshold:wc,boolean:yc,linear:Ec,recomb:Pc,modulate:xc})}});var an=x((xf,nn)=>{var Rr=Object.defineProperty,Rc=Object.getOwnPropertyDescriptor,$c=Object.getOwnPropertyNames,Sc=Object.prototype.hasOwnProperty,kc=(t,e)=>{for(var r in e)Rr(t,r,{get:e[r],enumerable:!0})},Ac=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of $c(e))!Sc.call(t,i)&&i!==r&&Rr(t,i,{get:()=>e[i],enumerable:!(s=Rc(e,i))||s.enumerable});return t},_c=t=>Ac(Rr({},"__esModule",{value:!0}),t),en={};kc(en,{default:()=>qc});nn.exports=_c(en);var ce={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},tn=Object.create(null);for(let t in ce)Object.hasOwn(ce,t)&&(tn[ce[t]]=t);var H={to:{},get:{}};H.get=function(t){let e=t.slice(0,3).toLowerCase(),r,s;switch(e){case"hsl":{r=H.get.hsl(t),s="hsl";break}case"hwb":{r=H.get.hwb(t),s="hwb";break}default:{r=H.get.rgb(t),s="rgb";break}}return r?{model:s,value:r}:null};H.get.rgb=function(t){if(!t)return null;let e=/^#([a-f\d]{3,4})$/i,r=/^#([a-f\d]{6})([a-f\d]{2})?$/i,s=/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/,i=/^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/,n=/^(\w+)$/,a=[0,0,0,1],o,c,h;if(o=t.match(r)){for(h=o[2],o=o[1],c=0;c<3;c++){let f=c*2;a[c]=Number.parseInt(o.slice(f,f+2),16)}h&&(a[3]=Number.parseInt(h,16)/255)}else if(o=t.match(e)){for(o=o[1],h=o[3],c=0;c<3;c++)a[c]=Number.parseInt(o[c]+o[c],16);h&&(a[3]=Number.parseInt(h+h,16)/255)}else if(o=t.match(s)){for(c=0;c<3;c++)a[c]=Number.parseInt(o[c+1],10);o[4]&&(a[3]=o[5]?Number.parseFloat(o[4])*.01:Number.parseFloat(o[4]))}else if(o=t.match(i)){for(c=0;c<3;c++)a[c]=Math.round(Number.parseFloat(o[c+1])*2.55);o[4]&&(a[3]=o[5]?Number.parseFloat(o[4])*.01:Number.parseFloat(o[4]))}else return(o=t.match(n))?o[1]==="transparent"?[0,0,0,0]:Object.hasOwn(ce,o[1])?(a=ce[o[1]],a[3]=1,a):null:null;for(c=0;c<3;c++)a[c]=ke(a[c],0,255);return a[3]=ke(a[3],0,1),a};H.get.hsl=function(t){if(!t)return null;let e=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){let s=Number.parseFloat(r[4]),i=(Number.parseFloat(r[1])%360+360)%360,n=ke(Number.parseFloat(r[2]),0,100),a=ke(Number.parseFloat(r[3]),0,100),o=ke(Number.isNaN(s)?1:s,0,1);return[i,n,a,o]}return null};H.get.hwb=function(t){if(!t)return null;let e=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){let s=Number.parseFloat(r[4]),i=(Number.parseFloat(r[1])%360+360)%360,n=ke(Number.parseFloat(r[2]),0,100),a=ke(Number.parseFloat(r[3]),0,100),o=ke(Number.isNaN(s)?1:s,0,1);return[i,n,a,o]}return null};H.to.hex=function(...t){return"#"+jt(t[0])+jt(t[1])+jt(t[2])+(t[3]<1?jt(Math.round(t[3]*255)):"")};H.to.rgb=function(...t){return t.length<4||t[3]===1?"rgb("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+")":"rgba("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+", "+t[3]+")"};H.to.rgb.percent=function(...t){let e=Math.round(t[0]/255*100),r=Math.round(t[1]/255*100),s=Math.round(t[2]/255*100);return t.length<4||t[3]===1?"rgb("+e+"%, "+r+"%, "+s+"%)":"rgba("+e+"%, "+r+"%, "+s+"%, "+t[3]+")"};H.to.hsl=function(...t){return t.length<4||t[3]===1?"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)":"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+t[3]+")"};H.to.hwb=function(...t){let e="";return t.length>=4&&t[3]!==1&&(e=", "+t[3]),"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+e+")"};H.to.keyword=function(...t){return tn[t.slice(0,3)]};function ke(t,e,r){return Math.min(Math.max(e,t),r)}function jt(t){let e=Math.round(t).toString(16).toUpperCase();return e.length<2?"0"+e:e}var Xe=H,rn={};for(let t of Object.keys(ce))rn[ce[t]]=t;var b={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},oklab:{channels:3,labels:["okl","oka","okb"]},lch:{channels:3,labels:"lch"},oklch:{channels:3,labels:["okl","okc","okh"]},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}},Me=b,we=(6/29)**3;function Ke(t){let e=t>.0031308?1.055*t**.4166666666666667-.055:t*12.92;return Math.min(Math.max(0,e),1)}function Qe(t){return t>.04045?((t+.055)/1.055)**2.4:t/12.92}for(let t of Object.keys(b)){if(!("channels"in b[t]))throw new Error("missing channels property: "+t);if(!("labels"in b[t]))throw new Error("missing channel labels property: "+t);if(b[t].labels.length!==b[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:r}=b[t];delete b[t].channels,delete b[t].labels,Object.defineProperty(b[t],"channels",{value:e}),Object.defineProperty(b[t],"labels",{value:r})}b.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,s=t[2]/255,i=Math.min(e,r,s),n=Math.max(e,r,s),a=n-i,o,c;switch(n){case i:{o=0;break}case e:{o=(r-s)/a;break}case r:{o=2+(s-e)/a;break}case s:{o=4+(e-r)/a;break}}o=Math.min(o*60,360),o<0&&(o+=360);let h=(i+n)/2;return n===i?c=0:h<=.5?c=a/(n+i):c=a/(2-n-i),[o,c*100,h*100]};b.rgb.hsv=function(t){let e,r,s,i,n,a=t[0]/255,o=t[1]/255,c=t[2]/255,h=Math.max(a,o,c),f=h-Math.min(a,o,c),g=function(m){return(h-m)/6/f+1/2};if(f===0)i=0,n=0;else{switch(n=f/h,e=g(a),r=g(o),s=g(c),h){case a:{i=s-r;break}case o:{i=1/3+e-s;break}case c:{i=2/3+r-e;break}}i<0?i+=1:i>1&&(i-=1)}return[i*360,n*100,h*100]};b.rgb.hwb=function(t){let e=t[0],r=t[1],s=t[2],i=b.rgb.hsl(t)[0],n=1/255*Math.min(e,Math.min(r,s));return s=1-1/255*Math.max(e,Math.max(r,s)),[i,n*100,s*100]};b.rgb.oklab=function(t){let e=Qe(t[0]/255),r=Qe(t[1]/255),s=Qe(t[2]/255),i=Math.cbrt(.4122214708*e+.5363325363*r+.0514459929*s),n=Math.cbrt(.2119034982*e+.6806995451*r+.1073969566*s),a=Math.cbrt(.0883024619*e+.2817188376*r+.6299787005*s),o=.2104542553*i+.793617785*n-.0040720468*a,c=1.9779984951*i-2.428592205*n+.4505937099*a,h=.0259040371*i+.7827717662*n-.808675766*a;return[o*100,c*100,h*100]};b.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,s=t[2]/255,i=Math.min(1-e,1-r,1-s),n=(1-e-i)/(1-i)||0,a=(1-r-i)/(1-i)||0,o=(1-s-i)/(1-i)||0;return[n*100,a*100,o*100,i*100]};function Nc(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}b.rgb.keyword=function(t){let e=rn[t];if(e)return e;let r=Number.POSITIVE_INFINITY,s;for(let i of Object.keys(ce)){let n=ce[i],a=Nc(t,n);a<r&&(r=a,s=i)}return s};b.keyword.rgb=function(t){return ce[t]};b.rgb.xyz=function(t){let e=Qe(t[0]/255),r=Qe(t[1]/255),s=Qe(t[2]/255),i=e*.4124564+r*.3575761+s*.1804375,n=e*.2126729+r*.7151522+s*.072175,a=e*.0193339+r*.119192+s*.9503041;return[i*100,n*100,a*100]};b.rgb.lab=function(t){let e=b.rgb.xyz(t),r=e[0],s=e[1],i=e[2];r/=95.047,s/=100,i/=108.883,r=r>we?r**(1/3):7.787*r+16/116,s=s>we?s**(1/3):7.787*s+16/116,i=i>we?i**(1/3):7.787*i+16/116;let n=116*s-16,a=500*(r-s),o=200*(s-i);return[n,a,o]};b.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,s=t[2]/100,i,n;if(r===0)return n=s*255,[n,n,n];let a=s<.5?s*(1+r):s+r-s*r,o=2*s-a,c=[0,0,0];for(let h=0;h<3;h++)i=e+1/3*-(h-1),i<0&&i++,i>1&&i--,6*i<1?n=o+(a-o)*6*i:2*i<1?n=a:3*i<2?n=o+(a-o)*(2/3-i)*6:n=o,c[h]=n*255;return c};b.hsl.hsv=function(t){let e=t[0],r=t[1]/100,s=t[2]/100,i=r,n=Math.max(s,.01);s*=2,r*=s<=1?s:2-s,i*=n<=1?n:2-n;let a=(s+r)/2,o=s===0?2*i/(n+i):2*r/(s+r);return[e,o*100,a*100]};b.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,s=t[2]/100,i=Math.floor(e)%6,n=e-Math.floor(e),a=255*s*(1-r),o=255*s*(1-r*n),c=255*s*(1-r*(1-n));switch(s*=255,i){case 0:return[s,c,a];case 1:return[o,s,a];case 2:return[a,s,c];case 3:return[a,o,s];case 4:return[c,a,s];case 5:return[s,a,o]}};b.hsv.hsl=function(t){let e=t[0],r=t[1]/100,s=t[2]/100,i=Math.max(s,.01),n,a;a=(2-r)*s;let o=(2-r)*i;return n=r*i,n/=o<=1?o:2-o,n=n||0,a/=2,[e,n*100,a*100]};b.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,s=t[2]/100,i=r+s,n;i>1&&(r/=i,s/=i);let a=Math.floor(6*e),o=1-s;n=6*e-a,(a&1)!==0&&(n=1-n);let c=r+n*(o-r),h,f,g;switch(a){default:case 6:case 0:{h=o,f=c,g=r;break}case 1:{h=c,f=o,g=r;break}case 2:{h=r,f=o,g=c;break}case 3:{h=r,f=c,g=o;break}case 4:{h=c,f=r,g=o;break}case 5:{h=o,f=r,g=c;break}}return[h*255,f*255,g*255]};b.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,s=t[2]/100,i=t[3]/100,n=1-Math.min(1,e*(1-i)+i),a=1-Math.min(1,r*(1-i)+i),o=1-Math.min(1,s*(1-i)+i);return[n*255,a*255,o*255]};b.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,s=t[2]/100,i,n,a;return i=e*3.2404542+r*-1.5371385+s*-.4985314,n=e*-.969266+r*1.8760108+s*.041556,a=e*.0556434+r*-.2040259+s*1.0572252,i=Ke(i),n=Ke(n),a=Ke(a),[i*255,n*255,a*255]};b.xyz.lab=function(t){let e=t[0],r=t[1],s=t[2];e/=95.047,r/=100,s/=108.883,e=e>we?e**(1/3):7.787*e+16/116,r=r>we?r**(1/3):7.787*r+16/116,s=s>we?s**(1/3):7.787*s+16/116;let i=116*r-16,n=500*(e-r),a=200*(r-s);return[i,n,a]};b.xyz.oklab=function(t){let e=t[0]/100,r=t[1]/100,s=t[2]/100,i=Math.cbrt(.8189330101*e+.3618667424*r-.1288597137*s),n=Math.cbrt(.0329845436*e+.9293118715*r+.0361456387*s),a=Math.cbrt(.0482003018*e+.2643662691*r+.633851707*s),o=.2104542553*i+.793617785*n-.0040720468*a,c=1.9779984951*i-2.428592205*n+.4505937099*a,h=.0259040371*i+.7827717662*n-.808675766*a;return[o*100,c*100,h*100]};b.oklab.oklch=function(t){return b.lab.lch(t)};b.oklab.xyz=function(t){let e=t[0]/100,r=t[1]/100,s=t[2]/100,i=(.999999998*e+.396337792*r+.215803758*s)**3,n=(1.000000008*e-.105561342*r-.063854175*s)**3,a=(1.000000055*e-.089484182*r-1.291485538*s)**3,o=1.227013851*i-.55779998*n+.281256149*a,c=-.040580178*i+1.11225687*n-.071676679*a,h=-.076381285*i-.421481978*n+1.58616322*a;return[o*100,c*100,h*100]};b.oklab.rgb=function(t){let e=t[0]/100,r=t[1]/100,s=t[2]/100,i=(e+.3963377774*r+.2158037573*s)**3,n=(e-.1055613458*r-.0638541728*s)**3,a=(e-.0894841775*r-1.291485548*s)**3,o=Ke(4.0767416621*i-3.3077115913*n+.2309699292*a),c=Ke(-1.2684380046*i+2.6097574011*n-.3413193965*a),h=Ke(-.0041960863*i-.7034186147*n+1.707614701*a);return[o*255,c*255,h*255]};b.oklch.oklab=function(t){return b.lch.lab(t)};b.lab.xyz=function(t){let e=t[0],r=t[1],s=t[2],i,n,a;n=(e+16)/116,i=r/500+n,a=n-s/200;let o=n**3,c=i**3,h=a**3;return n=o>we?o:(n-16/116)/7.787,i=c>we?c:(i-16/116)/7.787,a=h>we?h:(a-16/116)/7.787,i*=95.047,n*=100,a*=108.883,[i,n,a]};b.lab.lch=function(t){let e=t[0],r=t[1],s=t[2],i;i=Math.atan2(s,r)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(r*r+s*s);return[e,a,i]};b.lch.lab=function(t){let e=t[0],r=t[1],i=t[2]/360*2*Math.PI,n=r*Math.cos(i),a=r*Math.sin(i);return[e,n,a]};b.rgb.ansi16=function(t,e=null){let[r,s,i]=t,n=e===null?b.rgb.hsv(t)[2]:e;if(n=Math.round(n/50),n===0)return 30;let a=30+(Math.round(i/255)<<2|Math.round(s/255)<<1|Math.round(r/255));return n===2&&(a+=60),a};b.hsv.ansi16=function(t){return b.rgb.ansi16(b.hsv.rgb(t),t[2])};b.rgb.ansi256=function(t){let e=t[0],r=t[1],s=t[2];return e>>4===r>>4&&r>>4===s>>4?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(s/255*5)};b.ansi16.rgb=function(t){t=t[0];let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let r=(Math.trunc(t>50)+1)*.5,s=(e&1)*r*255,i=(e>>1&1)*r*255,n=(e>>2&1)*r*255;return[s,i,n]};b.ansi256.rgb=function(t){if(t=t[0],t>=232){let n=(t-232)*10+8;return[n,n,n]}t-=16;let e,r=Math.floor(t/36)/5*255,s=Math.floor((e=t%36)/6)/5*255,i=e%6/5*255;return[r,s,i]};b.rgb.hex=function(t){let r=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".slice(r.length)+r};b.hex.rgb=function(t){let e=t.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i);if(!e)return[0,0,0];let r=e[0];e[0].length===3&&(r=[...r].map(o=>o+o).join(""));let s=Number.parseInt(r,16),i=s>>16&255,n=s>>8&255,a=s&255;return[i,n,a]};b.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,s=t[2]/255,i=Math.max(Math.max(e,r),s),n=Math.min(Math.min(e,r),s),a=i-n,o,c=a<1?n/(1-a):0;return a<=0?o=0:i===e?o=(r-s)/a%6:i===r?o=2+(s-e)/a:o=4+(e-r)/a,o/=6,o%=1,[o*360,a*100,c*100]};b.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,s=r<.5?2*e*r:2*e*(1-r),i=0;return s<1&&(i=(r-.5*s)/(1-s)),[t[0],s*100,i*100]};b.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,s=e*r,i=0;return s<1&&(i=(r-s)/(1-s)),[t[0],s*100,i*100]};b.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,s=t[2]/100;if(r===0)return[s*255,s*255,s*255];let i=[0,0,0],n=e%1*6,a=n%1,o=1-a,c=0;switch(Math.floor(n)){case 0:{i[0]=1,i[1]=a,i[2]=0;break}case 1:{i[0]=o,i[1]=1,i[2]=0;break}case 2:{i[0]=0,i[1]=1,i[2]=a;break}case 3:{i[0]=0,i[1]=o,i[2]=1;break}case 4:{i[0]=a,i[1]=0,i[2]=1;break}default:i[0]=1,i[1]=0,i[2]=o}return c=(1-r)*s,[(r*i[0]+c)*255,(r*i[1]+c)*255,(r*i[2]+c)*255]};b.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,s=e+r*(1-e),i=0;return s>0&&(i=e/s),[t[0],i*100,s*100]};b.hcg.hsl=function(t){let e=t[1]/100,s=t[2]/100*(1-e)+.5*e,i=0;return s>0&&s<.5?i=e/(2*s):s>=.5&&s<1&&(i=e/(2*(1-s))),[t[0],i*100,s*100]};b.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,s=e+r*(1-e);return[t[0],(s-e)*100,(1-s)*100]};b.hwb.hcg=function(t){let e=t[1]/100,s=1-t[2]/100,i=s-e,n=0;return i<1&&(n=(s-i)/(1-i)),[t[0],i*100,n*100]};b.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};b.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};b.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};b.gray.hsl=function(t){return[0,0,t[0]]};b.gray.hsv=b.gray.hsl;b.gray.hwb=function(t){return[0,100,t[0]]};b.gray.cmyk=function(t){return[0,0,0,t[0]]};b.gray.lab=function(t){return[t[0],0,0]};b.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,s=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".slice(s.length)+s};b.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]};function Ic(){let t={},e=Object.keys(Me);for(let{length:r}=e,s=0;s<r;s++)t[e[s]]={distance:-1,parent:null};return t}function Fc(t){let e=Ic(),r=[t];for(e[t].distance=0;r.length>0;){let s=r.pop(),i=Object.keys(Me[s]);for(let{length:n}=i,a=0;a<n;a++){let o=i[a],c=e[o];c.distance===-1&&(c.distance=e[s].distance+1,c.parent=s,r.unshift(o))}}return e}function Cc(t,e){return function(r){return e(t(r))}}function Dc(t,e){let r=[e[t].parent,t],s=Me[e[t].parent][t],i=e[t].parent;for(;e[i].parent;)r.unshift(e[i].parent),s=Cc(Me[e[i].parent][i],s),i=e[i].parent;return s.conversion=r,s}function jc(t){let e=Fc(t),r={},s=Object.keys(e);for(let{length:i}=s,n=0;n<i;n++){let a=s[n];e[a].parent!==null&&(r[a]=Dc(a,e))}return r}var Tc=jc,Ye={},Lc=Object.keys(Me);function Oc(t){let e=function(...r){let s=r[0];return s==null?s:(s.length>1&&(r=s),t(r))};return"conversion"in t&&(e.conversion=t.conversion),e}function Mc(t){let e=function(...r){let s=r[0];if(s==null)return s;s.length>1&&(r=s);let i=t(r);if(typeof i=="object")for(let{length:n}=i,a=0;a<n;a++)i[a]=Math.round(i[a]);return i};return"conversion"in t&&(e.conversion=t.conversion),e}for(let t of Lc){Ye[t]={},Object.defineProperty(Ye[t],"channels",{value:Me[t].channels}),Object.defineProperty(Ye[t],"labels",{value:Me[t].labels});let e=Tc(t),r=Object.keys(e);for(let s of r){let i=e[s];Ye[t][s]=Mc(i),Ye[t][s].raw=Oc(i)}}var V=Ye,sn=["keyword","gray","hex"],Er={};for(let t of Object.keys(V))Er[[...V[t].labels].sort().join("")]=t;var Pr={};function L(t,e){if(!(this instanceof L))return new L(t,e);if(e&&e in sn&&(e=null),e&&!(e in V))throw new Error("Unknown model: "+e);let r,s;if(t==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(t instanceof L)this.model=t.model,this.color=[...t.color],this.valpha=t.valpha;else if(typeof t=="string"){let i=Xe.get(t);if(i===null)throw new Error("Unable to parse color from string: "+t);this.model=i.model,s=V[this.model].channels,this.color=i.value.slice(0,s),this.valpha=typeof i.value[s]=="number"?i.value[s]:1}else if(t.length>0){this.model=e||"rgb",s=V[this.model].channels;let i=Array.prototype.slice.call(t,0,s);this.color=xr(i,s),this.valpha=typeof t[s]=="number"?t[s]:1}else if(typeof t=="number")this.model="rgb",this.color=[t>>16&255,t>>8&255,t&255],this.valpha=1;else{this.valpha=1;let i=Object.keys(t);"alpha"in t&&(i.splice(i.indexOf("alpha"),1),this.valpha=typeof t.alpha=="number"?t.alpha:0);let n=i.sort().join("");if(!(n in Er))throw new Error("Unable to parse color from object: "+JSON.stringify(t));this.model=Er[n];let{labels:a}=V[this.model],o=[];for(r=0;r<a.length;r++)o.push(t[a[r]]);this.color=xr(o)}if(Pr[this.model])for(s=V[this.model].channels,r=0;r<s;r++){let i=Pr[this.model][r];i&&(this.color[r]=i(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}L.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(t){let e=this.model in Xe.to?this:this.rgb();e=e.round(typeof t=="number"?t:1);let r=e.valpha===1?e.color:[...e.color,this.valpha];return Xe.to[e.model](...r)},percentString(t){let e=this.rgb().round(typeof t=="number"?t:1),r=e.valpha===1?e.color:[...e.color,this.valpha];return Xe.to.rgb.percent(...r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){let t={},{channels:e}=V[this.model],{labels:r}=V[this.model];for(let s=0;s<e;s++)t[r[s]]=this.color[s];return this.valpha!==1&&(t.alpha=this.valpha),t},unitArray(){let t=this.rgb().color;return t[0]/=255,t[1]/=255,t[2]/=255,this.valpha!==1&&t.push(this.valpha),t},unitObject(){let t=this.rgb().object();return t.r/=255,t.g/=255,t.b/=255,this.valpha!==1&&(t.alpha=this.valpha),t},round(t){return t=Math.max(t||0,0),new L([...this.color.map(Bc(t)),this.valpha],this.model)},alpha(t){return t!==void 0?new L([...this.color,Math.max(0,Math.min(1,t))],this.model):this.valpha},red:F("rgb",0,j(255)),green:F("rgb",1,j(255)),blue:F("rgb",2,j(255)),hue:F(["hsl","hsv","hsl","hwb","hcg"],0,t=>(t%360+360)%360),saturationl:F("hsl",1,j(100)),lightness:F("hsl",2,j(100)),saturationv:F("hsv",1,j(100)),value:F("hsv",2,j(100)),chroma:F("hcg",1,j(100)),gray:F("hcg",2,j(100)),white:F("hwb",1,j(100)),wblack:F("hwb",2,j(100)),cyan:F("cmyk",0,j(100)),magenta:F("cmyk",1,j(100)),yellow:F("cmyk",2,j(100)),black:F("cmyk",3,j(100)),x:F("xyz",0,j(95.047)),y:F("xyz",1,j(100)),z:F("xyz",2,j(108.833)),l:F("lab",0,j(100)),a:F("lab",1),b:F("lab",2),keyword(t){return t!==void 0?new L(t):V[this.model].keyword(this.color)},hex(t){return t!==void 0?new L(t):Xe.to.hex(...this.rgb().round().color)},hexa(t){if(t!==void 0)return new L(t);let e=this.rgb().round().color,r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),Xe.to.hex(...e)+r},rgbNumber(){let t=this.rgb().color;return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255},luminosity(){let t=this.rgb().color,e=[];for(let[r,s]of t.entries()){let i=s/255;e[r]=i<=.04045?i/12.92:((i+.055)/1.055)**2.4}return .2126*e[0]+.7152*e[1]+.0722*e[2]},contrast(t){let e=this.luminosity(),r=t.luminosity();return e>r?(e+.05)/(r+.05):(r+.05)/(e+.05)},level(t){let e=this.contrast(t);return e>=7?"AAA":e>=4.5?"AA":""},isDark(){let t=this.rgb().color;return(t[0]*2126+t[1]*7152+t[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){let t=this.rgb();for(let e=0;e<3;e++)t.color[e]=255-t.color[e];return t},lighten(t){let e=this.hsl();return e.color[2]+=e.color[2]*t,e},darken(t){let e=this.hsl();return e.color[2]-=e.color[2]*t,e},saturate(t){let e=this.hsl();return e.color[1]+=e.color[1]*t,e},desaturate(t){let e=this.hsl();return e.color[1]-=e.color[1]*t,e},whiten(t){let e=this.hwb();return e.color[1]+=e.color[1]*t,e},blacken(t){let e=this.hwb();return e.color[2]+=e.color[2]*t,e},grayscale(){let t=this.rgb().color,e=t[0]*.3+t[1]*.59+t[2]*.11;return L.rgb(e,e,e)},fade(t){return this.alpha(this.valpha-this.valpha*t)},opaquer(t){return this.alpha(this.valpha+this.valpha*t)},rotate(t){let e=this.hsl(),r=e.color[0];return r=(r+t)%360,r=r<0?360+r:r,e.color[0]=r,e},mix(t,e){if(!t||!t.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof t);let r=t.rgb(),s=this.rgb(),i=e===void 0?.5:e,n=2*i-1,a=r.alpha()-s.alpha(),o=((n*a===-1?n:(n+a)/(1+n*a))+1)/2,c=1-o;return L.rgb(o*r.red()+c*s.red(),o*r.green()+c*s.green(),o*r.blue()+c*s.blue(),r.alpha()*i+s.alpha()*(1-i))}};for(let t of Object.keys(V)){if(sn.includes(t))continue;let{channels:e}=V[t];L.prototype[t]=function(...r){return this.model===t?new L(this):r.length>0?new L(r,t):new L([...Uc(V[this.model][t].raw(this.color)),this.valpha],t)},L[t]=function(...r){let s=r[0];return typeof s=="number"&&(s=xr(r,e)),new L(s,t)}}function zc(t,e){return Number(t.toFixed(e))}function Bc(t){return function(e){return zc(e,t)}}function F(t,e,r){t=Array.isArray(t)?t:[t];for(let s of t)(Pr[s]||=[])[e]=r;return t=t[0],function(s){let i;return s!==void 0?(r&&(s=r(s)),i=this[t](),i.color[e]=s,i):(i=this[t]().color[e],r&&(i=r(i)),i)}}function j(t){return function(e){return Math.max(0,Math.min(t,e))}}function Uc(t){return Array.isArray(t)?t:[t]}function xr(t,e){for(let r=0;r<e;r++)typeof t[r]!="number"&&(t[r]=0);return t}var qc=L});var ln=x((Rf,on)=>{on.exports=an().default});var fn=x(($f,un)=>{var Gc=ln(),ye=ie(),cn={multiband:"multiband","b-w":"b-w",bw:"b-w",cmyk:"cmyk",srgb:"srgb"};function Hc(t){return this._setBackgroundColourOption("tint",t),this}function Wc(t){return this.options.greyscale=ye.bool(t)?t:!0,this}function Vc(t){return this.greyscale(t)}function Jc(t){if(!ye.string(t))throw ye.invalidParameterError("colourspace","string",t);return this.options.colourspacePipeline=t,this}function Xc(t){return this.pipelineColourspace(t)}function Yc(t){if(!ye.string(t))throw ye.invalidParameterError("colourspace","string",t);return this.options.colourspace=t,this}function Kc(t){return this.toColourspace(t)}function hn(t){if(ye.object(t)||ye.string(t)&&t.length>=3&&t.length<=200){let e=Gc(t);return[e.red(),e.green(),e.blue(),Math.round(e.alpha()*255)]}else throw ye.invalidParameterError("background","object or string",t)}function Qc(t,e){ye.defined(e)&&(this.options[t]=hn(e))}un.exports=t=>{Object.assign(t.prototype,{tint:Hc,greyscale:Wc,grayscale:Vc,pipelineColourspace:Jc,pipelineColorspace:Xc,toColourspace:Yc,toColorspace:Kc,_getBackgroundColourOption:hn,_setBackgroundColourOption:Qc}),t.colourspace=cn,t.colorspace=cn}});var gn=x((Sf,dn)=>{var he=ie(),Zc={and:"and",or:"or",eor:"eor"};function eh(){return this.options.removeAlpha=!0,this}function th(t){if(he.defined(t))if(he.number(t)&&he.inRange(t,0,1))this.options.ensureAlpha=t;else throw he.invalidParameterError("alpha","number between 0 and 1",t);else this.options.ensureAlpha=1;return this}function rh(t){let e={red:0,green:1,blue:2,alpha:3};if(Object.keys(e).includes(t)&&(t=e[t]),he.integer(t)&&he.inRange(t,0,4))this.options.extractChannel=t;else throw he.invalidParameterError("channel","integer or one of: red, green, blue, alpha",t);return this}function sh(t,e){return Array.isArray(t)?t.forEach(function(r){this.options.joinChannelIn.push(this._createInputDescriptor(r,e))},this):this.options.joinChannelIn.push(this._createInputDescriptor(t,e)),this}function ih(t){if(he.string(t)&&he.inArray(t,["and","or","eor"]))this.options.bandBoolOp=t;else throw he.invalidParameterError("boolOp","one of: and, or, eor",t);return this}dn.exports=t=>{Object.assign(t.prototype,{removeAlpha:eh,ensureAlpha:th,extractChannel:rh,joinChannel:sh,bandbool:ih}),t.bool=Zc}});var wn=x((kf,vn)=>{var $r=I("node:path"),l=ie(),Ze=ft(),pn=new Map([["heic","heif"],["heif","heif"],["avif","avif"],["jpeg","jpeg"],["jpg","jpeg"],["jpe","jpeg"],["tile","tile"],["dz","tile"],["png","png"],["raw","raw"],["tiff","tiff"],["tif","tiff"],["webp","webp"],["gif","gif"],["jp2","jp2"],["jpx","jp2"],["j2k","jp2"],["j2c","jp2"],["jxl","jxl"]]),nh=/\.(jp[2x]|j2[kc])$/i,mn=()=>new Error("JP2 output requires libvips with support for OpenJPEG"),bn=t=>1<<31-Math.clz32(Math.ceil(Math.log2(t)));function ah(t,e){let r;if(l.string(t)?l.string(this.options.input.file)&&$r.resolve(this.options.input.file)===$r.resolve(t)?r=new Error("Cannot use same file for input and output"):nh.test($r.extname(t))&&!this.constructor.format.jp2k.output.file&&(r=mn()):r=new Error("Missing output file path"),r)if(l.fn(e))e(r);else return Promise.reject(r);else{this.options.fileOut=t;let s=Error();return this._pipeline(e,s)}return this}function oh(t,e){l.object(t)?this._setBooleanOption("resolveWithObject",t.resolveWithObject):this.options.resolveWithObject&&(this.options.resolveWithObject=!1),this.options.fileOut="";let r=Error();return this._pipeline(l.fn(t)?t:e,r)}function lh(){return this.options.keepMetadata|=1,this}function ch(t){if(l.object(t))for(let[e,r]of Object.entries(t))if(l.object(r))for(let[s,i]of Object.entries(r))if(l.string(i))this.options.withExif[`exif-${e.toLowerCase()}-${s}`]=i;else throw l.invalidParameterError(`${e}.${s}`,"string",i);else throw l.invalidParameterError(e,"object",r);else throw l.invalidParameterError("exif","object",t);return this.options.withExifMerge=!1,this.keepExif()}function hh(t){return this.withExif(t),this.options.withExifMerge=!0,this}function uh(){return this.options.keepMetadata|=8,this}function fh(t,e){if(l.string(t))this.options.withIccProfile=t;else throw l.invalidParameterError("icc","string",t);if(this.keepIccProfile(),l.object(e)&&l.defined(e.attach))if(l.bool(e.attach))e.attach||(this.options.keepMetadata&=-9);else throw l.invalidParameterError("attach","boolean",e.attach);return this}function dh(){return this.options.keepMetadata|=2,this}function gh(t){if(l.string(t)&&t.length>0)this.options.withXmp=t,this.options.keepMetadata|=2;else throw l.invalidParameterError("xmp","non-empty string",t);return this}function ph(){return this.options.keepMetadata=31,this}function mh(t){if(this.keepMetadata(),this.withIccProfile("srgb"),l.object(t)){if(l.defined(t.orientation))if(l.integer(t.orientation)&&l.inRange(t.orientation,1,8))this.options.withMetadataOrientation=t.orientation;else throw l.invalidParameterError("orientation","integer between 1 and 8",t.orientation);if(l.defined(t.density))if(l.number(t.density)&&t.density>0)this.options.withMetadataDensity=t.density;else throw l.invalidParameterError("density","positive number",t.density);l.defined(t.icc)&&this.withIccProfile(t.icc),l.defined(t.exif)&&this.withExifMerge(t.exif)}return this}function bh(t,e){let r=pn.get((l.object(t)&&l.string(t.id)?t.id:t).toLowerCase());if(!r)throw l.invalidParameterError("format",`one of: ${[...pn.keys()].join(", ")}`,t);return this[r](e)}function vh(t){if(l.object(t)){if(l.defined(t.quality))if(l.integer(t.quality)&&l.inRange(t.quality,1,100))this.options.jpegQuality=t.quality;else throw l.invalidParameterError("quality","integer between 1 and 100",t.quality);if(l.defined(t.progressive)&&this._setBooleanOption("jpegProgressive",t.progressive),l.defined(t.chromaSubsampling))if(l.string(t.chromaSubsampling)&&l.inArray(t.chromaSubsampling,["4:2:0","4:4:4"]))this.options.jpegChromaSubsampling=t.chromaSubsampling;else throw l.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",t.chromaSubsampling);let e=l.bool(t.optimizeCoding)?t.optimizeCoding:t.optimiseCoding;if(l.defined(e)&&this._setBooleanOption("jpegOptimiseCoding",e),l.defined(t.mozjpeg))if(l.bool(t.mozjpeg))t.mozjpeg&&(this.options.jpegTrellisQuantisation=!0,this.options.jpegOvershootDeringing=!0,this.options.jpegOptimiseScans=!0,this.options.jpegProgressive=!0,this.options.jpegQuantisationTable=3);else throw l.invalidParameterError("mozjpeg","boolean",t.mozjpeg);let r=l.bool(t.trellisQuantization)?t.trellisQuantization:t.trellisQuantisation;l.defined(r)&&this._setBooleanOption("jpegTrellisQuantisation",r),l.defined(t.overshootDeringing)&&this._setBooleanOption("jpegOvershootDeringing",t.overshootDeringing);let s=l.bool(t.optimizeScans)?t.optimizeScans:t.optimiseScans;l.defined(s)&&(this._setBooleanOption("jpegOptimiseScans",s),s&&(this.options.jpegProgressive=!0));let i=l.number(t.quantizationTable)?t.quantizationTable:t.quantisationTable;if(l.defined(i))if(l.integer(i)&&l.inRange(i,0,8))this.options.jpegQuantisationTable=i;else throw l.invalidParameterError("quantisationTable","integer between 0 and 8",i)}return this._updateFormatOut("jpeg",t)}function wh(t){if(l.object(t)){if(l.defined(t.progressive)&&this._setBooleanOption("pngProgressive",t.progressive),l.defined(t.compressionLevel))if(l.integer(t.compressionLevel)&&l.inRange(t.compressionLevel,0,9))this.options.pngCompressionLevel=t.compressionLevel;else throw l.invalidParameterError("compressionLevel","integer between 0 and 9",t.compressionLevel);l.defined(t.adaptiveFiltering)&&this._setBooleanOption("pngAdaptiveFiltering",t.adaptiveFiltering);let e=t.colours||t.colors;if(l.defined(e))if(l.integer(e)&&l.inRange(e,2,256))this.options.pngBitdepth=bn(e);else throw l.invalidParameterError("colours","integer between 2 and 256",e);if(l.defined(t.palette)?this._setBooleanOption("pngPalette",t.palette):[t.quality,t.effort,t.colours,t.colors,t.dither].some(l.defined)&&this._setBooleanOption("pngPalette",!0),this.options.pngPalette){if(l.defined(t.quality))if(l.integer(t.quality)&&l.inRange(t.quality,0,100))this.options.pngQuality=t.quality;else throw l.invalidParameterError("quality","integer between 0 and 100",t.quality);if(l.defined(t.effort))if(l.integer(t.effort)&&l.inRange(t.effort,1,10))this.options.pngEffort=t.effort;else throw l.invalidParameterError("effort","integer between 1 and 10",t.effort);if(l.defined(t.dither))if(l.number(t.dither)&&l.inRange(t.dither,0,1))this.options.pngDither=t.dither;else throw l.invalidParameterError("dither","number between 0.0 and 1.0",t.dither)}}return this._updateFormatOut("png",t)}function yh(t){if(l.object(t)){if(l.defined(t.quality))if(l.integer(t.quality)&&l.inRange(t.quality,1,100))this.options.webpQuality=t.quality;else throw l.invalidParameterError("quality","integer between 1 and 100",t.quality);if(l.defined(t.alphaQuality))if(l.integer(t.alphaQuality)&&l.inRange(t.alphaQuality,0,100))this.options.webpAlphaQuality=t.alphaQuality;else throw l.invalidParameterError("alphaQuality","integer between 0 and 100",t.alphaQuality);if(l.defined(t.lossless)&&this._setBooleanOption("webpLossless",t.lossless),l.defined(t.nearLossless)&&this._setBooleanOption("webpNearLossless",t.nearLossless),l.defined(t.smartSubsample)&&this._setBooleanOption("webpSmartSubsample",t.smartSubsample),l.defined(t.smartDeblock)&&this._setBooleanOption("webpSmartDeblock",t.smartDeblock),l.defined(t.preset))if(l.string(t.preset)&&l.inArray(t.preset,["default","photo","picture","drawing","icon","text"]))this.options.webpPreset=t.preset;else throw l.invalidParameterError("preset","one of: default, photo, picture, drawing, icon, text",t.preset);if(l.defined(t.effort))if(l.integer(t.effort)&&l.inRange(t.effort,0,6))this.options.webpEffort=t.effort;else throw l.invalidParameterError("effort","integer between 0 and 6",t.effort);l.defined(t.minSize)&&this._setBooleanOption("webpMinSize",t.minSize),l.defined(t.mixed)&&this._setBooleanOption("webpMixed",t.mixed)}return Sr(t,this.options),this._updateFormatOut("webp",t)}function Eh(t){if(l.object(t)){l.defined(t.reuse)&&this._setBooleanOption("gifReuse",t.reuse),l.defined(t.progressive)&&this._setBooleanOption("gifProgressive",t.progressive);let e=t.colours||t.colors;if(l.defined(e))if(l.integer(e)&&l.inRange(e,2,256))this.options.gifBitdepth=bn(e);else throw l.invalidParameterError("colours","integer between 2 and 256",e);if(l.defined(t.effort))if(l.number(t.effort)&&l.inRange(t.effort,1,10))this.options.gifEffort=t.effort;else throw l.invalidParameterError("effort","integer between 1 and 10",t.effort);if(l.defined(t.dither))if(l.number(t.dither)&&l.inRange(t.dither,0,1))this.options.gifDither=t.dither;else throw l.invalidParameterError("dither","number between 0.0 and 1.0",t.dither);if(l.defined(t.interFrameMaxError))if(l.number(t.interFrameMaxError)&&l.inRange(t.interFrameMaxError,0,32))this.options.gifInterFrameMaxError=t.interFrameMaxError;else throw l.invalidParameterError("interFrameMaxError","number between 0.0 and 32.0",t.interFrameMaxError);if(l.defined(t.interPaletteMaxError))if(l.number(t.interPaletteMaxError)&&l.inRange(t.interPaletteMaxError,0,256))this.options.gifInterPaletteMaxError=t.interPaletteMaxError;else throw l.invalidParameterError("interPaletteMaxError","number between 0.0 and 256.0",t.interPaletteMaxError);if(l.defined(t.keepDuplicateFrames))if(l.bool(t.keepDuplicateFrames))this._setBooleanOption("gifKeepDuplicateFrames",t.keepDuplicateFrames);else throw l.invalidParameterError("keepDuplicateFrames","boolean",t.keepDuplicateFrames)}return Sr(t,this.options),this._updateFormatOut("gif",t)}function Ph(t){if(!this.constructor.format.jp2k.output.buffer)throw mn();if(l.object(t)){if(l.defined(t.quality))if(l.integer(t.quality)&&l.inRange(t.quality,1,100))this.options.jp2Quality=t.quality;else throw l.invalidParameterError("quality","integer between 1 and 100",t.quality);if(l.defined(t.lossless))if(l.bool(t.lossless))this.options.jp2Lossless=t.lossless;else throw l.invalidParameterError("lossless","boolean",t.lossless);if(l.defined(t.tileWidth))if(l.integer(t.tileWidth)&&l.inRange(t.tileWidth,1,32768))this.options.jp2TileWidth=t.tileWidth;else throw l.invalidParameterError("tileWidth","integer between 1 and 32768",t.tileWidth);if(l.defined(t.tileHeight))if(l.integer(t.tileHeight)&&l.inRange(t.tileHeight,1,32768))this.options.jp2TileHeight=t.tileHeight;else throw l.invalidParameterError("tileHeight","integer between 1 and 32768",t.tileHeight);if(l.defined(t.chromaSubsampling))if(l.string(t.chromaSubsampling)&&l.inArray(t.chromaSubsampling,["4:2:0","4:4:4"]))this.options.jp2ChromaSubsampling=t.chromaSubsampling;else throw l.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",t.chromaSubsampling)}return this._updateFormatOut("jp2",t)}function Sr(t,e){if(l.object(t)&&l.defined(t.loop))if(l.integer(t.loop)&&l.inRange(t.loop,0,65535))e.loop=t.loop;else throw l.invalidParameterError("loop","integer between 0 and 65535",t.loop);if(l.object(t)&&l.defined(t.delay))if(l.integer(t.delay)&&l.inRange(t.delay,0,65535))e.delay=[t.delay];else if(Array.isArray(t.delay)&&t.delay.every(l.integer)&&t.delay.every(r=>l.inRange(r,0,65535)))e.delay=t.delay;else throw l.invalidParameterError("delay","integer or an array of integers between 0 and 65535",t.delay)}function xh(t){if(l.object(t)){if(l.defined(t.quality))if(l.integer(t.quality)&&l.inRange(t.quality,1,100))this.options.tiffQuality=t.quality;else throw l.invalidParameterError("quality","integer between 1 and 100",t.quality);if(l.defined(t.bitdepth))if(l.integer(t.bitdepth)&&l.inArray(t.bitdepth,[1,2,4,8]))this.options.tiffBitdepth=t.bitdepth;else throw l.invalidParameterError("bitdepth","1, 2, 4 or 8",t.bitdepth);if(l.defined(t.tile)&&this._setBooleanOption("tiffTile",t.tile),l.defined(t.tileWidth))if(l.integer(t.tileWidth)&&t.tileWidth>0)this.options.tiffTileWidth=t.tileWidth;else throw l.invalidParameterError("tileWidth","integer greater than zero",t.tileWidth);if(l.defined(t.tileHeight))if(l.integer(t.tileHeight)&&t.tileHeight>0)this.options.tiffTileHeight=t.tileHeight;else throw l.invalidParameterError("tileHeight","integer greater than zero",t.tileHeight);if(l.defined(t.miniswhite)&&this._setBooleanOption("tiffMiniswhite",t.miniswhite),l.defined(t.pyramid)&&this._setBooleanOption("tiffPyramid",t.pyramid),l.defined(t.xres))if(l.number(t.xres)&&t.xres>0)this.options.tiffXres=t.xres;else throw l.invalidParameterError("xres","number greater than zero",t.xres);if(l.defined(t.yres))if(l.number(t.yres)&&t.yres>0)this.options.tiffYres=t.yres;else throw l.invalidParameterError("yres","number greater than zero",t.yres);if(l.defined(t.compression))if(l.string(t.compression)&&l.inArray(t.compression,["none","jpeg","deflate","packbits","ccittfax4","lzw","webp","zstd","jp2k"]))this.options.tiffCompression=t.compression;else throw l.invalidParameterError("compression","one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k",t.compression);if(l.defined(t.bigtiff)&&this._setBooleanOption("tiffBigtiff",t.bigtiff),l.defined(t.predictor))if(l.string(t.predictor)&&l.inArray(t.predictor,["none","horizontal","float"]))this.options.tiffPredictor=t.predictor;else throw l.invalidParameterError("predictor","one of: none, horizontal, float",t.predictor);if(l.defined(t.resolutionUnit))if(l.string(t.resolutionUnit)&&l.inArray(t.resolutionUnit,["inch","cm"]))this.options.tiffResolutionUnit=t.resolutionUnit;else throw l.invalidParameterError("resolutionUnit","one of: inch, cm",t.resolutionUnit)}return this._updateFormatOut("tiff",t)}function Rh(t){return this.heif({...t,compression:"av1"})}function $h(t){if(l.object(t)){if(l.string(t.compression)&&l.inArray(t.compression,["av1","hevc"]))this.options.heifCompression=t.compression;else throw l.invalidParameterError("compression","one of: av1, hevc",t.compression);if(l.defined(t.quality))if(l.integer(t.quality)&&l.inRange(t.quality,1,100))this.options.heifQuality=t.quality;else throw l.invalidParameterError("quality","integer between 1 and 100",t.quality);if(l.defined(t.lossless))if(l.bool(t.lossless))this.options.heifLossless=t.lossless;else throw l.invalidParameterError("lossless","boolean",t.lossless);if(l.defined(t.effort))if(l.integer(t.effort)&&l.inRange(t.effort,0,9))this.options.heifEffort=t.effort;else throw l.invalidParameterError("effort","integer between 0 and 9",t.effort);if(l.defined(t.chromaSubsampling))if(l.string(t.chromaSubsampling)&&l.inArray(t.chromaSubsampling,["4:2:0","4:4:4"]))this.options.heifChromaSubsampling=t.chromaSubsampling;else throw l.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",t.chromaSubsampling);if(l.defined(t.bitdepth))if(l.integer(t.bitdepth)&&l.inArray(t.bitdepth,[8,10,12])){if(t.bitdepth!==8&&this.constructor.versions.heif)throw l.invalidParameterError("bitdepth when using prebuilt binaries",8,t.bitdepth);this.options.heifBitdepth=t.bitdepth}else throw l.invalidParameterError("bitdepth","8, 10 or 12",t.bitdepth)}else throw l.invalidParameterError("options","Object",t);return this._updateFormatOut("heif",t)}function Sh(t){if(l.object(t)){if(l.defined(t.quality))if(l.integer(t.quality)&&l.inRange(t.quality,1,100))this.options.jxlDistance=t.quality>=30?.1+(100-t.quality)*.09:53/3e3*t.quality*t.quality-23/20*t.quality+25;else throw l.invalidParameterError("quality","integer between 1 and 100",t.quality);else if(l.defined(t.distance))if(l.number(t.distance)&&l.inRange(t.distance,0,15))this.options.jxlDistance=t.distance;else throw l.invalidParameterError("distance","number between 0.0 and 15.0",t.distance);if(l.defined(t.decodingTier))if(l.integer(t.decodingTier)&&l.inRange(t.decodingTier,0,4))this.options.jxlDecodingTier=t.decodingTier;else throw l.invalidParameterError("decodingTier","integer between 0 and 4",t.decodingTier);if(l.defined(t.lossless))if(l.bool(t.lossless))this.options.jxlLossless=t.lossless;else throw l.invalidParameterError("lossless","boolean",t.lossless);if(l.defined(t.effort))if(l.integer(t.effort)&&l.inRange(t.effort,1,9))this.options.jxlEffort=t.effort;else throw l.invalidParameterError("effort","integer between 1 and 9",t.effort)}return Sr(t,this.options),this._updateFormatOut("jxl",t)}function kh(t){if(l.object(t)&&l.defined(t.depth))if(l.string(t.depth)&&l.inArray(t.depth,["char","uchar","short","ushort","int","uint","float","complex","double","dpcomplex"]))this.options.rawDepth=t.depth;else throw l.invalidParameterError("depth","one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex",t.depth);return this._updateFormatOut("raw")}function Ah(t){if(l.object(t)){if(l.defined(t.size))if(l.integer(t.size)&&l.inRange(t.size,1,8192))this.options.tileSize=t.size;else throw l.invalidParameterError("size","integer between 1 and 8192",t.size);if(l.defined(t.overlap))if(l.integer(t.overlap)&&l.inRange(t.overlap,0,8192)){if(t.overlap>this.options.tileSize)throw l.invalidParameterError("overlap",`<= size (${this.options.tileSize})`,t.overlap);this.options.tileOverlap=t.overlap}else throw l.invalidParameterError("overlap","integer between 0 and 8192",t.overlap);if(l.defined(t.container))if(l.string(t.container)&&l.inArray(t.container,["fs","zip"]))this.options.tileContainer=t.container;else throw l.invalidParameterError("container","one of: fs, zip",t.container);if(l.defined(t.layout))if(l.string(t.layout)&&l.inArray(t.layout,["dz","google","iiif","iiif3","zoomify"]))this.options.tileLayout=t.layout;else throw l.invalidParameterError("layout","one of: dz, google, iiif, iiif3, zoomify",t.layout);if(l.defined(t.angle))if(l.integer(t.angle)&&!(t.angle%90))this.options.tileAngle=t.angle;else throw l.invalidParameterError("angle","positive/negative multiple of 90",t.angle);if(this._setBackgroundColourOption("tileBackground",t.background),l.defined(t.depth))if(l.string(t.depth)&&l.inArray(t.depth,["onepixel","onetile","one"]))this.options.tileDepth=t.depth;else throw l.invalidParameterError("depth","one of: onepixel, onetile, one",t.depth);if(l.defined(t.skipBlanks))if(l.integer(t.skipBlanks)&&l.inRange(t.skipBlanks,-1,65535))this.options.tileSkipBlanks=t.skipBlanks;else throw l.invalidParameterError("skipBlanks","integer between -1 and 255/65535",t.skipBlanks);else l.defined(t.layout)&&t.layout==="google"&&(this.options.tileSkipBlanks=5);let e=l.bool(t.center)?t.center:t.centre;if(l.defined(e)&&this._setBooleanOption("tileCentre",e),l.defined(t.id))if(l.string(t.id))this.options.tileId=t.id;else throw l.invalidParameterError("id","string",t.id);if(l.defined(t.basename))if(l.string(t.basename))this.options.tileBasename=t.basename;else throw l.invalidParameterError("basename","string",t.basename)}if(l.inArray(this.options.formatOut,["jpeg","png","webp"]))this.options.tileFormat=this.options.formatOut;else if(this.options.formatOut!=="input")throw l.invalidParameterError("format","one of: jpeg, png, webp",this.options.formatOut);return this._updateFormatOut("dz")}function _h(t){if(!l.plainObject(t))throw l.invalidParameterError("options","object",t);if(l.integer(t.seconds)&&l.inRange(t.seconds,0,3600))this.options.timeoutSeconds=t.seconds;else throw l.invalidParameterError("seconds","integer between 0 and 3600",t.seconds);return this}function Nh(t,e){return l.object(e)&&e.force===!1||(this.options.formatOut=t),this}function Ih(t,e){if(l.bool(e))this.options[t]=e;else throw l.invalidParameterError(t,"boolean",e)}function Fh(){if(!this.options.streamOut){this.options.streamOut=!0;let t=Error();this._pipeline(void 0,t)}}function Ch(t,e){return typeof t=="function"?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),Ze.pipeline(this.options,(r,s,i)=>{r?t(l.nativeError(r,e)):t(null,s,i)})}):Ze.pipeline(this.options,(r,s,i)=>{r?t(l.nativeError(r,e)):t(null,s,i)}),this):this.options.streamOut?(this._isStreamInput()?(this.once("finish",()=>{this._flattenBufferIn(),Ze.pipeline(this.options,(r,s,i)=>{r?this.emit("error",l.nativeError(r,e)):(this.emit("info",i),this.push(s)),this.push(null),this.on("end",()=>this.emit("close"))})}),this.streamInFinished&&this.emit("finish")):Ze.pipeline(this.options,(r,s,i)=>{r?this.emit("error",l.nativeError(r,e)):(this.emit("info",i),this.push(s)),this.push(null),this.on("end",()=>this.emit("close"))}),this):this._isStreamInput()?new Promise((r,s)=>{this.once("finish",()=>{this._flattenBufferIn(),Ze.pipeline(this.options,(i,n,a)=>{i?s(l.nativeError(i,e)):this.options.resolveWithObject?r({data:n,info:a}):r(n)})})}):new Promise((r,s)=>{Ze.pipeline(this.options,(i,n,a)=>{i?s(l.nativeError(i,e)):this.options.resolveWithObject?r({data:n,info:a}):r(n)})})}vn.exports=t=>{Object.assign(t.prototype,{toFile:ah,toBuffer:oh,keepExif:lh,withExif:ch,withExifMerge:hh,keepIccProfile:uh,withIccProfile:fh,keepXmp:dh,withXmp:gh,keepMetadata:ph,withMetadata:mh,toFormat:bh,jpeg:vh,jp2:Ph,png:wh,webp:yh,tiff:xh,avif:Rh,heif:$h,jxl:Sh,gif:Eh,raw:kh,tile:Ah,timeout:_h,_updateFormatOut:Nh,_setBooleanOption:Ih,_read:Fh,_pipeline:Ch})}});var xn=x((Af,Pn)=>{var Dh=I("node:events"),Tt=xt(),Z=ie(),{runtimePlatformArch:jh}=pr(),B=ft(),yn=jh(),kr=B.libvipsVersion(),Ae=B.format();Ae.heif.output.alias=["avif","heic"];Ae.jpeg.output.alias=["jpe","jpg"];Ae.tiff.output.alias=["tif"];Ae.jp2k.output.alias=["j2c","j2k","jp2","jpx"];var Th={nearest:"nearest",bilinear:"bilinear",bicubic:"bicubic",locallyBoundedBicubic:"lbb",nohalo:"nohalo",vertexSplitQuadraticBasisSpline:"vsqbs"},et={vips:kr.semver};if(!kr.isGlobal)if(kr.isWasm)try{et=I("@img/sharp-wasm32/versions")}catch{}else try{et=I(`@img/sharp-${yn}/versions`)}catch{try{et=I(`@img/sharp-libvips-${yn}/versions`)}catch{}}et.sharp=dr().version;et.heif&&Ae.heif&&(Ae.heif.input.fileSuffix=[".avif"],Ae.heif.output.alias=["avif"]);function En(t){return Z.bool(t)?t?B.cache(50,20,100):B.cache(0,0,0):Z.object(t)?B.cache(t.memory,t.files,t.items):B.cache()}En(!0);function Lh(t){return B.concurrency(Z.integer(t)?t:null)}Tt.familySync()===Tt.GLIBC&&!B._isUsingJemalloc()?B.concurrency(1):Tt.familySync()===Tt.MUSL&&B.concurrency()===1024&&B.concurrency(I("node:os").availableParallelism());var Oh=new Dh.EventEmitter;function Mh(){return B.counters()}function zh(t){return B.simd(Z.bool(t)?t:null)}function Bh(t){if(Z.object(t))if(Array.isArray(t.operation)&&t.operation.every(Z.string))B.block(t.operation,!0);else throw Z.invalidParameterError("operation","Array<string>",t.operation);else throw Z.invalidParameterError("options","object",t)}function Uh(t){if(Z.object(t))if(Array.isArray(t.operation)&&t.operation.every(Z.string))B.block(t.operation,!1);else throw Z.invalidParameterError("operation","Array<string>",t.operation);else throw Z.invalidParameterError("options","object",t)}Pn.exports=t=>{t.cache=En,t.concurrency=Lh,t.counters=Mh,t.simd=zh,t.format=Ae,t.interpolators=Th,t.versions=et,t.queue=Oh,t.block=Bh,t.unblock=Uh}});var $n=x((Nf,Rn)=>{var Ee=Li();zi()(Ee);Wi()(Ee);Ji()(Ee);Zi()(Ee);fn()(Ee);gn()(Ee);wn()(Ee);xn()(Ee);Rn.exports=Ee});var it={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},Mr={available:["auth","oauth","billing","crud"],packageNames:{auth:"@donotdev/auth",oauth:"@donotdev/oauth",billing:"@donotdev/billing",crud:"@donotdev/crud"},hooks:{auth:["useAuth"],oauth:["useOAuth","useOAuthPartner","useOAuthConnection"],billing:["useStripeBilling","useStripeCheckout"],crud:["useCrud","useCrudCollection"]}};var re={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},De={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Vt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},nt={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},mt={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},K={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${mt.SOURCE_EAGER}/*_*.json`],lazy:[`${mt.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},bt={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async","@donotdev/core","@donotdev/components","@donotdev/ui","@donotdev/templates","@donotdev/firebase"],optionalFeatures:["@donotdev/components","@donotdev/auth","@donotdev/billing","@donotdev/crud","@donotdev/oauth","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder"],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},zr=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var Jt={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}},at={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},Xt=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Or={base:{absolute:!0,onlyFiles:!0,ignore:K.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...K.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...K.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:K.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:K.globalIgnore}};function Br(t,e=null){let r=K[t];if(!r)throw new Error(`Unknown pattern type: ${t}`);return e&&r.framework?{...r,framework:r.framework.map(s=>`${e}/${s}`)}:r}function vt(t){return Or[t]||Or.base}import*as $ from"node:fs";import"node:fs";import{createRequire as ha}from"node:module";import{resolve as wt,join as me,dirname as xe,relative as Ur,normalize as ua,sep as qr,extname as fa}from"node:path";import{fileURLToPath as da}from"node:url";import ga from"fast-glob";var qe={getGlobOptionsFor:vt||void 0,SCAN_PATTERNS:K||void 0,getPatternsFor:Br||void 0,I18N_PATHS:mt||void 0},T={error:(t,e)=>{},warn:(t,e)=>{},info:t=>{}};function Gr(t,e){return t().catch(r=>{throw new Error(`${e}: ${r instanceof Error?r.message:String(r)}`)})}var Hr={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},D=class t{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return t._instance||(t._instance=new t(e)),t._instance}static _reset(){t._instance=null}constructor(e={}){if(t._instance)return t._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let r=process.cwd();if(!r)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(r)}catch(r){throw new Error(`PathResolver constructor failed: ${r instanceof Error?r.message:String(r)}. cwd: ${process.cwd()}`)}this._appRoot=null,t._instance=this}normalizePath(e){if(!e)return"";try{return ua(e).split(qr).join("/")}catch{return String(e).split(qr).join("/")}}getRelativePath(e){let r=this.getAppRoot(),s=Ur(r,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(xe(e)):""}resolvePackage(e,r=null){try{let s=r||this.getAppRoot(),n=ha(me(s,"package.json")).resolve(e);return this.normalizePath(n)}catch{return null}}resolveFrameworkPackage(e,r=null){let s=this.resolvePackage(`${e}/package.json`,r);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),o=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(o))return o;if(["auth","billing","crud","oauth"].includes(a)){let c=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(c))return c}if(a==="firebase"){let c=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(c))return c}}let i=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(i))return i;let n=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(n)?n:null}resolvePackageAsset(e,r=null){return this.resolvePackage(e,r)}resolveAppPath(e){let r=this.getAppRoot(),s=wt(r,e);return this.normalizePath(s)}resolveRepoPath(e){let r=this.getRepoRoot(),s=this.normalizePath(e),i=wt(r,s);return this.normalizePath(i)}resolvePath(e,r){let s=this.normalizePath(r),i=this.normalizePath(e),n=wt(s,i);return this.normalizePath(n)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let r=$.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:r.size,isFile:r.isFile(),isDirectory:r.isDirectory()}}catch{return null}}_detectFormat(e,r){return r&&r!=="auto"?r:fa(e).toLowerCase()===".json"?"json":"text"}async read(e,r={}){let{format:s="auto",encoding:i="utf8"}=r,n=this._detectFormat(e,s);try{if(n==="buffer")return await $.promises.readFile(e);let a=await $.promises.readFile(e,i),o=this.stripBom(a);return n==="json"?JSON.parse(o):o}catch(a){return this.options.debug&&T.warn(`Failed to read file: ${e}`,a),null}}readSync(e,r={}){let{format:s="auto",encoding:i="utf8"}=r,n=this._detectFormat(e,s);try{if(n==="buffer")return $.readFileSync(e);let a=$.readFileSync(e,i),o=this.stripBom(a);return n==="json"?JSON.parse(o):o}catch(a){return this.options.debug&&T.warn(`Failed to read file: ${e}`,a),null}}async write(e,r,s={}){let{format:i="auto",overwrite:n=!1,dryRun:a=!1,verbose:o=!1}=s,c=this.normalizePath(e),h=this.normalizePath(xe(c)),f=this.pathExists(c);if(f&&!n)return o&&T.info(`Skipping existing file: ${c}`),!1;if(a)return T.info(`[DRY RUN] Would write file: ${c}`),!0;try{await $.promises.mkdir(h,{recursive:!0})}catch(p){if(p?.code!=="EEXIST")throw p}let g=this._detectFormat(e,i),m;Buffer.isBuffer(r)?m=r:g==="json"&&typeof r=="object"?m=JSON.stringify(r,null,2):m=String(r);try{return await Gr(async()=>(Buffer.isBuffer(m)?await $.promises.writeFile(c,m):await $.promises.writeFile(c,m,"utf8"),o&&T.info(`${f?"Updated":"Created"} file: ${c}`),!0),`Failed to write file: ${c}`)}catch{return!1}}writeSync(e,r,s={}){let{format:i="auto",overwrite:n=!1,dryRun:a=!1,verbose:o=!1}=s,c=this.normalizePath(e),h=this.normalizePath(xe(c)),f=this.pathExists(c);if(f&&!n)return o&&T.info(`Skipping existing file: ${c}`),!1;if(a)return T.info(`[DRY RUN] Would write file: ${c}`),!0;try{$.mkdirSync(h,{recursive:!0})}catch(p){if(p?.code!=="EEXIST")throw p}let g=this._detectFormat(e,i),m;Buffer.isBuffer(r)?m=r:g==="json"&&typeof r=="object"?m=JSON.stringify(r,null,2):m=String(r);try{return Buffer.isBuffer(m)?$.writeFileSync(c,m):$.writeFileSync(c,m,"utf8"),o&&T.info(`${f?"Updated":"Created"} file: ${c}`),!0}catch(p){throw new Error(`Failed to write file: ${c}: ${p instanceof Error?p.message:String(p)}`)}}async copy(e,r,s={}){let{overwrite:i=!1,dryRun:n=!1,verbose:a=!1}=s,o=this.normalizePath(r),c=this.pathExists(o);if(c&&!i)return a&&T.info(`Skipping existing file: ${o}`),!1;if(n)return T.info(`[DRY RUN] Would copy file: ${o}`),!0;let h=this.normalizePath(xe(o));try{await $.promises.mkdir(h,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}try{return await Gr(async()=>(await $.promises.copyFile(e,o),a&&T.info(`${c?"Updated":"Created"} file: ${o}`),!0),`Failed to copy file from ${e} to ${o}`)}catch{return!1}}copySync(e,r,s={}){let{overwrite:i=!1,dryRun:n=!1,verbose:a=!1}=s,o=this.normalizePath(r),c=this.pathExists(o);if(c&&!i)return a&&T.info(`Skipping existing file: ${o}`),!1;if(n)return T.info(`[DRY RUN] Would copy file: ${o}`),!0;let h=this.normalizePath(xe(o));try{$.mkdirSync(h,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}try{return $.copyFileSync(e,o),a&&T.info(`${c?"Updated":"Created"} file: ${o}`),!0}catch{return!1}}pathExists(e,r=!1){try{return $.existsSync(e)}catch(s){return r||T.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let r=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return $.existsSync(r)||$.mkdirSync(r,{recursive:!0}),!0}catch{return!1}}readdirSync(e,r){try{return $.readdirSync(e,r)}catch(s){return this.options.debug&&T.warn(`Failed to read directory: ${e}`,s),r&&typeof r=="object"&&"withFileTypes"in r&&r.withFileTypes?[]:[]}}statSync(e){try{return $.statSync(e)}catch(r){return this.options.debug&&T.warn(`Failed to stat file: ${e}`,r),null}}lstatSync(e){try{return $.lstatSync(e)}catch(r){return this.options.debug&&T.warn(`Failed to lstat file: ${e}`,r),null}}async ensureDir(e){try{await $.promises.mkdir(e,{recursive:!0})}catch(r){if(r?.code!=="EEXIST")throw r}}ensureDirSync(e){try{$.mkdirSync(e,{recursive:!0})}catch(r){if(r?.code!=="EEXIST")throw r}}async remove(e){await $.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){$.rmSync(e,{recursive:!0,force:!0})}async readdir(e,r){return $.promises.readdir(e,r)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=me(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let r=this.normalizePath(wt(e)),s=this.getAppRoot(),i=Ur(s,r),n=this.normalizePath(i);return!n.startsWith("../")&&!n.startsWith("/")}async findFiles(e,r,s={}){let i=this.normalizePath(me(e,r)),n=this.getAppRoot(),a=this.normalizePath(n),o=i.startsWith(a)?i.slice(a.length+1):i,c={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:qe.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([o],{...c,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let r=qe.I18N_PATHS;if(!r)return null;let s=e.replace(r.SOURCE_ROOT+"/",""),i=this.resolveFrameworkPackage("@donotdev/core");if(!i)return null;let n=this.normalizePath(me(i,r.PUBLISHED_ROOT,s)),a=n.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),n}async _globWithNormalization(e,r){return(await ga(e,r)).map(i=>{let n=typeof i=="string"?i:i.path;return this.normalizePath(n)})}async resolveFiles(e,r="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(r==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let f of s)if(typeof f!="string"||f.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let i=this.getAppRoot(),n=qe.getGlobOptionsFor?qe.getGlobOptionsFor(r):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(i),o=e.framework.map(f=>{let g=this.normalizePath(f);return g.startsWith(a)?g.slice(a.length+1):g}),c=e.consumer.map(f=>{let g=this.normalizePath(f);return g.startsWith(a)?g.slice(a.length+1):g}),h={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:i};try{let f=o.length>0?await this._globWithNormalization(o,h):[],g=await this._globWithNormalization(c,h);return{frameworkFiles:f,consumerFiles:g}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!qe.getPatternsFor)return{framework:[],consumer:[],all:[]};let r=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!r||r===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${r}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let i=qe.getPatternsFor(e),n=this.isMonorepo();if(e==="i18n"){let c=i,h={eager:c.eager.map(f=>f.startsWith("!")?"!"+this.resolveAppPath(f.slice(1)):this.resolveAppPath(f)),lazy:c.lazy.map(f=>f.startsWith("!")?"!"+this.resolveAppPath(f.slice(1)):this.resolveAppPath(f)),framework:{eager:n?(c.framework?.eager||[]).map(f=>this.resolveRepoPath(f)).filter(Boolean):await Promise.all((c.framework?.eager||[]).map(f=>this._resolveFrameworkI18nPattern(f))).then(f=>f.filter(Boolean)),lazy:n?(c.framework?.lazy||[]).map(f=>this.resolveRepoPath(f)).filter(Boolean):await Promise.all((c.framework?.lazy||[]).map(f=>this._resolveFrameworkI18nPattern(f))).then(f=>f.filter(Boolean))},all:[]};return h.all=[...h.eager,...h.lazy,...h.framework.eager,...h.framework.lazy],h}let a=i,o={framework:n?(a.framework||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):[],consumer:(a.consumer||[]).map(c=>this.resolveAppPath(c)),all:[]};return o.all=[...o.consumer,...o.framework],o}getEmptyModulePath(e=!1){if(e)return"@donotdev/core/empty";let r=this.resolvePackage("@donotdev/core/empty");if(r)return r;let s=xe(da(import.meta.url));return this.normalizePath(me(s,"../empty.js"))}_findRepoRoot(e){let r=this.normalizePath(e),s=0,i=this.options.maxLevels;for(;s<i;){let n=this.normalizePath(me(r,Hr.TOOLING)),a=this.normalizePath(me(r,Hr.CORE));if(this.pathExists(n)&&this.pathExists(a))return r;let o=me(r,"apps");if(this.pathExists(o)&&this.statSync(o)?.isDirectory())return this.normalizePath(r);let c=this.normalizePath(me(r,"package.json"));if(this.pathExists(c)&&this.normalizePath(xe(r))===r)return r;let h=this.normalizePath(xe(r));if(h===r)break;r=h,s++}return this.normalizePath(e)}};function Wr({logger:t,debug:e=!1}={}){let r=D.getInstance(),s=!1,i=null;if(process.env.DNDEV_APP_ROOT?(i=r.normalizePath(process.env.DNDEV_APP_ROOT),r.pathExists(i)?(r.setAppRoot(i),s=!0,e&&t&&t.debug(`App root set from DNDEV_APP_ROOT: ${i}`)):t&&t.warn(`DNDEV_APP_ROOT path does not exist: ${i}`)):e&&t&&t.debug("DNDEV_APP_ROOT env var not set"),!s){if(r.getRepoRoot()){let a=r.resolveRepoPath("apps");if(r.pathExists(a))try{let o=process.cwd(),c=r.normalizePath(o);if(c.includes("/apps/")){let h=c.indexOf("/apps/"),g=c.substring(h+6).split("/")[0];if(g){let m=r.resolveRepoPath(`apps/${g}`),p=r.resolveRepoPath(`apps/${g}/next.config.js`);r.pathExists(p)&&(i=m,r.setAppRoot(i),s=!0,e&&t&&t.debug(`App root detected from process.cwd(): ${i}`))}}}catch{}}!s&&!i&&(i=process.cwd(),r.setAppRoot(i),s=!0,e&&t&&t.debug(`App root fallback to process.cwd(): ${i}`))}return{appRoot:i,appRootSet:s}}function Vr(){try{let t=D.getInstance(),e=t.resolveAppPath("package.json"),r=t.readSync(e,{format:"json"});if(!r)return[];let s={...r.dependencies,...r.devDependencies};return Object.keys(s).filter(n=>{let a=n.startsWith("@donotdev/"),o=n==="entities",c=s[n]&&typeof s[n]=="string"&&s[n].startsWith("workspace:");return a||o||c}).filter(n=>!bt.buildTimePackages.includes(n)).sort()}catch{return[]}}function be(t){return t&&typeof t=="object"&&!Array.isArray(t)}import Yt from"node:fs";import Xr from"node:path";var Jr=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,Re=class{constructor(e,r={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...r},this.logger=r.logger||{debug:(s,...i)=>{this.options.debug}},this.patterns={selectors:{...Jt.selectors,...this.options.customPatterns?.selectors},themes:{...Jt.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let r=e.replace(/^--/,"");if(!r)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=r.split("-").filter(a=>a.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let i=s.map((a,o)=>{let c=a.replace(/[^a-zA-Z0-9]/g,"");return c?o===0?c.toLowerCase():c.charAt(0).toUpperCase()+c.slice(1).toLowerCase():null}).filter(Boolean).join("");return!i||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(i)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${i}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(i)?`${i}Var`:i}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,r,s){let i=[],n,a=this.pathResolver.normalizePath(r),o=this._stripComments(e),c=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(n=c.exec(o))!==null;){let[,h,f,g]=n;if(!h||!g)continue;let m=f.match(this.patterns.themes.themeIcon),p=f.match(this.patterns.themes.themeIsDark),R={name:h,displayName:g,isDark:p?p[1]==="1":!1,meta:{icon:m?.[1]},source:this.pathResolver.getBasename(r)};this._debug(`Discovered theme: ${h} (${g})`),i.push(R),s.themes.set(h,{name:h,displayName:g,isDark:R.isDark,file:a,variables:new Set,meta:R.meta})}return i.length>0&&this._debug(`Extracted ${i.length} themes from ${a}`),i}extractClasses(e,r){(e.match(this.patterns.selectors.class)||[]).forEach(i=>{let n=i.slice(1);n.startsWith("_")||r.classes.add(n)})}extractVariables(e,r,s){(e.match(this.patterns.selectors.variable)||[]).forEach(n=>{n.startsWith("--")&&n.length>2?s==="framework"?r.variables.framework.add(n):r.variables.consumer.add(n):this._debug(`Skipping invalid CSS variable: ${n}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let r=this._stripComments(e),s=new Set,i;for(Jr.lastIndex=0;(i=Jr.exec(r))!==null;){let n=i[1];n&&n.trim()&&s.add(n.trim())}return Array.from(s)}extractKeyframes(e,r){(e.match(this.patterns.selectors.keyframe)||[]).forEach(i=>{let n=i.replace("@keyframes","").trim();n&&r.keyframes.add(n)})}validateCSS(e){let r=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(n=>{r.push(`Possible malformed CSS variable: ${n}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(n=>{if(!n.includes("--theme-label")&&n.includes("--")){let a=n.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&r.push(`Theme class "${a}" missing --theme-label`)}}),r}extractAll(e,r,s="consumer"){let i={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},n=this.extractThemes(e,r,i);this.extractClasses(e,i),this.extractVariables(e,i,s),this.extractKeyframes(e,i);let a=this.validateCSS(e);return{themes:n,classes:Array.from(i.classes),variables:{framework:Array.from(i.variables.framework),consumer:Array.from(i.variables.consumer),all:[...Array.from(i.variables.framework),...Array.from(i.variables.consumer)].sort()},keyframes:Array.from(i.keyframes),warnings:a}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,r){this.logger.debug(e,r||"")}};var q;try{q=await import("@clack/prompts")}catch{q={log:{message:t=>{},info:t=>{},warn:t=>{},error:t=>{},success:t=>{},step:t=>{}}}}var ee={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function pa(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function se(t,e){return pa()?`${e}${t}${ee.reset}`:t}function W(t,e,r,s={}){let{logDir:i=".dndev-logs",fileLogging:n=!1}=s,a=D.getInstance(),o=null;if(n){let f=a.resolveAppPath(i);a.pathExists(f)||a.mkdir(f),o=a.resolveAppPath(`${i}/${t.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let g=`=== ${t} Log Started at ${new Date().toISOString()} ===
3
- `;a.writeSync(o,g)}let c=(f,g,m)=>{if(o){let p=new Date().toISOString(),R=m.length>0?" "+m.map(J=>typeof J=="object"?JSON.stringify(J,null,2):String(J)).join(" "):"",C=`${p} [${f}] ${g}${R}
4
- `;a.appendFile(o,C)}},h=(f,g)=>{if(g.length===0)return f;let m=g.map(p=>typeof p=="object"?JSON.stringify(p,null,2):String(p)).join(" ");return`${f} ${m}`};return{debug:(f,...g)=>{e&&(n?c("DEBUG",f,g):q.log.message(se(h(f,g),ee.gray)))},verbose:(f,...g)=>{r&&(n?c("VERBOSE",f,g):q.log.message(h(f,g)))},info:(f,...g)=>{n?c("INFO",f,g):q.log.info(se(h(f,g),ee.brightCyan))},warn:(f,...g)=>{e&&n?c("WARN",f,g):q.log.warn(se(h(f,g),ee.brightYellow))},error:(f,...g)=>{e&&n?c("ERROR",f,g):q.log.error(se(h(f,g),ee.brightRed))},success:(f,...g)=>{e&&n?c("SUCCESS",f,g):q.log.success(se(h(f,g),ee.brightGreen))},when:(f,g="debug")=>(m,...p)=>{if(f){let R=h(m,p);switch(g){case"verbose":r&&(q.log.message(R),c("VERBOSE",m,p));break;case"info":q.log.info(se(R,ee.brightCyan)),c("INFO",m,p);break;case"warn":q.log.warn(se(R,ee.brightYellow)),c("WARN",m,p);break;case"error":q.log.error(se(R,ee.brightRed)),c("ERROR",m,p);break;case"success":q.log.success(se(R,ee.brightGreen)),c("SUCCESS",m,p);break;default:e&&(q.log.message(se(R,ee.gray)),c("DEBUG",m,p))}}},getLogFilePath:()=>o}}var ma=3,Yr="dndev-font-preloads.json";async function ba(t,e){let r=W("font-preload-next",e,!1);try{let s=await t.resolvePatterns("css"),{consumerFiles:i}=await t.resolveFiles(s,"css");if(!i?.length)return[at.Inter];let n=new Re(t,{debug:e,logger:r}),a=new Set;for(let c of i)try{let h=await t.read(c,{format:"text"});h&&n.extractFontFamilies(h).forEach(f=>a.add(f))}catch{}if(a.size===0)return[at.Inter];let o=new Set;for(let c of a){let h=at[c];h&&o.add(h)}return Array.from(o)}catch{return[at.Inter]}}function Kr({pathResolver:t,debug:e=!1}){let r=W("font-preload-next",e,!1);return{apply(s){s.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(i,n)=>{if(i.compiler.isChild()||i.compiler.name?.includes("server"))return n();try{let o=t.getAppRoot();if(!o)return n();let c=await ba(t,e),h=i.outputOptions.publicPath&&String(i.outputOptions.publicPath)!=="auto"?i.outputOptions.publicPath.replace(/\/$/,""):"",f=[];for(let[p]of Object.entries(i.assets)){if(!p.endsWith(".woff2")&&!p.endsWith(".woff"))continue;let R=p.toLowerCase();if(c.some(C=>R.includes(C))){let C=h?`${h}/${p}`:`/${p}`;if(f.push({href:C,type:"font/woff2"}),f.length>=ma)break}}let g=Xr.join(o,"public");if(!Yt.existsSync(g))try{Yt.mkdirSync(g,{recursive:!0})}catch(p){return r.debug(`Font preload: could not create public dir: ${p?.message}`),n()}let m=Xr.join(g,Yr);Yt.writeFileSync(m,JSON.stringify(f,null,0),"utf8"),r.debug(`Font preload: wrote ${f.length} entries to ${Yr}`)}catch(o){r.debug(`Font preload manifest: ${o?.message}`)}n()})}}}function Qr({originalWebpack:t,unusedFeaturePackages:e,usedFeaturePackages:r,logger:s,debug:i}){return(n,a)=>{let{dev:o,isServer:c,webpack:h}=a;o&&!c&&(n.infrastructureLogging={level:"error"},n.stats={...n.stats,logging:"error",loggingTrace:!1},n.ignoreWarnings=[...n.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let f=n.module?.rules?.find(g=>g.test?.test?.(".svg"));f&&(f.exclude=/\.svg$/i),n.module=n.module||{},n.module.rules=n.module.rules||[],n.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),h?.IgnorePlugin&&n.plugins.push(new h.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let g=D.getInstance();n.plugins.push(Kr({pathResolver:g,debug:i}))}catch(g){s.debug(`Font preload webpack plugin skipped: ${g?.message}`)}if(e.length>0)if(s.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),s.info(`\u2705 Including features: ${r.join(", ")}`),n.externals=n.externals||[],Array.isArray(n.externals))n.externals.push(...e);else{let g=n.externals;n.externals=(m,p,R)=>e.includes(p)?R(null,"commonjs "+p):typeof g=="function"?g(m,p,R):R()}return t?t(n,a):n}}function Zr({originalRewrites:t,handlers:e,logger:r}){return async function(){try{let s=t?await t():[],n=e.filter(o=>o?.getAPIRewrites).map(o=>o.getAPIRewrites()).reduce((o,c)=>(c?.beforeFiles&&o.beforeFiles.push(...c.beforeFiles),c?.afterFiles&&o.afterFiles.push(...c.afterFiles),c?.fallback&&o.fallback.push(...c.fallback),o),{beforeFiles:[],afterFiles:[],fallback:[]}),a={beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...n.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...n.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...n.fallback]};return a.beforeFiles.length===0&&a.afterFiles.length===0&&a.fallback.length===0?null:a}catch(s){return r.error(`Next.js config failed to merge rewrites: ${s.message}`),r.error(`Stack: ${s.stack||"No stack trace available"}`),null}}}function es({routeResult:t,themeResult:e,i18nResult:r,assetResult:s,seoResult:i,pwaResult:n,serverShimResult:a,restNextConfig:o,discoveredPackages:c,webpackConfig:h,rewritesConfig:f,missingOptionalDeps:g,env:m,logger:p}){let R=o?.output==="export",J=o?.distDir||".next";return{transpilePackages:c,...o?.serverExternalPackages||o?.serverComponentsExternalPackages?{serverExternalPackages:(o?.serverExternalPackages||o?.serverComponentsExternalPackages||[]).filter(ue=>!ue.startsWith("@donotdev/"))}:{},...be(o)?o:(p.warn("restNextConfig is not a plain object:",o),{}),distDir:J,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...be(t)?t:(p.error(`Route handler config invalid (got ${typeof t}):`,t),{}),...be(e)?e:(p.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...be(r)?r:(p.error(`I18n handler config invalid (got ${typeof r}):`,r),{}),...be(s)?s:(p.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...be(i)?i:(p.error(`SEO handler config invalid (got ${typeof i}):`,i),{}),...be(n)?n:(p.error(`PWA handler config invalid (got ${typeof n}):`,n),{}),...be(a)?a:(p.warn("serverShimConfig returned non-object:",a),{}),webpack:h,...R?{}:{rewrites:async()=>await f()||void 0},env:m,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var va=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json"],wa="dndev-config-",ts=".dndev-build";function ya(t){if(!t)return!1;let e=D.getInstance(),r=e.resolveAppPath(ts),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(r,{format:"text"})||"").trim()===s}catch{return!1}}function Ea(t){if(!t)return;let e=D.getInstance(),r=e.resolveAppPath(ts),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(r,s)}catch{}}function Kt(t,e){if(!t)return;let r=D.getInstance();for(let i of va){let n=r.resolveAppPath(i);if(r.pathExists(n))try{r.removeSync(n),e.debug(`Cleaned: ${i}`)}catch{}}let s=r.resolveAppPath("src/config");if(r.pathExists(s))try{let i=r.readdirSync(s);for(let n of i)if(n.startsWith(wa)&&n.endsWith(".js"))try{let a=r.resolvePath(n,s);r.removeSync(a),e.debug(`Cleaned: src/config/${n}`)}catch{}}catch{}}async function Qt({routeHandler:t,themeHandler:e,i18nHandler:r,assetHandler:s,seoHandler:i,pwaHandler:n},a){let o=t?.pathResolver;if(!o)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let c=o.getAppRoot(),h=o.getRepoRoot();if(!c||c===h){a.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(R=>setTimeout(R,0));let p=o.getAppRoot();if(!p||p===h)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(ya(c)){a.debug("Discoveries already completed this build, skipping");return}let f=Date.now();if(t)try{a.info("\u{1F50D} Starting route discovery...");let R=(await t.generateFiles())?.routes?.length||0;a.info(`\u2705 Routes generated: ${R} routes found`),R===0&&a.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(p){throw a.error(`\u274C Route generation failed: ${p.message}`),p.stack&&a.error(`Stack: ${p.stack}`),p}else a.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let g=[{name:"Theme",handler:e},{name:"I18n",handler:r},{name:"Asset",handler:s},{name:"SEO",handler:i},{name:"PWA",handler:n}];for(let{name:p,handler:R}of g)try{await R.generateFiles()}catch(C){a.debug(`${p} generation failed: ${C.message}`)}let m=Date.now()-f;a.verbose?.(`\u2705 All discoveries completed in ${m}ms - Next.js can now compile`),Ea(c)}async function rs(t,e,r){if(r)return!1;try{let s=await t.getDiscoveryData();return s?.copiedAssets?.length>0&&e.info(`\u{1F4E6} Copied ${s.copiedAssets.length} assets from framework`),!0}catch(s){return e.debug(`Asset discovery failed (non-critical): ${s.message}`),!1}}var ot={debug:!1,verbose:process.env.CI!=="true",features:{},generateManifest:!0,routes:{disabled:!1,debug:!1,routingMode:"app",generateMiddleware:!0},themes:{debug:!1},i18n:{debug:!1,fallbackLanguage:"en"},assets:{debug:!1},pwa:{debug:!1},seo:{disabled:!1,debug:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0,debug:!1},discovery:{debug:!1,verbose:!1,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"}};function ss(t,e){let r={...t};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?r[s]=ss(t[s]||{},e[s]):r[s]=e[s]}),r}function is(t={}){return ss(ot,t)}function ns(t){let{features:e={},routes:r={},themes:s={},i18n:i={},assets:n={},pwa:a={},seo:o={},serverShim:c={},discovery:h={},generateManifest:f,debug:g,verbose:m,...p}=t,R=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:f,debug:g,verbose:m,mode:R,isDev:R==="development",routeOptions:r,themeOptions:s,i18nOptions:i,assetOptions:n,featureOptions:e,pwaOptions:a,seoOptions:o,serverShimOptions:c,discoveryOptions:h,nextConfigOptions:p}}var G=class{constructor(e,r={}){this.options={...r,...this.getHandlerDefaults()},this.logger=W(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=D.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let r={...ot.discovery,...this.options};return new e(this.pathResolver,r)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}createNextConfig(){return(e={})=>(this.options.debug&&this.logger.debug(`${this.getHandlerName()} handler initialized`),{...e,webpack:(r,s)=>{let{dev:i,isServer:n,webpack:a}=s;return this.applyViteIgnorePlugin(r,a),this._generateFiles(),e.webpack?e.webpack(r,s):r},rewrites:async function(){try{let r=e.rewrites?await e.rewrites():[],s=this.getAPIRewrites();return this.mergeRewrites(r,s)}catch(r){return this.logger.error(`${this.getHandlerName()} handler failed to merge rewrites: ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`),[]}}.bind(this)})}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let r=this.getHandlerName().toLowerCase(),s=De.next[`config${r.charAt(0).toUpperCase()}${r.slice(1)}`];if(!s)throw new Error(`No config path defined for ${r} handler. Add config${r.charAt(0).toUpperCase()}${r.slice(1)} to GENERATED_PATHS.next in constants.js`);let i=this.generateConfigContent(e);this.writeGeneratedFile(s,i,`DnDev ${r} config`)}generateConfigContent(e){let r=this.getHandlerName().toLowerCase(),s=re[r]||r;return`// Auto-generated DnDev config by @donotdev/config
1
+ var ae={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},Ge={available:["auth","oauth","billing","crud"],packageNames:{auth:"@donotdev/auth",oauth:"@donotdev/oauth",billing:"@donotdev/billing",crud:"@donotdev/crud"},hooks:{auth:["useAuth"],oauth:["useOAuth","useOAuthPartner","useOAuthConnection"],billing:["useStripeBilling","useStripeCheckout"],crud:["useCrud","useCrudCollection"]}};var O={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},X={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},ke={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ne={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},ge={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},N={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${ge.SOURCE_EAGER}/*_*.json`],lazy:[`${ge.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},he={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async","@donotdev/core","@donotdev/components","@donotdev/ui","@donotdev/templates","@donotdev/firebase"],optionalFeatures:["@donotdev/components","@donotdev/auth","@donotdev/billing","@donotdev/crud","@donotdev/oauth","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder"],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},We=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var Ae={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}},ie={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},_e=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ue={base:{absolute:!0,onlyFiles:!0,ignore:N.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...N.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...N.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:N.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:N.globalIgnore}};function Be(l,e=null){let t=N[l];if(!t)throw new Error(`Unknown pattern type: ${l}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function fe(l){return Ue[l]||Ue.base}import*as m from"node:fs";import"node:fs";import{createRequire as Lt}from"node:module";import{resolve as de,join as U,dirname as B,relative as He,normalize as Ut,sep as Ve,extname as Gt}from"node:path";import{fileURLToPath as Wt}from"node:url";import Bt from"fast-glob";var te={getGlobOptionsFor:fe||void 0,SCAN_PATTERNS:N||void 0,getPatternsFor:Be||void 0,I18N_PATHS:ge||void 0},R={error:(l,e)=>{},warn:(l,e)=>{},info:l=>{}};function Je(l,e){return l().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var qe={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},P=class l{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return l._instance||(l._instance=new l(e)),l._instance}static _reset(){l._instance=null}constructor(e={}){if(l._instance)return l._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,l._instance=this}normalizePath(e){if(!e)return"";try{return Ut(e).split(Ve).join("/")}catch{return String(e).split(Ve).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=He(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(B(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Lt(U(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),n=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(n))return n;if(["auth","billing","crud","oauth"].includes(a)){let i=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(i))return i}if(a==="firebase"){let i=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(i))return i}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=de(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=de(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=de(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=m.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:Gt(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await m.promises.readFile(e);let a=await m.promises.readFile(e,r),n=this.stripBom(a);return o==="json"?JSON.parse(n):n}catch(a){return this.options.debug&&R.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return m.readFileSync(e);let a=m.readFileSync(e,r),n=this.stripBom(a);return o==="json"?JSON.parse(n):n}catch(a){return this.options.debug&&R.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:n=!1}=s,i=this.normalizePath(e),p=this.normalizePath(B(i)),c=this.pathExists(i);if(c&&!o)return n&&R.info(`Skipping existing file: ${i}`),!1;if(a)return R.info(`[DRY RUN] Would write file: ${i}`),!0;try{await m.promises.mkdir(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return await Je(async()=>(Buffer.isBuffer(h)?await m.promises.writeFile(i,h):await m.promises.writeFile(i,h,"utf8"),n&&R.info(`${c?"Updated":"Created"} file: ${i}`),!0),`Failed to write file: ${i}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:n=!1}=s,i=this.normalizePath(e),p=this.normalizePath(B(i)),c=this.pathExists(i);if(c&&!o)return n&&R.info(`Skipping existing file: ${i}`),!1;if(a)return R.info(`[DRY RUN] Would write file: ${i}`),!0;try{m.mkdirSync(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return Buffer.isBuffer(h)?m.writeFileSync(i,h):m.writeFileSync(i,h,"utf8"),n&&R.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch(g){throw new Error(`Failed to write file: ${i}: ${g instanceof Error?g.message:String(g)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,n=this.normalizePath(t),i=this.pathExists(n);if(i&&!r)return a&&R.info(`Skipping existing file: ${n}`),!1;if(o)return R.info(`[DRY RUN] Would copy file: ${n}`),!0;let p=this.normalizePath(B(n));try{await m.promises.mkdir(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await Je(async()=>(await m.promises.copyFile(e,n),a&&R.info(`${i?"Updated":"Created"} file: ${n}`),!0),`Failed to copy file from ${e} to ${n}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,n=this.normalizePath(t),i=this.pathExists(n);if(i&&!r)return a&&R.info(`Skipping existing file: ${n}`),!1;if(o)return R.info(`[DRY RUN] Would copy file: ${n}`),!0;let p=this.normalizePath(B(n));try{m.mkdirSync(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return m.copyFileSync(e,n),a&&R.info(`${i?"Updated":"Created"} file: ${n}`),!0}catch{return!1}}pathExists(e,t=!1){try{return m.existsSync(e)}catch(s){return t||R.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return m.existsSync(t)||m.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return m.readdirSync(e,t)}catch(s){return this.options.debug&&R.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return m.statSync(e)}catch(t){return this.options.debug&&R.warn(`Failed to stat file: ${e}`,t),null}}lstatSync(e){try{return m.lstatSync(e)}catch(t){return this.options.debug&&R.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await m.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{m.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await m.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){m.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return m.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=U(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(de(e)),s=this.getAppRoot(),r=He(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(U(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),n=r.startsWith(a)?r.slice(a.length+1):r,i={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:te.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([n],{...i,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=te.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(U(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await Bt(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=te.getGlobOptionsFor?te.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),n=e.framework.map(c=>{let u=this.normalizePath(c);return u.startsWith(a)?u.slice(a.length+1):u}),i=e.consumer.map(c=>{let u=this.normalizePath(c);return u.startsWith(a)?u.slice(a.length+1):u}),p={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=n.length>0?await this._globWithNormalization(n,p):[],u=await this._globWithNormalization(i,p);return{frameworkFiles:c,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!te.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=te.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let i=r,p={eager:i.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:i.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(i.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((i.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(i.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((i.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return p.all=[...p.eager,...p.lazy,...p.framework.eager,...p.framework.lazy],p}let a=r,n={framework:o?(a.framework||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):[],consumer:(a.consumer||[]).map(i=>this.resolveAppPath(i)),all:[]};return n.all=[...n.consumer,...n.framework],n}getEmptyModulePath(e=!1){if(e)return"@donotdev/core/empty";let t=this.resolvePackage("@donotdev/core/empty");if(t)return t;let s=B(Wt(import.meta.url));return this.normalizePath(U(s,"../empty.js"))}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(U(t,qe.TOOLING)),a=this.normalizePath(U(t,qe.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let n=U(t,"apps");if(this.pathExists(n)&&this.statSync(n)?.isDirectory())return this.normalizePath(t);let i=this.normalizePath(U(t,"package.json"));if(this.pathExists(i)&&this.normalizePath(B(t))===t)return t;let p=this.normalizePath(B(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function Ye({logger:l,debug:e=!1}={}){let t=P.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):l&&l.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&l&&l.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let a=t.resolveRepoPath("apps");if(t.pathExists(a))try{let n=process.cwd(),i=t.normalizePath(n);if(i.includes("/apps/")){let p=i.indexOf("/apps/"),u=i.substring(p+6).split("/")[0];if(u){let h=t.resolveRepoPath(`apps/${u}`),g=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(g)&&(r=h,t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}function Ke(){try{let l=P.getInstance(),e=l.resolveAppPath("package.json"),t=l.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(o=>{let a=o.startsWith("@donotdev/"),n=o==="entities",i=s[o]&&typeof s[o]=="string"&&s[o].startsWith("workspace:");return a||n||i}).filter(o=>!he.buildTimePackages.includes(o)).sort()}catch{return[]}}function G(l){return l&&typeof l=="object"&&!Array.isArray(l)}import Ee from"node:fs";import Ze from"node:path";var Xe=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,H=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{...Ae.selectors,...this.options.customPatterns?.selectors},themes:{...Ae.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(a=>a.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((a,n)=>{let i=a.replace(/[^a-zA-Z0-9]/g,"");return i?n===0?i.toLowerCase():i.charAt(0).toUpperCase()+i.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,a=this.pathResolver.normalizePath(t),n=this._stripComments(e),i=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=i.exec(n))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let h=c.match(this.patterns.themes.themeIcon),g=c.match(this.patterns.themes.themeIsDark),d={name:p,displayName:u,isDark:g?g[1]==="1":!1,meta:{icon:h?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(d),s.themes.set(p,{name:p,displayName:u,isDark:d.isDark,file:a,variables:new Set,meta:d.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${a}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Xe.lastIndex=0;(r=Xe.exec(t))!==null;){let o=r[1];o&&o.trim()&&s.add(o.trim())}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let a=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let a=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:a}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};import*as x from"@clack/prompts";var D={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function Ht(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function I(l,e){return Ht()?`${e}${l}${D.reset}`:l}function k(l,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,a=P.getInstance(),n=null;if(o){let c=a.resolveAppPath(r);a.pathExists(c)||a.mkdir(c),n=a.resolveAppPath(`${r}/${l.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${l} Log Started at ${new Date().toISOString()} ===
2
+ `;a.writeSync(n,u)}let i=(c,u,h)=>{if(n){let g=new Date().toISOString(),d=h.length>0?" "+h.map(A=>typeof A=="object"?JSON.stringify(A,null,2):String(A)).join(" "):"",w=`${g} [${c}] ${u}${d}
3
+ `;a.appendFile(n,w)}},p=(c,u)=>{if(u.length===0)return c;let h=u.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${c} ${h}`};return{debug:(c,...u)=>{e&&(o?i("DEBUG",c,u):x.log.message(I(p(c,u),D.gray)))},verbose:(c,...u)=>{t&&(o?i("VERBOSE",c,u):x.log.message(p(c,u)))},info:(c,...u)=>{o?i("INFO",c,u):x.log.info(I(p(c,u),D.brightCyan))},warn:(c,...u)=>{e&&o?i("WARN",c,u):x.log.warn(I(p(c,u),D.brightYellow))},error:(c,...u)=>{e&&o?i("ERROR",c,u):x.log.error(I(p(c,u),D.brightRed))},success:(c,...u)=>{e&&o?i("SUCCESS",c,u):x.log.success(I(p(c,u),D.brightGreen))},when:(c,u="debug")=>(h,...g)=>{if(c){let d=p(h,g);switch(u){case"verbose":t&&(x.log.message(d),i("VERBOSE",h,g));break;case"info":x.log.info(I(d,D.brightCyan)),i("INFO",h,g);break;case"warn":x.log.warn(I(d,D.brightYellow)),i("WARN",h,g);break;case"error":x.log.error(I(d,D.brightRed)),i("ERROR",h,g);break;case"success":x.log.success(I(d,D.brightGreen)),i("SUCCESS",h,g);break;default:e&&(x.log.message(I(d,D.gray)),i("DEBUG",h,g))}}},getLogFilePath:()=>n}}var Vt=3,Qe="dndev-font-preloads.json";async function Jt(l,e){let t=k("font-preload-next",e,!1);try{let s=await l.resolvePatterns("css"),{consumerFiles:r}=await l.resolveFiles(s,"css");if(!r?.length)return[ie.Inter];let o=new H(l,{debug:e,logger:t}),a=new Set;for(let i of r)try{let p=await l.read(i,{format:"text"});p&&o.extractFontFamilies(p).forEach(c=>a.add(c))}catch{}if(a.size===0)return[ie.Inter];let n=new Set;for(let i of a){let p=ie[i];p&&n.add(p)}return Array.from(n)}catch{return[ie.Inter]}}function et({pathResolver:l,debug:e=!1}){let t=k("font-preload-next",e,!1);return{apply(s){s.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(r,o)=>{if(r.compiler.isChild()||r.compiler.name?.includes("server"))return o();try{let n=l.getAppRoot();if(!n)return o();let i=await Jt(l,e),p=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",c=[];for(let[g]of Object.entries(r.assets)){if(!g.endsWith(".woff2")&&!g.endsWith(".woff"))continue;let d=g.toLowerCase();if(i.some(w=>d.includes(w))){let w=p?`${p}/${g}`:`/${g}`;if(c.push({href:w,type:"font/woff2"}),c.length>=Vt)break}}let u=Ze.join(n,"public");if(!Ee.existsSync(u))try{Ee.mkdirSync(u,{recursive:!0})}catch(g){return t.debug(`Font preload: could not create public dir: ${g?.message}`),o()}let h=Ze.join(u,Qe);Ee.writeFileSync(h,JSON.stringify(c,null,0),"utf8"),t.debug(`Font preload: wrote ${c.length} entries to ${Qe}`)}catch(n){t.debug(`Font preload manifest: ${n?.message}`)}o()})}}}function tt({originalWebpack:l,unusedFeaturePackages:e,usedFeaturePackages:t,logger:s,debug:r}){return(o,a)=>{let{dev:n,isServer:i,webpack:p}=a;n&&!i&&(o.infrastructureLogging={level:"error"},o.stats={...o.stats,logging:"error",loggingTrace:!1},o.ignoreWarnings=[...o.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let c=o.module?.rules?.find(u=>u.test?.test?.(".svg"));c&&(c.exclude=/\.svg$/i),o.module=o.module||{},o.module.rules=o.module.rules||[],o.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),p?.IgnorePlugin&&o.plugins.push(new p.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let u=P.getInstance();o.plugins.push(et({pathResolver:u,debug:r}))}catch(u){s.debug(`Font preload webpack plugin skipped: ${u?.message}`)}if(e.length>0)if(s.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),s.info(`\u2705 Including features: ${t.join(", ")}`),o.externals=o.externals||[],Array.isArray(o.externals))o.externals.push(...e);else{let u=o.externals;o.externals=(h,g,d)=>e.includes(g)?d(null,"commonjs "+g):typeof u=="function"?u(h,g,d):d()}return l?l(o,a):o}}function st({originalRewrites:l,handlers:e,logger:t}){return async function(){try{let s=l?await l():[],o=e.filter(n=>n?.getAPIRewrites).map(n=>n.getAPIRewrites()).reduce((n,i)=>(i?.beforeFiles&&n.beforeFiles.push(...i.beforeFiles),i?.afterFiles&&n.afterFiles.push(...i.afterFiles),i?.fallback&&n.fallback.push(...i.fallback),n),{beforeFiles:[],afterFiles:[],fallback:[]}),a={beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...o.fallback]};return a.beforeFiles.length===0&&a.afterFiles.length===0&&a.fallback.length===0?null:a}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),null}}}function rt({routeResult:l,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:a,restNextConfig:n,discoveredPackages:i,webpackConfig:p,rewritesConfig:c,missingOptionalDeps:u,env:h,logger:g}){let d=n?.output==="export",A=n?.distDir||".next";return{transpilePackages:i,...n?.serverExternalPackages||n?.serverComponentsExternalPackages?{serverExternalPackages:(n?.serverExternalPackages||n?.serverComponentsExternalPackages||[]).filter(T=>!T.startsWith("@donotdev/"))}:{},...G(n)?n:(g.warn("restNextConfig is not a plain object:",n),{}),distDir:A,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...G(l)?l:(g.error(`Route handler config invalid (got ${typeof l}):`,l),{}),...G(e)?e:(g.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...G(t)?t:(g.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...G(s)?s:(g.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...G(r)?r:(g.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...G(o)?o:(g.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...G(a)?a:(g.warn("serverShimConfig returned non-object:",a),{}),webpack:p,...d?{}:{rewrites:async()=>await c()||void 0},env:h,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var qt=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json"],Yt="dndev-config-",ot=".dndev-build";function Kt(l){if(!l)return!1;let e=P.getInstance(),t=e.resolveAppPath(ot),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function Xt(l){if(!l)return;let e=P.getInstance(),t=e.resolveAppPath(ot),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s)}catch{}}function Ne(l,e){if(!l)return;let t=P.getInstance();for(let r of qt){let o=t.resolveAppPath(r);if(t.pathExists(o))try{t.removeSync(o),e.debug(`Cleaned: ${r}`)}catch{}}let s=t.resolveAppPath("src/config");if(t.pathExists(s))try{let r=t.readdirSync(s);for(let o of r)if(o.startsWith(Yt)&&o.endsWith(".js"))try{let a=t.resolvePath(o,s);t.removeSync(a),e.debug(`Cleaned: src/config/${o}`)}catch{}}catch{}}async function Fe({routeHandler:l,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:o},a){let n=l?.pathResolver;if(!n)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let i=n.getAppRoot(),p=n.getRepoRoot();if(!i||i===p){a.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(d=>setTimeout(d,0));let g=n.getAppRoot();if(!g||g===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Kt(i)){a.debug("Discoveries already completed this build, skipping");return}let c=Date.now();if(l)try{a.info("\u{1F50D} Starting route discovery...");let d=(await l.generateFiles())?.routes?.length||0;a.info(`\u2705 Routes generated: ${d} routes found`),d===0&&a.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(g){throw a.error(`\u274C Route generation failed: ${g.message}`),g.stack&&a.error(`Stack: ${g.stack}`),g}else a.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let u=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:o}];for(let{name:g,handler:d}of u)try{await d.generateFiles()}catch(w){a.debug(`${g} generation failed: ${w.message}`)}let h=Date.now()-c;a.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`),Xt(i)}async function at(l,e,t){if(t)return!1;try{let s=await l.getDiscoveryData();return s?.copiedAssets?.length>0&&e.info(`\u{1F4E6} Copied ${s.copiedAssets.length} assets from framework`),!0}catch(s){return e.debug(`Asset discovery failed (non-critical): ${s.message}`),!1}}var le={debug:!1,verbose:process.env.CI!=="true",features:{},generateManifest:!0,routes:{disabled:!1,debug:!1,routingMode:"app",generateMiddleware:!0},themes:{debug:!1},i18n:{debug:!1,fallbackLanguage:"en"},assets:{debug:!1},pwa:{debug:!1},seo:{disabled:!1,debug:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0,debug:!1},discovery:{debug:!1,verbose:!1,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"}};function nt(l,e){let t={...l};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=nt(l[s]||{},e[s]):t[s]=e[s]}),t}function it(l={}){return nt(le,l)}function lt(l){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:a={},seo:n={},serverShim:i={},discovery:p={},generateManifest:c,debug:u,verbose:h,...g}=l,d=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:u,verbose:h,mode:d,isDev:d==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:a,seoOptions:n,serverShimOptions:i,discoveryOptions:p,nextConfigOptions:g}}var $=class{constructor(e,t={}){this.options={...t,...this.getHandlerDefaults()},this.logger=k(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=P.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...le.discovery,...this.options};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}createNextConfig(){return(e={})=>(this.options.debug&&this.logger.debug(`${this.getHandlerName()} handler initialized`),{...e,webpack:(t,s)=>{let{dev:r,isServer:o,webpack:a}=s;return this.applyViteIgnorePlugin(t,a),this._generateFiles(),e.webpack?e.webpack(t,s):t},rewrites:async function(){try{let t=e.rewrites?await e.rewrites():[],s=this.getAPIRewrites();return this.mergeRewrites(t,s)}catch(t){return this.logger.error(`${this.getHandlerName()} handler failed to merge rewrites: ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`),[]}}.bind(this)})}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let t=this.getHandlerName().toLowerCase(),s=X.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!s)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let r=this.generateConfigContent(e);this.writeGeneratedFile(s,r,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),s=O[t]||t;return`// Auto-generated DnDev config by @donotdev/config
5
4
  // Generated at: ${new Date().toISOString()}
6
5
  // Populates _DNDEV_CONFIG_ with discovery results
7
6
 
8
- const ${r}Config = ${JSON.stringify(e,null,2)};
7
+ const ${t}Config = ${JSON.stringify(e,null,2)};
9
8
 
10
9
  // Populate unified DnDev config for runtime access (universal CSR/SSR)
11
10
  if (typeof globalThis !== 'undefined') {
@@ -18,12 +17,12 @@ if (typeof globalThis !== 'undefined') {
18
17
  timestamp: Date.now(),
19
18
  };
20
19
  }
21
- globalThis._DNDEV_CONFIG_.${s} = ${r}Config;
20
+ globalThis._DNDEV_CONFIG_.${s} = ${t}Config;
22
21
  }
23
22
 
24
23
  // Export for compatibility
25
- export default ${r}Config;
26
- `}writeGeneratedFile(e,r,s="file"){let i=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(i,r),this.logger.debug(`Generated ${s}: ${i}`),i}async generateManifest(e){let r=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(r,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),r=this.pathResolver.readSync(e,{format:"text"});r&&(this.writeGeneratedFile("next-env.d.ts",r,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,r){return e.plugins=e.plugins||[],e.plugins.push(new r.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new r.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new r.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,r){let s={beforeFiles:r?.beforeFiles||[],afterFiles:r?.afterFiles||[],fallback:r?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var Q=class t{constructor(e,r={}){if(this.constructor===t)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...r},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=W(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let r=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let i=await this._scanFiles(s),n=await this._processFiles(i);this.cache={...n,timestamp:Date.now()};let a=Date.now()-r;return this.logger.debug(`Discovery completed in ${a}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let r=this._getPatternType();return await this.pathResolver.resolveFiles(e,r)}_extractFileNameInfo(e){let r=e.split("/"),s=r[r.length-1],i=s.split(".")[0],n=s.split(".").pop();return{fileName:s,baseName:i,extension:n,directory:r.slice(0,-1).join("/")}}async _processSingleFile(e,r){try{let s=this.pathResolver.getFileInfo(e);return s?await r(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,r){return(await Promise.all(e.map(i=>this._processSingleFile(i,r)))).filter(i=>i!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var Lt=class extends Q{constructor(e,r={}){super(e,{assets:K.assets.fallback,assetPatterns:K.assets.patterns,frameworkPackage:Vt.package,assetsPath:Vt.assetsPath,modernFormats:K.assets.modern,...r}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let r=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(r),i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let a=[],o=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(o)&&this.options.generateAssets!==!1&&(a=(await this._generateMissingAssets(r))?.generated||[]);let{consumerFiles:c}=e,h=await this._processAssetFiles(c),f=this._buildAssetManifest(h),g=await this._readLogoSvgContent("/logo.svg",r);return{assets:h,manifest:{...f,logoSvgContent:g},copiedAssets:s,generatedAssets:a,pwaIcons:this._extractPWAIcons(h)}}_extractPWAIcons(e){let r=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let i=s.path.split("/").pop()||"";return r.some(n=>n.test(i))}).map(s=>{let i=s.path.split("/").pop()||"",n=i.match(/(\d+)x(\d+)/),a=n?{width:parseInt(n[1]),height:parseInt(n[2])}:this._getDefaultIconSize(i);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:a,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(i)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,r=this.cache?.copiedAssets?.length||0;return`${e} assets, ${r} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,r){let s=this.getAssets().map(n=>n.path),i=r||this.options.modernFormats;for(let n of i){let a=`/${e}.${n}`;if(s.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let r=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),r;let i=this.pathResolver.resolveAppPath(nt.public);this.pathResolver.pathExists(i)||(this.pathResolver.mkdir(i),this.logger.debug(`Created public directory: ${i}`));for(let n of this.options.assets)await this._ensureAsset(n,i,s)&&r.push(n);r.length>0&&this.logger.debug(`Added ${r.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return r}async _ensureAsset(e,r,s){let i=this.pathResolver.resolveAppPath(`${nt.public}/${e}`);if(this.pathResolver.pathExists(i))return this.logger.debug(`Asset exists: ${e}`),!1;let n=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(n)){if(await this.pathResolver.copy(n,i))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let r=[];for(let s of e)try{let i=this.pathResolver.getFileInfo(s);if(i&&i.isFile){let n=s.split("/").pop()||s.split("\\").pop(),a=this._analyzeAsset(n,i.size);a&&r.push(a)}}catch(i){this.logger.debug(`Error processing asset file ${s}: ${i.message}`)}return this.logger.debug(`Processed ${r.length} assets from ${e.length} files`),r}_analyzeAsset(e,r){let s=this._determineAssetType(e),i=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:s,format:i,size:r,sizeFormatted:this._formatBytes(r),isModern:this.options.modernFormats.includes(i)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let r=e.toLowerCase();if(r.includes("favicon"))return"favicon";if(r.includes("logo"))return"logo";if(r.includes("icon"))return"icon";if(r.includes("apple-touch"))return"apple-touch-icon";if(r.includes("android-chrome"))return"android-icon";if(r.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let r=1024,s=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(r));return parseFloat((e/Math.pow(r,i)).toFixed(2))+" "+s[i]}_matchesPattern(e,r){let s=e.toLowerCase(),i=r.toLowerCase();return s.includes(i.replace("*",""))}_buildAssetManifest(e){let r=e.map(i=>i.path);return{logo:{optimal:this._getOptimalAsset("logo",r,this.options.modernFormats),fallback:this._getOptimalAsset("logo",r,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",r,["svg","ico"]),fallback:this._getOptimalAsset("favicon",r,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",r,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",r,["png"]),512:this._getOptimalAsset("android-chrome-512x512",r,["png"])},manifest:r.find(i=>i.includes("manifest.json"))||null,modernFormats:e.filter(i=>i.isModern).map(i=>i.path),fallbackFormats:e.filter(i=>!i.isModern).map(i=>i.path)}}_getOptimalAsset(e,r,s){for(let i of s){let n=`/${e}.${i}`;if(r.includes(n))return n}return null}async _resolveFrameworkAssetsDir(e){try{let r=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",r);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let i=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(i)?(this.logger.debug(`Using framework assets from: ${i}`),i):(this.logger.debug(`Assets directory not found: ${i}`),null)}catch(r){return this.logger.debug(`Error resolving framework assets directory: ${r.message}`),null}}async _resolvePackage(e,r){try{let s=this.pathResolver.resolveFrameworkPackage(e,r);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,r){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),i=this.pathResolver.resolveAppPath(`${nt.public}/${s}`);return this.pathResolver.pathExists(i)&&await this.pathResolver.read(i,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let r=await this._resolveFrameworkAssetsDir(e);if(!r)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${r}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let i=this.pathResolver.resolveAppPath(nt.public);this.pathResolver.pathExists(i)||this.pathResolver.mkdir(i);let n=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,n)}catch(r){return this.logger.debug(`Failed to copy framework logo: ${r.message}`),!1}}async _generateMissingAssets(e){let r=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(r))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let i=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],n=[{name:"favicon.svg",format:"svg"}],a=[],o=[];try{let c=await this.pathResolver.read(r,{format:"text"});if(!c)return{generated:[],skipped:[...n,...i].map(f=>f.name),error:"Failed to read logo.svg"};for(let f of n){let g=`${s}/${f.name}`;if(this.pathResolver.pathExists(g)){o.push(f.name);continue}try{await this.pathResolver.write(`public/${f.name}`,c),a.push(f.name)}catch(m){this.logger.debug(`Failed to copy ${f.name}: ${m.message}`),o.push(f.name)}}let h=await Promise.resolve().then(()=>la($n(),1)).catch(()=>null);if(!h)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),o.push(...i.map(f=>f.name));else for(let f of i){let g=`${s}/${f.name}`;if(this.pathResolver.pathExists(g)){o.push(f.name);continue}try{let m=h.default(r).resize(f.size,f.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),p;f.format==="ico"?p=await m.toFormat("png").toBuffer():p=await m.toFormat(f.format).toBuffer(),await this.pathResolver.write(`public/${f.name}`,p),a.push(f.name)}catch(m){this.logger.debug(`Failed to generate ${f.name}: ${m.message}`),o.push(f.name)}}return{generated:a,skipped:o,error:null}}catch(c){return this.logger.debug(`Asset generation failed: ${c.message}`),{generated:[],skipped:requiredAssets.map(h=>h.name),error:c.message}}}};var _r={data:null},Ar=class extends G{constructor(e={}){super(Lt,e)}getHandlerDefaults(){return{manifestPath:De.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let r=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
24
+ export default ${t}Config;
25
+ `}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var F=class l{constructor(e,t={}){if(this.constructor===l)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=k(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let a=Date.now()-t;return this.logger.debug(`Discovery completed in ${a}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var me=class extends F{constructor(e,t={}){super(e,{assets:N.assets.fallback,assetPatterns:N.assets.patterns,frameworkPackage:ke.package,assetsPath:ke.assetsPath,modernFormats:N.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let a=[],n=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(n)&&this.options.generateAssets!==!1&&(a=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:i}=e,p=await this._processAssetFiles(i),c=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...c,logoSvgContent:u},copiedAssets:s,generatedAssets:a,pwaIcons:this._extractPWAIcons(p)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(o=>o.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",o=r.match(/(\d+)x(\d+)/),a=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:a,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let a=`/${e}.${o}`;if(s.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(ne.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let o of this.options.assets)await this._ensureAsset(o,r,s)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${ne.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let o=s.split("/").pop()||s.split("\\").pop(),a=this._analyzeAsset(o,r.size);a&&t.push(a)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let o=`/${e}.${r}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${ne.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(ne.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],a=[],n=[];try{let i=await this.pathResolver.read(t,{format:"text"});if(!i)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){n.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,i),a.push(c.name)}catch(h){this.logger.debug(`Failed to copy ${c.name}: ${h.message}`),n.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),n.push(...r.map(c=>c.name));else for(let c of r){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){n.push(c.name);continue}try{let h=p.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;c.format==="ico"?g=await h.toFormat("png").toBuffer():g=await h.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,g),a.push(c.name)}catch(h){this.logger.debug(`Failed to generate ${c.name}: ${h.message}`),n.push(c.name)}}return{generated:a,skipped:n,error:null}}catch(i){return this.logger.debug(`Asset generation failed: ${i.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:i.message}}}};var Ce={data:null},De=class extends ${constructor(e={}){super(me,e)}getHandlerDefaults(){return{manifestPath:X.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
27
26
  // Generated at: ${new Date().toISOString()}
28
27
  // Populates _DNDEV_CONFIG_ with discovery results
29
28
 
@@ -40,9 +39,9 @@ if (typeof globalThis !== 'undefined') {
40
39
  timestamp: Date.now(),
41
40
  };
42
41
  }
43
- globalThis._DNDEV_CONFIG_.${re.assets} = {
42
+ globalThis._DNDEV_CONFIG_.${O.assets} = {
44
43
  mapping: assetConfig.manifest,
45
- logoSvgContent: ${JSON.stringify(r)},
44
+ logoSvgContent: ${JSON.stringify(t)},
46
45
  manifest: {
47
46
  totalAssets: ${e.assets?.length||0},
48
47
  generatedAt: '${new Date().toISOString()}',
@@ -52,20 +51,20 @@ if (typeof globalThis !== 'undefined') {
52
51
 
53
52
  // Export for compatibility
54
53
  export default assetConfig;
55
- `}logDiscoveryResults(e){let r=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${r} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${r} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(_r.data={pwaIcons:e.pwaIcons}),e}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(r=>({path:r.path,type:r.type,format:r.format,size:r.size,optimized:r.optimized})),manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} assets, ${e.copiedAssets.length} copied from framework`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateAssetManifest(e),this.options.optimizeImages&&await this.generateImageOptimization(e),await this.generateAPIHandler(e)}async generateAssetManifest(e){let r=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",r,"asset manifest")}generateAssetManifestContent(e){let r=e.assets.map(n=>` {
56
- path: '${n.path}',
57
- type: '${n.type}',
58
- format: '${n.format}',
59
- size: ${n.size},
60
- optimized: ${n.optimized||!1}
54
+ `}logDiscoveryResults(e){let t=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(Ce.data={pwaIcons:e.pwaIcons}),e}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({path:t.path,type:t.type,format:t.format,size:t.size,optimized:t.optimized})),manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} assets, ${e.copiedAssets.length} copied from framework`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateAssetManifest(e),this.options.optimizeImages&&await this.generateImageOptimization(e),await this.generateAPIHandler(e)}async generateAssetManifest(e){let t=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",t,"asset manifest")}generateAssetManifestContent(e){let t=e.assets.map(o=>` {
55
+ path: '${o.path}',
56
+ type: '${o.type}',
57
+ format: '${o.format}',
58
+ size: ${o.size},
59
+ optimized: ${o.optimized||!1}
61
60
  }`).join(`,
62
- `),s=Object.entries(e.manifest).map(([n,a])=>` ${n}: ${JSON.stringify(a)}`).join(`,
63
- `),i=e.manifest.logoSvgContent||null;return`// Auto-generated asset manifest by @donotdev/config
61
+ `),s=Object.entries(e.manifest).map(([o,a])=>` ${o}: ${JSON.stringify(a)}`).join(`,
62
+ `),r=e.manifest.logoSvgContent||null;return`// Auto-generated asset manifest by @donotdev/config
64
63
  // Generated at ${new Date().toISOString()}
65
64
  // Populates _DNDEV_CONFIG_ with discovery results
66
65
 
67
66
  export const assets = [
68
- ${r}
67
+ ${t}
69
68
  ];
70
69
 
71
70
  export const assetManifest = {
@@ -94,7 +93,7 @@ if (typeof globalThis !== 'undefined') {
94
93
  }
95
94
  globalThis._DNDEV_CONFIG_.assets = {
96
95
  mapping: assetManifest,
97
- logoSvgContent: ${JSON.stringify(i)},
96
+ logoSvgContent: ${JSON.stringify(r)},
98
97
  manifest: {
99
98
  totalAssets: ${e.assets.length},
100
99
  generatedAt: '${new Date().toISOString()}',
@@ -103,9 +102,9 @@ if (typeof globalThis !== 'undefined') {
103
102
  }
104
103
 
105
104
  export default assets;
106
- `}async generateImageOptimization(e){let r=e.assets.filter(i=>i.type==="image");if(r.length===0){this.logger.debug("No image assets found, skipping optimization config");return}let s=this.generateImageOptimizationContent(r);this.writeGeneratedFile("src/app/image-optimization.generated.ts",s,"image optimization config")}generateImageOptimizationContent(e){let r=e.map(s=>{let i=s.path.split("/").pop().split(".")[0];return` '${i}': {
105
+ `}async generateImageOptimization(e){let t=e.assets.filter(r=>r.type==="image");if(t.length===0){this.logger.debug("No image assets found, skipping optimization config");return}let s=this.generateImageOptimizationContent(t);this.writeGeneratedFile("src/app/image-optimization.generated.ts",s,"image optimization config")}generateImageOptimizationContent(e){let t=e.map(s=>{let r=s.path.split("/").pop().split(".")[0];return` '${r}': {
107
106
  src: '${s.path}',
108
- alt: '${i}',
107
+ alt: '${r}',
109
108
  width: ${s.width||"auto"},
110
109
  height: ${s.height||"auto"},
111
110
  priority: false
@@ -114,21 +113,21 @@ export default assets;
114
113
  // Generated at ${new Date().toISOString()}
115
114
 
116
115
  export const imageConfigs = {
117
- ${r}
116
+ ${t}
118
117
  };
119
118
 
120
119
  export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
121
120
 
122
121
  export default imageConfigs;
123
- `}};function Sn(t={}){return new Ar(t)}var Ot=class extends Q{constructor(e,r={}){super(e,{fallbackLanguage:"en",additionalPaths:[],...r})}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let r=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!r||r===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${r}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${r}, repoRoot=${s}`);let i=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${i.eager.length}, lazy: ${i.lazy.length}, framework eager: ${i.framework?.eager?.length||0}, framework lazy: ${i.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let n=vt("i18n"),a=i.eager||[],o=i.lazy||[],c=(this.options.additionalPaths||[]).map(S=>{let k=S.endsWith(".json")?S:`${S}/*_*.json`;return this.pathResolver.resolveAppPath(k)});c.length>0&&this.logger.debug(`Additional i18n paths configured: ${c.join(", ")}`);let h=i.framework?.eager||[],f=i.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${o.join(", ")}, framework eager: ${h.join(", ")}, framework lazy: ${f.join(", ")}`),h.length===0&&f.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let g=this.pathResolver.normalizePath(r),m=this.pathResolver.normalizePath(s),p=(S,k)=>{let A=this.pathResolver.normalizePath(S),U=this.pathResolver.normalizePath(k);return A.startsWith(U)?A.slice(U.length+1):A},R=a.map(S=>p(S,r)),J=[...o,...c].map(S=>p(S,r)),ze=h.map(S=>p(S,s)),ue=f.map(S=>p(S,s)),_e={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r},Ne=await this.pathResolver._globWithNormalization(R,_e),Be=await this.pathResolver._globWithNormalization(J,_e),Ie={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:n.ignore?.filter(S=>S!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(Ie.ignore)}`);let X=await this.pathResolver._globWithNormalization(ze,Ie),fe=await this.pathResolver._globWithNormalization(ue,Ie);this.logger.debug(`Found ${Ne.length} eager, ${Be.length} lazy, ${X.length} framework eager, ${fe.length} framework lazy files`),X.length>0?this.logger.debug(`Framework eager files (first 3): ${X.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${h.join(", ")}`),fe.length>0?this.logger.debug(`Framework lazy files (first 3): ${fe.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${f.join(", ")}`);let rt=[...new Set([...Ne,...Be,...X,...fe])],Ue=new Set([...Ne,...X]),y={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},Pe=new Map,de=[...X,...fe];for(let S of de){let k=this._processTranslationFile(S,X.includes(S),r);if(k){let A=`${k.namespace}_${k.language}`;Pe.set(A,k),y.allNamespaces.add(k.namespace),y.supportedLanguages.add(k.language),X.includes(S)&&y.eagerNamespaces.add(k.namespace)}}let te=new Set;for(let S of rt){if(de.includes(S))continue;let k=this._processTranslationFile(S,Ue.has(S),r);if(k){let{namespace:A,language:U,importPath:gt,content:Ut}=k,Y=`${k.namespace}_${k.language}`;if(Pe.has(Y)){let ge=Pe.get(Y);k.content=this._mergeTranslations(ge.content,Ut)}y.allNamespaces.add(A),y.supportedLanguages.add(U),te.add(U),Ue.has(S)&&y.eagerNamespaces.add(A),y.mapping[A]||(y.mapping[A]={}),y.mapping[A][U]=gt,k.content&&(y.content[A]||(y.content[A]={}),y.content[A][U]=k.content),y.files.push({path:S,relativePath:this.pathResolver.getRelativePath(S),namespace:A,language:U,eager:Ue.has(S),size:k.content?JSON.stringify(k.content).length:0})}}for(let[S,k]of Pe){let[A,U]=S.split("_");(!y.mapping[A]||!y.mapping[A][U])&&(y.mapping[A]||(y.mapping[A]={}),y.mapping[A][U]=k.importPath,y.content[A]||(y.content[A]={}),y.content[A][U]=k.content)}let Fe=te.size>0?[...te].sort():[this.options.fallbackLanguage];return{mapping:y.mapping,content:y.content,eagerNamespaces:[...y.eagerNamespaces].sort(),allNamespaces:[...y.allNamespaces].sort(),supportedLanguages:Fe,fallbackLanguage:this.options.fallbackLanguage,files:y.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let r=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let i=Date.now()-r;return this.logger.debug(`Discovery completed in ${i}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,r,s){let i=e.split("/").pop()||e.split("\\").pop()||"",n,a,o=i.match(/^([^_]+)_([^.]+)\.json$/);if(!o)return this.logger.debug(`Invalid translation file name format: ${i}`),null;if([,n,a]=o,!n||!a)return this.logger.debug(`Invalid namespace or language in file: ${i}`),null;let h="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),f;try{if(f=this.pathResolver.readSync(e,{format:"json"}),!f)return this.logger.debug(`Could not read file: ${e}`),null}catch(g){return this.logger.debug(`Error parsing JSON from ${e}: ${g.message}`),null}return{namespace:n,language:a,importPath:h,content:f}}_mergeTranslations(e,r){let s={...e};for(let[i,n]of Object.entries(r))typeof n=="object"&&n!==null&&!Array.isArray(n)?s[i]=this._mergeTranslations(s[i]||{},n):s[i]=n;return s}};var Nr=class extends G{constructor(e={}){super(Ot,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let r={...ot.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,r)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let r=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(i=>i!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${r.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let r=e.stats||{},s=r.totalNamespaces||0,i=r.totalLanguages||0;return`${s} namespaces, ${i} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:r,supportedLanguages:s,eagerNamespaces:i,fallbackLanguage:n,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
122
+ `}};function ct(l={}){return new De(l)}var ve=class extends F{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],...t})}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=fe("i18n"),a=r.eager||[],n=r.lazy||[],i=(this.options.additionalPaths||[]).map(v=>{let b=v.endsWith(".json")?v:`${v}/*_*.json`;return this.pathResolver.resolveAppPath(b)});i.length>0&&this.logger.debug(`Additional i18n paths configured: ${i.join(", ")}`);let p=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${n.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${c.join(", ")}`),p.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),h=this.pathResolver.normalizePath(s),g=(v,b)=>{let y=this.pathResolver.normalizePath(v),S=this.pathResolver.normalizePath(b);return y.startsWith(S)?y.slice(S.length+1):y},d=a.map(v=>g(v,t)),A=[...n,...i].map(v=>g(v,t)),Z=p.map(v=>g(v,s)),T=c.map(v=>g(v,s)),V={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},J=await this.pathResolver._globWithNormalization(d,V),Q=await this.pathResolver._globWithNormalization(A,V),q={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(v=>v!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(q.ignore)}`);let _=await this.pathResolver._globWithNormalization(Z,q),j=await this.pathResolver._globWithNormalization(T,q);this.logger.debug(`Found ${J.length} eager, ${Q.length} lazy, ${_.length} framework eager, ${j.length} framework lazy files`),_.length>0?this.logger.debug(`Framework eager files (first 3): ${_.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),j.length>0?this.logger.debug(`Framework lazy files (first 3): ${j.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let re=[...new Set([...J,...Q,..._,...j])],ee=new Set([...J,..._]),f={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},W=new Map,M=[..._,...j];for(let v of M){let b=this._processTranslationFile(v,_.includes(v),t);if(b){let y=`${b.namespace}_${b.language}`;W.set(y,b),f.allNamespaces.add(b.namespace),f.supportedLanguages.add(b.language),_.includes(v)&&f.eagerNamespaces.add(b.namespace)}}let C=new Set;for(let v of re){if(M.includes(v))continue;let b=this._processTranslationFile(v,ee.has(v),t);if(b){let{namespace:y,language:S,importPath:pe,content:Pe}=b,E=`${b.namespace}_${b.language}`;if(W.has(E)){let z=W.get(E);b.content=this._mergeTranslations(z.content,Pe)}f.allNamespaces.add(y),f.supportedLanguages.add(S),C.add(S),ee.has(v)&&f.eagerNamespaces.add(y),f.mapping[y]||(f.mapping[y]={}),f.mapping[y][S]=pe,b.content&&(f.content[y]||(f.content[y]={}),f.content[y][S]=b.content),f.files.push({path:v,relativePath:this.pathResolver.getRelativePath(v),namespace:y,language:S,eager:ee.has(v),size:b.content?JSON.stringify(b.content).length:0})}}for(let[v,b]of W){let[y,S]=v.split("_");(!f.mapping[y]||!f.mapping[y][S])&&(f.mapping[y]||(f.mapping[y]={}),f.mapping[y][S]=b.importPath,f.content[y]||(f.content[y]={}),f.content[y][S]=b.content)}let Y=C.size>0?[...C].sort():[this.options.fallbackLanguage];return{mapping:f.mapping,content:f.content,eagerNamespaces:[...f.eagerNamespaces].sort(),allNamespaces:[...f.allNamespaces].sort(),supportedLanguages:Y,fallbackLanguage:this.options.fallbackLanguage,files:f.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,a,n=r.match(/^([^_]+)_([^.]+)\.json$/);if(!n)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,a]=n,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let p="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:o,language:a,importPath:p,content:c}}_mergeTranslations(e,t){let s={...e};for(let[r,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?s[r]=this._mergeTranslations(s[r]||{},o):s[r]=o;return s}};var Oe=class extends ${constructor(e={}){super(ve,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...le.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:o,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
124
123
  // Generated at: ${new Date().toISOString()}
125
124
  // Populates _DNDEV_CONFIG_ with discovery results
126
125
 
127
126
  const i18nConfig = {
128
- mapping: ${JSON.stringify(r,null,2)},
127
+ mapping: ${JSON.stringify(t,null,2)},
129
128
  languages: ${JSON.stringify(s,null,2)},
130
- eager: ${JSON.stringify(i,null,2)},
131
- fallback: '${n}',
129
+ eager: ${JSON.stringify(r,null,2)},
130
+ fallback: '${o}',
132
131
  content: ${JSON.stringify(a||{},null,2)},
133
132
  storage: {
134
133
  type: 'localStorage',
@@ -142,10 +141,10 @@ const i18nConfig = {
142
141
  errorCacheTTL: 30000,
143
142
  },
144
143
  manifest: {
145
- totalFiles: ${Object.keys(r).length},
146
- totalNamespaces: ${Object.keys(r).length},
144
+ totalFiles: ${Object.keys(t).length},
145
+ totalNamespaces: ${Object.keys(t).length},
147
146
  totalLanguages: ${s.length},
148
- eagerNamespaces: ${i.length},
147
+ eagerNamespaces: ${r.length},
149
148
  generatedAt: new Date().toISOString(),
150
149
  },
151
150
  debug: ${this.options.debug},
@@ -162,12 +161,12 @@ if (typeof globalThis !== 'undefined') {
162
161
  timestamp: Date.now(),
163
162
  };
164
163
  }
165
- globalThis._DNDEV_CONFIG_.${re.i18n} = i18nConfig;
164
+ globalThis._DNDEV_CONFIG_.${O.i18n} = i18nConfig;
166
165
  }
167
166
 
168
167
  // Export for compatibility
169
168
  export default i18nConfig;
170
- `}};function kn(t={}){return new Nr(t)}var Mt=class extends Q{constructor(e,r={}){super(e,{...r})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:r,consumerFiles:s}=e,i=[...r,...s];this.logger.debug(`Processing ${i.length} PWA files`);let n=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),n=[...this.options.assetData.pwaIcons]);let a=await this._analyzePWAFiles(i),o=a.filter(m=>m.type==="manifest"||m.type==="service-worker");n.push(...o);let c=a.filter(m=>m.type==="icon"),h=new Set(n.filter(m=>m.type==="icon").map(m=>m.path)),f=c.filter(m=>!h.has(m.path));n.push(...f);let g=this._generatePWAManifest(n);return{assets:n,manifest:g,totalFiles:i.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let r=[];for(let s of e){let i=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,n=await this._analyzePWAAsset(i);n&&r.push(n)}return r}async _analyzePWAAsset(e){let r=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!r)return null;let s=e.relativePath,i=e.fileName;return i.includes("manifest.json")?this._parseManifestFile(r,s):i.includes("service-worker")||i.includes("sw.")?this._parseServiceWorkerFile(r,s):this._isPWAIcon(i)?this._parseIconFile(e,s):null}_parseManifestFile(e,r){try{let s=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:r,content:s,size:typeof e=="string"?e.length:JSON.stringify(s).length}}catch(s){return this.logger.debug(`Failed to parse manifest: ${s.message}`),null}}_parseServiceWorkerFile(e,r){return{type:"service-worker",path:r,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,r){let s=e.fileName,i=this._extractIconSize(s);return{type:"icon",path:r,size:i,format:e.extension,purpose:this._getIconPurpose(s)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(s=>e.includes(s))}_extractIconSize(e){let r=e.match(/(\d+)x(\d+)/);return r?{width:parseInt(r[1]),height:parseInt(r[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let r=e.filter(n=>n.type==="icon"),i=e.find(n=>n.type==="manifest")?.content||this._getDefaultManifest();return r.length>0&&(i.icons=r.map(n=>({src:`/${n.path}`,sizes:`${n.size.width}x${n.size.height}`,type:`image/${n.format}`,purpose:n.purpose}))),i}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let r=e.manifest||this._getDefaultManifest();return JSON.stringify(r,null,2)}generateServiceWorkerContent(e,r={}){let s=this._getWorkboxDefaults(r),i=r.backgroundSync!==!1&&r.backgroundSync,n=r.precacheManifest||[],a=JSON.stringify(n,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
169
+ `}};function pt(l={}){return new Oe(l)}var be=class extends F{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:s}=e,r=[...t,...s];this.logger.debug(`Processing ${r.length} PWA files`);let o=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),o=[...this.options.assetData.pwaIcons]);let a=await this._analyzePWAFiles(r),n=a.filter(h=>h.type==="manifest"||h.type==="service-worker");o.push(...n);let i=a.filter(h=>h.type==="icon"),p=new Set(o.filter(h=>h.type==="icon").map(h=>h.path)),c=i.filter(h=>!p.has(h.path));o.push(...c);let u=this._generatePWAManifest(o);return{assets:o,manifest:u,totalFiles:r.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let s of e){let r=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,o=await this._analyzePWAAsset(r);o&&t.push(o)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let s=e.relativePath,r=e.fileName;return r.includes("manifest.json")?this._parseManifestFile(t,s):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,s):this._isPWAIcon(r)?this._parseIconFile(e,s):null}_parseManifestFile(e,t){try{let s=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:s,size:typeof e=="string"?e.length:JSON.stringify(s).length}}catch(s){return this.logger.debug(`Failed to parse manifest: ${s.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let s=e.fileName,r=this._extractIconSize(s);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(s)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(s=>e.includes(s))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(o=>o.type==="icon"),r=e.find(o=>o.type==="manifest")?.content||this._getDefaultManifest();return t.length>0&&(r.icons=t.map(o=>({src:`/${o.path}`,sizes:`${o.size.width}x${o.size.height}`,type:`image/${o.format}`,purpose:o.purpose}))),r}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let t=e.manifest||this._getDefaultManifest();return JSON.stringify(t,null,2)}generateServiceWorkerContent(e,t={}){let s=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,o=t.precacheManifest||[],a=JSON.stringify(o,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
171
170
  // Generated at ${new Date().toISOString()}
172
171
 
173
172
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
@@ -177,7 +176,7 @@ const { registerRoute } = workbox.routing;
177
176
  const { CacheFirst, NetworkFirst, StaleWhileRevalidate } = workbox.strategies;
178
177
  const { ExpirationPlugin } = workbox.expiration;
179
178
  const { CacheableResponsePlugin } = workbox.cacheableResponse;
180
- ${i?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
179
+ ${r?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
181
180
 
182
181
  // Clean up outdated caches
183
182
  cleanupOutdatedPrecaches();
@@ -187,9 +186,9 @@ const precacheManifest = ${a.length>2?a:"self.__WB_MANIFEST || []"};
187
186
  precacheAndRoute(precacheManifest);
188
187
 
189
188
  // Runtime caching strategies
190
- ${this._generateWorkboxRuntimeCaching(s.runtimeCaching,r)}
189
+ ${this._generateWorkboxRuntimeCaching(s.runtimeCaching,t)}
191
190
 
192
- ${i?this._generateBackgroundSync(r.backgroundSync):""}
191
+ ${r?this._generateBackgroundSync(t.backgroundSync):""}
193
192
 
194
193
  // Skip waiting and claim clients
195
194
  self.addEventListener('message', (event) => {
@@ -201,45 +200,45 @@ self.addEventListener('message', (event) => {
201
200
  self.addEventListener('activate', (event) => {
202
201
  event.waitUntil(self.clients.claim());
203
202
  });
204
- `}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:r})=>r.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,r={}){return e.map((s,i)=>{let{urlPattern:n,handler:a,options:o={}}=s,c=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",h;typeof n=="function"?h="({ request }) => request.destination === 'document'":n instanceof RegExp?h=n.toString():h=JSON.stringify(n);let f=[];o.expiration&&f.push(`new ExpirationPlugin({
205
- maxEntries: ${o.expiration.maxEntries||50},
206
- maxAgeSeconds: ${o.expiration.maxAgeSeconds||3600*24},
207
- })`),o.cacheableResponse&&f.push(`new CacheableResponsePlugin({
208
- statuses: ${JSON.stringify(o.cacheableResponse.statuses||[0,200])},
209
- })`),o.backgroundSync&&f.push(`new BackgroundSyncPlugin('${o.backgroundSync.queueName||"background-sync-queue"}', {
210
- maxRetentionTime: ${o.backgroundSync.maxRetentionTime||1440},
211
- })`);let g="";return o.cacheName&&(g+=`
212
- cacheName: '${o.cacheName}',`),f.length>0&&(g+=`
203
+ `}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:o,handler:a,options:n={}}=s,i=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",p;typeof o=="function"?p="({ request }) => request.destination === 'document'":o instanceof RegExp?p=o.toString():p=JSON.stringify(o);let c=[];n.expiration&&c.push(`new ExpirationPlugin({
204
+ maxEntries: ${n.expiration.maxEntries||50},
205
+ maxAgeSeconds: ${n.expiration.maxAgeSeconds||3600*24},
206
+ })`),n.cacheableResponse&&c.push(`new CacheableResponsePlugin({
207
+ statuses: ${JSON.stringify(n.cacheableResponse.statuses||[0,200])},
208
+ })`),n.backgroundSync&&c.push(`new BackgroundSyncPlugin('${n.backgroundSync.queueName||"background-sync-queue"}', {
209
+ maxRetentionTime: ${n.backgroundSync.maxRetentionTime||1440},
210
+ })`);let u="";return n.cacheName&&(u+=`
211
+ cacheName: '${n.cacheName}',`),c.length>0&&(u+=`
213
212
  plugins: [
214
- ${f.join(`,
213
+ ${c.join(`,
215
214
  `)}
216
- ],`),o.networkTimeoutSeconds&&(g+=`
217
- networkTimeoutSeconds: ${o.networkTimeoutSeconds},`),`// Runtime cache ${i+1}: ${o.cacheName||"cache-"+i}
215
+ ],`),n.networkTimeoutSeconds&&(u+=`
216
+ networkTimeoutSeconds: ${n.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${n.cacheName||"cache-"+r}
218
217
  registerRoute(
219
- ${h},
220
- new ${c}({${g}
218
+ ${p},
219
+ new ${i}({${u}
221
220
  })
222
221
  );`}).join(`
223
222
 
224
- `)}_generateBackgroundSync(e){if(!e||e===!1)return"";let r=e.queueName||"background-sync-queue",s=e.maxRetentionTime||1440,i=e.urlPattern||/\/api\/.*/i,n;return typeof i=="function"||i instanceof RegExp?n=i.toString():n=JSON.stringify(i),`
223
+ `)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",s=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,o;return typeof r=="function"||r instanceof RegExp?o=r.toString():o=JSON.stringify(r),`
225
224
  // Background sync for offline actions
226
225
  const { NetworkOnly } = workbox.strategies;
227
226
  registerRoute(
228
- ${n},
227
+ ${o},
229
228
  new NetworkOnly({
230
229
  plugins: [
231
- new BackgroundSyncPlugin('${r}', {
230
+ new BackgroundSyncPlugin('${t}', {
232
231
  maxRetentionTime: ${s},
233
232
  }),
234
233
  ],
235
234
  }),
236
235
  'POST'
237
236
  );
238
- `}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let r=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),i=this.pathResolver.resolveAppPath(`${e}/static/css`),n=[];try{let a=[`${r}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${i}/**/*.css`];for(let o of a){let c=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),o.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let h of c){let f=this.pathResolver.getRelativePath(h);if(f.startsWith(`${e}/static/`)){let g=`/_next/${f.replace(`${e}/static/`,"")}`;n.push({url:g,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return n}generatePrecacheManifest(e=[],r=null){let s=e;return r&&typeof r=="function"&&(s=r(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Ir=class extends G{constructor(e={}){super(Mt,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let r=this.options.assetData||_r.data;return new e(this.pathResolver,{...this.options,assetData:r})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(r=>({type:r.type,path:r.path,size:r.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.enabled){this.logger.debug("PWA disabled, skipping generation");return}this.options.generateManifest&&await this.generatePWAManifest(e),this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let r=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,r,"PWA manifest")}async generateServiceWorker(e){let r=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let n=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(n,r.manifestTransform)}let i=this.discovery.generateServiceWorkerContent(e,{...r,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,i,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let r=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...r,...s]},webpack:(r,s)=>{let{dev:i,isServer:n,webpack:a}=s;return this.applyViteIgnorePlugin(r,a),!i&&!n&&this._generateFiles(),e.webpack?e.webpack(r,s):r}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function An(t={}){return new Ir(t)}import{createRequire as Hh}from"node:module";function _n(t,e="unknown"){try{let r=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=t.match(r);if(!s)return null;let i=s[1];i=i.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(c,h)=>`icon: '${h}'`);let n=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...t.matchAll(n)].forEach(c=>{let h=c[1],f=c[2];i=i.replace(new RegExp(`\\b${h}\\b`,"g"),`'${f}'`)}),Function(`return ${i}`)()}catch{return null}}var dt=null,Nn=null;function qh(t){let r=(t.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return r.charAt(0).toUpperCase()+r.slice(1)}var tt=class extends Q{constructor(e,r={}){super(e,{additionalPatterns:[],...r}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let r=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(dt&&Nn===s)return this.logger.debug("Using cached route discovery results"),this.routes=dt.routes,this.errors=dt.errors,this.source=dt.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${r}`),this.options.debug){let i=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${i} files in ${r}`);let n=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(n)}`)}return await this._performAutoDiscovery(e,r),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),dt={routes:this.routes,errors:this.errors,source:this.source},Nn=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,r){let{consumerFiles:s}=e,i=await this._batchProcessFiles(s,h=>this._analyzePageFile(h,r)),n=await this._scanAdditionalPatterns(r),a=await this._batchProcessFiles(n,h=>this._analyzePageFile(h,r)),o=[...i,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${n.length} additional files`),this.routes=o.filter(h=>h.path==="home"||h.path==="/home"?(this.logger.debug(`Filtered reserved route: ${h.path} - Use root "/" instead (${h.file})`),!1):!0);let c=new Map;for(let h of this.routes){let f=h.path;if(c.has(f)){let g=c.get(f);throw new Error(`Route conflict: Multiple routes found for path '${f}'. Routes: ${g.file} and ${h.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}c.set(f,h)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+n.length} files`)}async _scanAdditionalPatterns(e){let r=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(r.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:r,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,r){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let i=e.relativePath,n="/src/"+i.replace(/\\/g,"/");n=n.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(s,e.absolutePath),o=qh(n),h=o===it.HOMEPAGE_COMPONENT?it.HOMEPAGE_PATH:this._resolveRoutePath(a,i,e.absolutePath),f=this._extractPageMeta(i,s),{entity:g,action:m,...p}=a||{};return{path:h,component:o,importPath:n,auth:a?.auth||!1,meta:{...f,...p,entity:f.entity,action:f.action},metaExport:a,file:i}}_extractMetaExport(e,r){try{let s=_n(e,r);return s?(this.logger.debug(`Extracted meta export from ${r}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${r}: ${s.message}`),null}}_generateRoutePath(e){let r=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(r.endsWith("/index")||r==="index")&&(r=r.replace(/\/index$/,"")||"/"),r==="/"?"/":"/"+r.replace(/\/+/g,"/")}_resolveRoutePath(e,r,s){if(!e?.route)return this._generateRoutePath(r);if(typeof e.route=="string"){let i=e.route.trim();return i==="/"?"/":(i=i.replace(/\/+/g,"/"),i.startsWith("/")||(i="/"+i),i)}if(typeof e.route=="object"&&e.route!==null){let i=this._generateRoutePath(r),n=e.route.params;if(Array.isArray(n)&&n.length>0){let a=n.map(o=>`:${o}`).join("/");return`${i}/${a}`}return i}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(r)}_extractPageMeta(e,r){let s=e.split("/").pop()?.replace(".tsx","")||"",i=s.replace(/Page$/,"");i=i.replace(/([A-Z])/g," $1").trim(),i=i.charAt(0).toUpperCase()+i.slice(1);let n=e.split("/"),a=null,o=null;return n.length>1&&(a=n[n.length-2],s.includes("List")?o="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?o="form":(s.includes("Detail")||s.includes("View"))&&(o="detail")),{title:i,entity:a,action:o,file:e}}};function Gh(t,e,r="configuration-error",s={}){let i=`[${t}] ${e}`,n=new Error(i);return n.code=r,n.pluginName=t,n.context=s,n}function In(t,e,r,s={}){return Gh(t,`Required resource missing: ${e}. ${r}`,"missing-required-resource",Object.assign({resourceName:e},s))}import{readFileSync as od}from"node:fs";import{join as cd}from"node:path";function Fn(t){return t?.languages||t?.supportedLanguages||["en"]}function Cn(t){return t?.fallback||t?.fallbackLanguage||"en"}var Fr=class extends G{constructor(e={}){super(tt,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:De.next.middleware,manifestPath:De.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let r=e.routes||[],s=r.filter(n=>n.auth&&n.auth.required).length,i=r.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${i} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(r=>({path:r.path,auth:r.auth,meta:r.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let r=e.routes||[],s={totalRoutes:r.length,authRequired:r.filter(i=>i.auth&&i.auth.required).length,publicRoutes:r.filter(i=>!i.auth||i.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
237
+ `}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let n of a){let i=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),n.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of i){let c=this.pathResolver.getRelativePath(p);if(c.startsWith(`${e}/static/`)){let u=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:u,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Ie=class extends ${constructor(e={}){super(be,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Ce.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.enabled){this.logger.debug("PWA disabled, skipping generation");return}this.options.generateManifest&&await this.generatePWAManifest(e),this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,t,"PWA manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:o,webpack:a}=s;return this.applyViteIgnorePlugin(t,a),!r&&!o&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function ut(l={}){return new Ie(l)}import{createRequire as es}from"node:module";function gt(l,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=l.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...l.matchAll(o)].forEach(i=>{let p=i[1],c=i[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var ce=null,ht=null;function Zt(l){let t=(l.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var se=class extends F{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(ce&&ht===s)return this.logger.debug("Using cached route discovery results"),this.routes=ce.routes,this.errors=ce.errors,this.source=ce.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let o=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(o)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),ce={routes:this.routes,errors:this.errors,source:this.source},ht=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),o=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),n=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=n.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let i=new Map;for(let p of this.routes){let c=p.path;if(i.has(c)){let u=i.get(c);throw new Error(`Route conflict: Multiple routes found for path '${c}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}i.set(c,p)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,o="/src/"+r.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(s,e.absolutePath),n=Zt(o),p=n===ae.HOMEPAGE_COMPONENT?ae.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:h,...g}=a||{};return{path:p,component:n,importPath:o,auth:a?.auth||!1,meta:{...c,...g,entity:c.entity,action:c.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=gt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let a=o.map(n=>`:${n}`).join("/");return`${r}/${a}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z])/g," $1").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),a=null,n=null;return o.length>1&&(a=o[o.length-2],s.includes("List")?n="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?n="form":(s.includes("Detail")||s.includes("View"))&&(n="detail")),{title:r,entity:a,action:n,file:e}}};function Qt(l,e,t="configuration-error",s={}){let r=`[${l}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=l,o.context=s,o}function ft(l,e,t,s={}){return Qt(l,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}import{readFileSync as kr}from"node:fs";import{join as _r}from"node:path";function dt(l){return l?.languages||l?.supportedLanguages||["en"]}function mt(l){return l?.fallback||l?.fallbackLanguage||"en"}var Te=class extends ${constructor(e={}){super(se,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:X.next.middleware,manifestPath:X.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(o=>o.auth&&o.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
239
238
  // Generated at: ${new Date().toISOString()}
240
239
  // Populates _DNDEV_CONFIG_.routes with discovery results
241
240
 
242
- const routeMapping = ${JSON.stringify(r,null,2)};
241
+ const routeMapping = ${JSON.stringify(t,null,2)};
243
242
 
244
243
  const routeManifest = ${JSON.stringify(s,null,2)};
245
244
 
@@ -254,7 +253,7 @@ if (typeof globalThis !== 'undefined') {
254
253
  timestamp: Date.now(),
255
254
  };
256
255
  }
257
- globalThis._DNDEV_CONFIG_.${re.routes} = {
256
+ globalThis._DNDEV_CONFIG_.${O.routes} = {
258
257
  mapping: routeMapping,
259
258
  manifest: routeManifest,
260
259
  };
@@ -264,17 +263,17 @@ if (typeof globalThis !== 'undefined') {
264
263
  export const routes = routeMapping;
265
264
  export const manifest = routeManifest;
266
265
  export default { routes: routeMapping, manifest: routeManifest };
267
- `}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles();let r=0;for(let s of e.routes)await this.generateSingleAppPage(s)&&r++;this.logger.debug(`Successfully generated ${r}/${e.routes.length} app/** page files`)}catch(r){throw this.logger.error(`Failed to generate app/** files: ${r.message}`),r}}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),r=["src/app/**/page.tsx","src/app/[...slug]/page.tsx"],s=await this.pathResolver._globWithNormalization(r,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),i=0;for(let n of s)if(await this.hasGenerationMarker(n))try{await this.pathResolver.remove(n),i++,this.logger.debug(`Cleaned generated file: ${n}`)}catch(a){this.logger.debug(`Could not clean file ${n}: ${a.message}`)}i>0&&this.logger.debug(`Cleaned ${i} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e){try{let r=this.convertRouteToAppPath(e.path),s=`src/app${r}/page.tsx`,i=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(i)&&!await this.hasGenerationMarker(i))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let n={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},a=this.generatePageFileContent(n);return this.writeGeneratedFile(s,a,`app page: ${r}`),!0}catch(r){return this.logger.debug(`Error generating page for route ${e.path}: ${r.message}`),!1}}convertRouteToAppPath(e){if(e===it.HOMEPAGE_PATH)return"";let r=e;return r.startsWith("/")||(r="/"+r),r=r.replace(/\/+/g,"/"),r}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let r=this.pathResolver.getAppRoot(),s=Hh(r),i=s.resolve(e);delete s.cache[i];let n=s(i);return n.default||n.i18nConfig||n}catch(r){return this.logger.debug(`Failed to require i18n config: ${r.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e){let r=this.extractComponentName(e.filePath),s=e.relativePath||e.file,i=this.calculateRelativeImportPath(s,e.path),n=this.isClientComponent(e.filePath),a=e.metaExport&&Object.keys(e.metaExport).length>0,o=this.loadI18nConfig(),c=e.metaExport?.namespace,h=`// Generated by @donotdev/config - DO NOT EDIT
266
+ `}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles();let t=0;for(let s of e.routes)await this.generateSingleAppPage(s)&&t++;this.logger.debug(`Successfully generated ${t}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=["src/app/**/page.tsx","src/app/[...slug]/page.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let o of s)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),r++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(a){this.logger.debug(`Could not clean file ${o}: ${a.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e){try{let t=this.convertRouteToAppPath(e.path),s=`src/app${t}/page.tsx`,r=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(r)&&!await this.hasGenerationMarker(r))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let o={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},a=this.generatePageFileContent(o);return this.writeGeneratedFile(s,a,`app page: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===ae.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=es(t),r=s.resolve(e);delete s.cache[r];let o=s(r);return o.default||o.i18nConfig||o}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e){let t=this.extractComponentName(e.filePath),s=e.relativePath||e.file,r=this.calculateRelativeImportPath(s,e.path),o=this.isClientComponent(e.filePath),a=e.metaExport&&Object.keys(e.metaExport).length>0,n=this.loadI18nConfig(),i=e.metaExport?.namespace,p=`// Generated by @donotdev/config - DO NOT EDIT
268
267
  // This file will be regenerated when src/pages changes
269
268
  // To customize: edit ${e.filePath} or create manual app/** files
270
- ${n?`'use client';
269
+ ${o?`'use client';
271
270
  `:""}
272
- import ${r} from '${i}';
273
- `;return n||(a&&c&&o?h+=this.generateMetadataFunction(e,c,o):a&&(h+=`
271
+ import ${t} from '${r}';
272
+ `;return o||(a&&i&&n?p+=this.generateMetadataFunction(e,i,n):a&&(p+=`
274
273
  export const metadata = ${this.generateMetadataObject(e.metaExport)};
275
- `)),h+=`
276
- export default ${r};
277
- `,h}generateMetadataFunction(e,r,s){let i=Fn(s),n=Cn(s),a="`",o=i.map(c=>` '${c}': { href: ${a}\${baseUrl}\${currentPath}${a} }`).join(`,
274
+ `)),p+=`
275
+ export default ${t};
276
+ `,p}generateMetadataFunction(e,t,s){let r=dt(s),o=mt(s),a="`",n=r.map(i=>` '${i}': { href: ${a}\${baseUrl}\${currentPath}${a} }`).join(`,
278
277
  `);return`
279
278
  import type { Metadata } from 'next';
280
279
  import { readFileSync } from 'node:fs';
@@ -312,8 +311,8 @@ function getTranslationValue(translation, keyPath) {
312
311
 
313
312
  // I18n config (inlined from build-time config)
314
313
  const i18nConfig = ${JSON.stringify(s,null,2)};
315
- const supportedLocales = ${JSON.stringify(i)};
316
- const fallbackLocale = '${n}';
314
+ const supportedLocales = ${JSON.stringify(r)};
315
+ const fallbackLocale = '${o}';
317
316
 
318
317
  export async function generateMetadata({ params }): Promise<Metadata> {
319
318
  // Detect locale from params or use fallback
@@ -329,8 +328,8 @@ export async function generateMetadata({ params }): Promise<Metadata> {
329
328
  const currentPath = '${e.path}';
330
329
 
331
330
  // Read translation for current locale
332
- const translation = readTranslation('${r}', effectiveLocale, i18nConfig) ||
333
- readTranslation('${r}', fallbackLocale, i18nConfig);
331
+ const translation = readTranslation('${t}', effectiveLocale, i18nConfig) ||
332
+ readTranslation('${t}', fallbackLocale, i18nConfig);
334
333
 
335
334
  // Extract metadata from translation
336
335
  const title = getTranslationValue(translation, 'title') || '${e.metaExport?.title||""}';
@@ -380,14 +379,14 @@ export async function generateMetadata({ params }): Promise<Metadata> {
380
379
  },
381
380
  alternates: {
382
381
  languages: {
383
- ${o}
382
+ ${n}
384
383
  },
385
384
  },
386
385
  };
387
386
 
388
387
  return metadata;
389
388
  }
390
- `}generateMetadataObject(e){let r={};return e.title&&(r.title=e.title),e.description&&(r.description=e.description),(e.title||e.description)&&(r.openGraph={},e.title&&(r.openGraph.title=e.title),e.description&&(r.openGraph.description=e.description),r.openGraph.type="website"),(e.title||e.description)&&(r.twitter={card:"summary_large_image"},e.title&&(r.twitter.title=e.title),e.description&&(r.twitter.description=e.description)),Object.keys(e).forEach(s=>{["title","description"].includes(s)||(r[s]=e[s])}),JSON.stringify(r,null,2)}extractComponentName(e){let s=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return s.charAt(0).toUpperCase()+s.slice(1)}async hasGenerationMarker(e){try{let r=await this.pathResolver.read(e,{format:"text"});return r&&r.includes("// Generated by @donotdev/config")}catch{return!1}}async generateMiddleware(e){let r=e.routes.filter(i=>i.auth&&i.auth!==!1&&i.auth.required);if(r.length===0){this.logger.debug("No protected routes found, skipping middleware generation");return}let s=this.generateMiddlewareContent(r);this.writeGeneratedFile(this.options.middlewarePath,s,"middleware")}generateMiddlewareContent(e){let r=e.map(s=>` '${s.path.replace(/\[([^\]]+)\]/g,":$1").replace(/\.\.\./g,"*")}'`).join(`,
389
+ `}generateMetadataObject(e){let t={};return e.title&&(t.title=e.title),e.description&&(t.description=e.description),(e.title||e.description)&&(t.openGraph={},e.title&&(t.openGraph.title=e.title),e.description&&(t.openGraph.description=e.description),t.openGraph.type="website"),(e.title||e.description)&&(t.twitter={card:"summary_large_image"},e.title&&(t.twitter.title=e.title),e.description&&(t.twitter.description=e.description)),Object.keys(e).forEach(s=>{["title","description"].includes(s)||(t[s]=e[s])}),JSON.stringify(t,null,2)}extractComponentName(e){let s=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return s.charAt(0).toUpperCase()+s.slice(1)}async hasGenerationMarker(e){try{let t=await this.pathResolver.read(e,{format:"text"});return t&&t.includes("// Generated by @donotdev/config")}catch{return!1}}async generateMiddleware(e){let t=e.routes.filter(r=>r.auth&&r.auth!==!1&&r.auth.required);if(t.length===0){this.logger.debug("No protected routes found, skipping middleware generation");return}let s=this.generateMiddlewareContent(t);this.writeGeneratedFile(this.options.middlewarePath,s,"middleware")}generateMiddlewareContent(e){let t=e.map(s=>` '${s.path.replace(/\[([^\]]+)\]/g,":$1").replace(/\.\.\./g,"*")}'`).join(`,
391
390
  `);return`// Auto-generated middleware by @donotdev/config
392
391
  // Generated at ${new Date().toISOString()}
393
392
 
@@ -396,7 +395,7 @@ import type { NextRequest } from 'next/server';
396
395
 
397
396
  // Protected route patterns
398
397
  const protectedRoutes = [
399
- ${r}
398
+ ${t}
400
399
  ];
401
400
 
402
401
  // Auth check function (customize as needed)
@@ -453,7 +452,7 @@ export const config = {
453
452
  '/((?!api|_next/static|_next/image|favicon.ico).*)',
454
453
  ],
455
454
  };
456
- `}async generateAppRoutes(e){let r=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",r,"app routes index")}generateAppRoutesContent(e){let r=e.map(s=>{let i=s.componentName||this.pathToComponentName(s.path),n=s.relativePath||s.file;if(!n)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let a=n.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
455
+ `}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),o=s.relativePath||s.file;if(!o)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let a=o.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
457
456
  path: '${s.path}',
458
457
  component: lazy(() => import('${a}')),
459
458
  auth: ${JSON.stringify(s.auth)},
@@ -465,7 +464,7 @@ export const config = {
465
464
  import { lazy } from 'react';
466
465
 
467
466
  export const appRoutes = [
468
- ${r}
467
+ ${t}
469
468
  ];
470
469
 
471
470
  export const routeManifest = {
@@ -475,7 +474,7 @@ export const routeManifest = {
475
474
  };
476
475
 
477
476
  export default appRoutes;
478
- `}async generatePagesRoutes(e){let r=this.generatePagesRoutesContent(e.routes);this.writeGeneratedFile("src/pages/routes.generated.ts",r,"pages routes index")}generatePagesRoutesContent(e){let r=e.map(s=>` '${s.path}': {
477
+ `}async generatePagesRoutes(e){let t=this.generatePagesRoutesContent(e.routes);this.writeGeneratedFile("src/pages/routes.generated.ts",t,"pages routes index")}generatePagesRoutesContent(e){let t=e.map(s=>` '${s.path}': {
479
478
  auth: ${JSON.stringify(s.auth)},
480
479
  meta: ${JSON.stringify(s.meta)},
481
480
  file: '${s.file}'
@@ -484,7 +483,7 @@ export default appRoutes;
484
483
  // Generated at ${new Date().toISOString()}
485
484
 
486
485
  export const pageRoutes = {
487
- ${r}
486
+ ${t}
488
487
  };
489
488
 
490
489
  export const routeManifest = {
@@ -494,17 +493,17 @@ export const routeManifest = {
494
493
  };
495
494
 
496
495
  export default pageRoutes;
497
- `}pathToComponentName(e){return e.split("/").filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")+"Page"}calculateRelativeImportPath(e,r){if(!e)throw new Error("relativePath is required for import path calculation");let i=e.replace(/\.tsx$/,"").replace(/^src\//,""),n=r==="/"?0:r.split("/").filter(Boolean).length;return`${"../".repeat(n+1)}${i}`}isClientComponent(e){try{let r=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(r))return!1;let s=this.pathResolver.readSync(r);return s?s.split(`
498
- `).slice(0,50).some(n=>n.trim()==="'use client';"||n.trim()==='"use client";'):!1}catch{return!1}}};function Dn(t={}){return new Fr(t)}import{readFileSync as Wh,readdirSync as Vh,existsSync as Jh}from"fs";import{join as jn}from"path";var zt=class{constructor(e={}){let{debug:r=!1,generateRobotsTxt:s=!0,generateSitemap:i=!0,baseUrl:n,siteName:a,crawlDelay:o=1,routes:c={},...h}=e;if(!n||!a)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:r,generateRobotsTxt:s,generateSitemap:i,baseUrl:n,siteName:a,crawlDelay:o,routes:c,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...h},this.appRoot=h.appRoot||null,this.logger=W("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,r,s=null){try{let i=this.generateRouteMetaTags(e.routes||[]),n={routes:e.routes||[],routeMetaTags:i,baseUrl:this.options.baseUrl,siteName:this.options.siteName},a=this.discoverBlogPosts(),o={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:n.routes.length,publicRoutes:n.routes.filter(c=>!c.auth||c.auth===!1).length,protectedRoutes:n.routes.filter(c=>c.auth&&c.auth.required).length,blogPosts:a.length};return this.options.generateRobotsTxt&&(o.robotsTxt=await this.generateRobotsTxt(n,r,s)),this.options.generateSitemap&&(o.sitemap=await this.generateSitemap(n,r,s,a)),a.length>0&&(o.rss=await this.generateRSSFeed(a,r,s)),o.manifest=await this.generateManifest(n,r,s),o}catch(i){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${i.message}`),this.logger.error(`Stack: ${i.stack||"No stack trace available"}`),i}}async generateRobotsTxt(e,r,s=null){if(s&&await s("robots.txt"))return this.logger.info("\u2705 robots.txt already exists, skipping generation"),{fileName:"robots.txt",skipped:!0};let i=[];(e.routes||[]).forEach(a=>{if(a.auth&&a.auth.required){let o=a.path.startsWith("/")?a.path:`/${a.path}`;i.push(o)}}),i.push("/admin","/api","/_next","/static");let n=this.generateRobotsTxtContent({disallowedPaths:[...new Set(i)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await r("robots.txt",n),{fileName:"robots.txt",content:n,disallowedPaths:i.length}}async generateSitemap(e,r,s=null,i=[]){if(s&&await s("sitemap.xml"))return this.logger.info("\u2705 sitemap.xml already exists, skipping generation"),{fileName:"sitemap.xml",skipped:!0};let a=(e.routes||[]).filter(c=>!c.auth||c.auth===!1).map(c=>({url:c.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:c.path==="/"?"1.0":"0.8"}));if(i.length>0){a.push({url:"/blog",lastmod:i[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let c of i)a.push({url:`/blog/${c.slug}`,lastmod:c.date,changefreq:"monthly",priority:"0.6"})}let o=this.generateSitemapContent(a);return await r("sitemap.xml",o),{fileName:"sitemap.xml",content:o,publicRoutes:a.length}}async generateManifest(e,r,s=null){if(s&&await s("seo-manifest.json"))return this.logger.info("\u2705 seo-manifest.json already exists, skipping generation"),{fileName:"seo-manifest.json",skipped:!0};let i={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(a=>!a.auth||a.auth===!1).length||0,protectedRoutes:e.routes?.filter(a=>a.auth&&a.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},n=JSON.stringify(i,null,2);return await r("seo-manifest.json",n),{fileName:"seo-manifest.json",content:n,manifest:i}}generateRobotsTxtContent(e={}){let{allowedPaths:r=["/"],disallowedPaths:s=["/admin","/api"],sitemap:i,crawlDelay:n}=e,a=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",o=["User-agent: *",...s.map(c=>`Disallow: ${a(c)}`),...r.map(c=>`Allow: ${a(c)}`)];return n&&o.push(`Crawl-delay: ${n}`),i&&o.push(`Sitemap: ${i}`),o.join(`
496
+ `}pathToComponentName(e){return e.split("/").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")+"Page"}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let r=e.replace(/\.tsx$/,"").replace(/^src\//,""),o=t==="/"?0:t.split("/").filter(Boolean).length;return`${"../".repeat(o+1)}${r}`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let s=this.pathResolver.readSync(t);return s?s.split(`
497
+ `).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function vt(l={}){return new Te(l)}import{readFileSync as ts,readdirSync as ss,existsSync as rs}from"fs";import{join as bt}from"path";var ye=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:a,crawlDelay:n=1,routes:i={},...p}=e;if(!o||!a)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:o,siteName:a,crawlDelay:n,routes:i,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=k("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,s=null){try{let r=this.generateRouteMetaTags(e.routes||[]),o={routes:e.routes||[],routeMetaTags:r,baseUrl:this.options.baseUrl,siteName:this.options.siteName},a=this.discoverBlogPosts(),n={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:o.routes.length,publicRoutes:o.routes.filter(i=>!i.auth||i.auth===!1).length,protectedRoutes:o.routes.filter(i=>i.auth&&i.auth.required).length,blogPosts:a.length};return this.options.generateRobotsTxt&&(n.robotsTxt=await this.generateRobotsTxt(o,t,s)),this.options.generateSitemap&&(n.sitemap=await this.generateSitemap(o,t,s,a)),a.length>0&&(n.rss=await this.generateRSSFeed(a,t,s)),n.manifest=await this.generateManifest(o,t,s),n}catch(r){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`),r}}async generateRobotsTxt(e,t,s=null){if(s&&await s("robots.txt"))return this.logger.info("\u2705 robots.txt already exists, skipping generation"),{fileName:"robots.txt",skipped:!0};let r=[];(e.routes||[]).forEach(a=>{if(a.auth&&a.auth.required){let n=a.path.startsWith("/")?a.path:`/${a.path}`;r.push(n)}}),r.push("/admin","/api","/_next","/static");let o=this.generateRobotsTxtContent({disallowedPaths:[...new Set(r)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",o),{fileName:"robots.txt",content:o,disallowedPaths:r.length}}async generateSitemap(e,t,s=null,r=[]){if(s&&await s("sitemap.xml"))return this.logger.info("\u2705 sitemap.xml already exists, skipping generation"),{fileName:"sitemap.xml",skipped:!0};let a=(e.routes||[]).filter(i=>!i.auth||i.auth===!1).map(i=>({url:i.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:i.path==="/"?"1.0":"0.8"}));if(r.length>0){a.push({url:"/blog",lastmod:r[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let i of r)a.push({url:`/blog/${i.slug}`,lastmod:i.date,changefreq:"monthly",priority:"0.6"})}let n=this.generateSitemapContent(a);return await t("sitemap.xml",n),{fileName:"sitemap.xml",content:n,publicRoutes:a.length}}async generateManifest(e,t,s=null){if(s&&await s("seo-manifest.json"))return this.logger.info("\u2705 seo-manifest.json already exists, skipping generation"),{fileName:"seo-manifest.json",skipped:!0};let r={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(a=>!a.auth||a.auth===!1).length||0,protectedRoutes:e.routes?.filter(a=>a.auth&&a.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},o=JSON.stringify(r,null,2);return await t("seo-manifest.json",o),{fileName:"seo-manifest.json",content:o,manifest:r}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:o}=e,a=i=>i?i==="*"?"*":i.startsWith("/")?i:`/${i}`:"/",n=["User-agent: *",...s.map(i=>`Disallow: ${a(i)}`),...t.map(i=>`Allow: ${a(i)}`)];return o&&n.push(`Crawl-delay: ${o}`),r&&n.push(`Sitemap: ${r}`),n.join(`
499
498
  `)}generateSitemapContent(e){return`<?xml version="1.0" encoding="UTF-8"?>
500
499
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
501
- ${e.map(({url:s,lastmod:i,changefreq:n,priority:a})=>{let o=[` <loc>${this.options.baseUrl}${s}</loc>`];return i&&o.push(` <lastmod>${i}</lastmod>`),n&&o.push(` <changefreq>${n}</changefreq>`),a&&o.push(` <priority>${a}</priority>`),` <url>
502
- ${o.join(`
500
+ ${e.map(({url:s,lastmod:r,changefreq:o,priority:a})=>{let n=[` <loc>${this.options.baseUrl}${s}</loc>`];return r&&n.push(` <lastmod>${r}</lastmod>`),o&&n.push(` <changefreq>${o}</changefreq>`),a&&n.push(` <priority>${a}</priority>`),` <url>
501
+ ${n.join(`
503
502
  `)}
504
503
  </url>`}).join(`
505
504
  `)}
506
- </urlset>`}generateRouteMetaTags(e){return e.map(r=>{let s=this.options.siteName;if(r.meta?.title)s=`${r.meta.title} - ${this.options.siteName}`;else if(r.path!=="/"){let n=r.path.split("/").filter(Boolean);n.length>0&&(s=`${n[n.length-1].split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ")} - ${this.options.siteName}`)}let i=`Welcome to ${this.options.siteName}`;if(r.meta?.description)i=r.meta.description;else if(r.meta?.entity&&r.meta?.action)i=`${r.meta.action} ${r.meta.entity} on ${this.options.siteName}`;else if(r.path!=="/"){let n=r.path.split("/").filter(Boolean);n.length>0&&(i=`Explore ${n[n.length-1].split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:r.path,meta:{title:s,description:i,canonical:`${this.options.baseUrl}${r.path}`,robots:r.auth&&r.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=jn(this.appRoot,"src","content","blog");try{if(!Jh(e))return[];let r=Vh(e).filter(i=>i.endsWith("_en.md"));if(r.length===0)return[];let s=[];for(let i of r){let n=Wh(jn(e,i),"utf-8"),a=i.replace(/_en\.md$/,""),o=n.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(o)for(let h of o[1].split(`
507
- `)){let f=h.indexOf(":");f!==-1&&(c[h.slice(0,f).trim()]=h.slice(f+1).trim())}s.push({slug:a,title:c.title||a,description:c.description||"",date:c.date||new Date().toISOString().split("T")[0],tags:c.tags?c.tags.split(",").map(h=>h.trim()):[],image:c.image||null})}return s.sort((i,n)=>n.date.localeCompare(i.date)),this.logger.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(r){return this.logger.debug(`Blog content discovery skipped: ${r.message}`),[]}}async generateRSSFeed(e,r,s=null){if(s&&await s("rss.xml"))return this.logger.info("\u2705 rss.xml already exists, skipping generation"),{fileName:"rss.xml",skipped:!0};let i=e.map(a=>` <item>
505
+ </urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(r=`Explore ${o[o.length-1].split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=bt(this.appRoot,"src","content","blog");try{if(!rs(e))return[];let t=ss(e).filter(r=>r.endsWith("_en.md"));if(t.length===0)return[];let s=[];for(let r of t){let o=ts(bt(e,r),"utf-8"),a=r.replace(/_en\.md$/,""),n=o.match(/^---\r?\n([\s\S]*?)\r?\n---/),i={};if(n)for(let p of n[1].split(`
506
+ `)){let c=p.indexOf(":");c!==-1&&(i[p.slice(0,c).trim()]=p.slice(c+1).trim())}s.push({slug:a,title:i.title||a,description:i.description||"",date:i.date||new Date().toISOString().split("T")[0],tags:i.tags?i.tags.split(",").map(p=>p.trim()):[],image:i.image||null})}return s.sort((r,o)=>o.date.localeCompare(r.date)),this.logger.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(t){return this.logger.debug(`Blog content discovery skipped: ${t.message}`),[]}}async generateRSSFeed(e,t,s=null){if(s&&await s("rss.xml"))return this.logger.info("\u2705 rss.xml already exists, skipping generation"),{fileName:"rss.xml",skipped:!0};let r=e.map(a=>` <item>
508
507
  <title><![CDATA[${a.title}]]></title>
509
508
  <link>${this.options.baseUrl}/blog/${a.slug}</link>
510
509
  <guid>${this.options.baseUrl}/blog/${a.slug}</guid>
@@ -513,7 +512,7 @@ ${o.join(`
513
512
  <category>${a.tags.join(", ")}</category>`:""}${a.image?`
514
513
  <enclosure url="${this.options.baseUrl}${a.image}" type="image/png" length="0"/>`:""}
515
514
  </item>`).join(`
516
- `),n=`<?xml version="1.0" encoding="UTF-8"?>
515
+ `),o=`<?xml version="1.0" encoding="UTF-8"?>
517
516
  <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
518
517
  <channel>
519
518
  <title>${this.options.siteName}</title>
@@ -521,14 +520,14 @@ ${o.join(`
521
520
  <description>${this.options.siteName} Blog</description>
522
521
  <language>en</language>
523
522
  <atom:link href="${this.options.baseUrl}/rss.xml" rel="self" type="application/rss+xml"/>
524
- ${i}
523
+ ${r}
525
524
  </channel>
526
- </rss>`;return await r("rss.xml",n),{fileName:"rss.xml",content:n,postCount:e.length}}getGenerationSummary(e){let r=e.routes?.length||0,s=e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,i=e.routes?.filter(n=>n.auth&&n.auth.required).length||0;return`${r} routes (${s} public, ${i} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(r=>!r.auth||r.auth===!1).length||0,protectedRoutes:e.routes?.filter(r=>r.auth&&r.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}};var Cr=class extends G{constructor(e={}){super(tt,e);let r=D.getInstance(),s=W("SEO Handler",this.options.debug,this.options.verbose),i=process.env.NEXT_PUBLIC_APP_URL||null;i&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${i}`);let n=e.seo?.baseUrl;if(!n&&i){let c=i.trim().replace(/\/+$/,"");n=/^https?:\/\//i.test(c)?c:`https://${c}`}n?s.debug(`Found app URL: ${n}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let a=e.siteName||e.seo?.siteName||null;if(s.verbose(`Name: ${a||"Not found"}`),s.verbose(`URL: ${n||"Not found"}`),a&&s.debug(` - Site name from appConfig: "${a}"`),e.seo?.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let o=[];if(n||o.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),a||o.push("siteName (APP_NAME in src/config/app.ts)"),o.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),o.forEach(c=>s.warn(` - ${c}`)),s.warn(""),s.warn(" To fix:"),n||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),a||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this.seoGenerator=new zt({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:n,siteName:a,crawlDelay:this.options.crawlDelay,appRoot:r.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let r=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(r))e=await this.pathResolver.read(r,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(r){this.logger.debug(`Could not load route manifest for SEO: ${r.message}`);return}try{let r=async(n,a)=>{if(!n){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${n}`,a,n)},s=async n=>{try{let a=this.pathResolver.resolveAppPath(`public/${n}`);return this.pathResolver.pathExists(a)}catch{return!1}},i=await this.seoGenerator.generateSEOFiles(e,r,s);i.robotsTxt&&!i.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${i.robotsTxt.disallowedPaths||0} disallowed paths`),i.sitemap&&!i.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${i.sitemap.publicRoutes||0} routes`),i.rss&&!i.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${i.rss.postCount||0} blog posts`),i.manifest&&!i.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json")}catch(r){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`)}}}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function Tn(t={}){return new Cr(t)}function Ln(t={}){let{debug:e}=t;return(r={})=>({...r,webpack:(s,i)=>{let{isServer:n}=i;return n||(s.externals||(s.externals={}),zr.forEach(a=>{s.externals[a]=`commonjs ${a}`})),r.webpack?r.webpack(s,i):s}})}var Bt=class extends Q{constructor(e,r,s={}){super(r,s),this.cssExtractor=e||new Re(r,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:r,consumerFiles:s}=e;this.logger.debug(`Scanning ${r.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",r),this.logger.debug("Consumer files:",s),r.length>0?(this.logger.debug(`Framework files found: ${r.length}`),this.logger.debug("Framework files:",r)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(r),await this._processConsumerFiles(s);let i=this._serializeThemes();return this.logger.debug(`Discovered ${i.length} themes:`,i.map(n=>n.name)),{themes:i,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return Xt.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let r of e)try{let s=await this.pathResolver.read(r,{format:"text"}),i=this.pathResolver.normalizePath(r);this.cssExtractor.extractThemes(s,i,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(i)}`)}catch(s){this.logger.debug(`Error scanning framework file ${r}: ${s.message}`)}}async _processConsumerFiles(e){for(let r of e)try{let s=await this.pathResolver.read(r,{format:"text"}),i=this.pathResolver.normalizePath(r);this.cssExtractor.extractThemes(s,i,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(i)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${r}: ${s.message}`)}}_addEssentialThemes(){Xt.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var Dr=class extends G{constructor(e={}){super(Bt,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new Re(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let r=e.themes||[],s=r.filter(n=>!n.essential).length,i=r.length;if(i===0)throw In("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${i} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:r,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
525
+ </rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}};var je=class extends ${constructor(e={}){super(se,e);let t=P.getInstance(),s=k("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let o=e.seo?.baseUrl;if(!o&&r){let i=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(i)?i:`https://${i}`}o?s.debug(`Found app URL: ${o}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let a=e.siteName||e.seo?.siteName||null;if(s.verbose(`Name: ${a||"Not found"}`),s.verbose(`URL: ${o||"Not found"}`),a&&s.debug(` - Site name from appConfig: "${a}"`),e.seo?.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let n=[];if(o||n.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),a||n.push("siteName (APP_NAME in src/config/app.ts)"),n.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),n.forEach(i=>s.warn(` - ${i}`)),s.warn(""),s.warn(" To fix:"),o||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),a||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this.seoGenerator=new ye({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:o,siteName:a,crawlDelay:this.options.crawlDelay,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(o,a)=>{if(!o){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${o}`,a,o)},s=async o=>{try{let a=this.pathResolver.resolveAppPath(`public/${o}`);return this.pathResolver.pathExists(a)}catch{return!1}},r=await this.seoGenerator.generateSEOFiles(e,t,s);r.robotsTxt&&!r.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${r.robotsTxt.disallowedPaths||0} disallowed paths`),r.sitemap&&!r.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${r.sitemap.publicRoutes||0} routes`),r.rss&&!r.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${r.rss.postCount||0} blog posts`),r.manifest&&!r.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json")}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function yt(l={}){return new je(l)}function wt(l={}){let{debug:e}=l;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),We.forEach(a=>{s.externals[a]=`commonjs ${a}`})),t.webpack?t.webpack(s,r):s}})}var we=class extends F{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new H(t,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:s}=e;this.logger.debug(`Scanning ${t.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",s),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t),await this._processConsumerFiles(s);let r=this._serializeThemes();return this.logger.debug(`Discovered ${r.length} themes:`,r.map(o=>o.name)),{themes:r,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return _e.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning framework file ${t}: ${s.message}`)}}async _processConsumerFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${t}: ${s.message}`)}}_addEssentialThemes(){_e.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var Me=class extends ${constructor(e={}){super(we,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new H(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(o=>!o.essential).length,r=t.length;if(r===0)throw ft("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
527
526
  // Generated at: ${new Date().toISOString()}
528
527
  // Populates _DNDEV_CONFIG_ with discovery results
529
528
 
530
529
  const themeConfig = {
531
- discovered: ${JSON.stringify(r,null,2)},
530
+ discovered: ${JSON.stringify(t,null,2)},
532
531
  variables: ${JSON.stringify(s,null,2)},
533
532
  utilities: {
534
533
  framework: ${JSON.stringify(s.framework,null,2)},
@@ -536,7 +535,7 @@ const themeConfig = {
536
535
  all: ${JSON.stringify(s.all,null,2)},
537
536
  },
538
537
  manifest: {
539
- totalThemes: ${r.length},
538
+ totalThemes: ${t.length},
540
539
  totalVariables: ${s.all.length},
541
540
  frameworkVariables: ${s.framework.length},
542
541
  consumerVariables: ${s.consumer.length},
@@ -555,7 +554,7 @@ if (typeof globalThis !== 'undefined') {
555
554
  timestamp: Date.now(),
556
555
  };
557
556
  }
558
- globalThis._DNDEV_CONFIG_.${re.themes} = themeConfig;
557
+ globalThis._DNDEV_CONFIG_.${O.themes} = themeConfig;
559
558
  }
560
559
 
561
560
  // Export for compatibility
@@ -571,26 +570,6 @@ export function useTheme() {
571
570
  }
572
571
 
573
572
  export default useTheme;
574
- `}};function On(t={}){return new Dr(t)}function Mn({debug:t,verbose:e,generateManifest:r,routeOptions:s,themeOptions:i,i18nOptions:n,assetOptions:a,seoOptions:o,pwaOptions:c,serverShimOptions:h,appUrl:f,isDev:g,logger:m}){let p=s.debug??t,R=i.debug??t,C=n.debug??t,J=a.debug??t,ze=o.debug??t,ue=c.debug??t,_e=h.debug??t,Ne=s.verbose??e,Be=i.verbose??e,Ie=n.verbose??e,X=a.verbose??e,fe=o.verbose??e,rt=c.verbose??e,Ue=h.verbose??e,y={debug:t,verbose:e,generateManifest:r},Pe=s.disabled?null:Dn({...y,...s,debug:p,verbose:Ne});t&&m.debug(`Route handler created: ${Pe?"enabled":"disabled"} (debug: ${p})`);let de=On({...y,...i,debug:R,verbose:Be}),te=kn({...y,...n,debug:C,verbose:Ie}),Fe=Sn({...y,...a,debug:J,verbose:X}),S=Tn({...y,...o,debug:ze,verbose:fe,appUrl:f,isDev:g}),k=An({...y,...c,debug:ue,verbose:rt}),A=Ln({...y,...h,debug:_e,verbose:Ue});return{routeHandler:Pe,themeHandler:de,i18nHandler:te,assetHandler:Fe,seoHandler:S,pwaHandler:k,serverShimHandler:A}}function zn(t,e){let r={};if(t.routeHandler)try{r.routeConfig=t.routeHandler.createNextConfig()}catch(i){e.error(`Route handler failed during config creation: ${i.message}`),e.error(`Stack: ${i.stack||"No stack trace available"}`),r.routeConfig=()=>({})}else r.routeConfig=()=>({});let s=[{name:"theme",handler:t.themeHandler},{name:"i18n",handler:t.i18nHandler},{name:"asset",handler:t.assetHandler},{name:"seo",handler:t.seoHandler},{name:"pwa",handler:t.pwaHandler}];for(let{name:i,handler:n}of s)try{r[`${i}Config`]=n.createNextConfig()}catch(a){e.error(`${i.charAt(0).toUpperCase()+i.slice(1)} handler failed: ${a.message}`),e.error(`Stack: ${a.stack||"No stack trace available"}`),r[`${i}Config`]=()=>({})}try{r.serverShimConfig=t.serverShimHandler}catch(i){e.error(`ServerShim handler failed: ${i.message}`),e.error(`Stack: ${i.stack||"No stack trace available"}`),r.serverShimConfig=()=>({})}return r}import{readFileSync as Xh}from"node:fs";import{createRequire as Yh}from"node:module";import{join as Kh}from"node:path";var Qh=Yh(import.meta.url);function Zh(t){if(!t)return[];try{let e=Kh(t,"package.json"),r=JSON.parse(Xh(e,"utf8")),s=new Set;if(r.peerDependenciesMeta)for(let[i,n]of Object.entries(r.peerDependenciesMeta))n?.optional&&s.add(i);if(r.optionalDependencies)for(let i of Object.keys(r.optionalDependencies))s.add(i);return Array.from(s)}catch{return[]}}function eu(t){let e=bt.optionalFeatures||[],r=Zh(t);return[...new Set([...e,...r])]}function jr(t){let e=eu(t),r=[],s=[];for(let i of e)try{Qh.resolve(i,{paths:[t||process.cwd()]}),s.push(i)}catch{r.push(i)}return{missing:r,installed:s}}function tu(t={}){let{port:e,...r}=t;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let pe=process.env.CI==="true";process.env.DNDEV_BUILD_ID=pe?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let{appConfig:s,...i}=r;if(!s)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let n=s?.features?{debug:s.features.debug}:void 0,a=s?.seo&&typeof s.seo!="boolean"?{...s.seo,siteName:s.seo.siteName||s.app?.name}:s?.app?.name?{siteName:s.app.name}:void 0,o=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:c,seo:h,...f}=i,g={...n?{features:n}:{},...a?{seo:a}:{},...f},m=is(g),p=ns(m);if(!p)throw new Error("normalizeOptions returned undefined");let{generateManifest:R,debug:C,verbose:J,mode:ze,isDev:ue,routeOptions:_e,themeOptions:Ne,i18nOptions:Be,assetOptions:Ie,pwaOptions:X,seoOptions:fe,serverShimOptions:rt,nextConfigOptions:Ue}=p,y=W("next-config",C,J),{appRoot:Pe,appRootSet:de}=Wr({logger:y,debug:C}),te=!1,Fe=!1,{installed:S}=jr(process.cwd()),k=Object.values(Mr.packageNames),A=k.filter(pe=>!S.includes(pe)),U=k.filter(pe=>S.includes(pe)),gt=process.env.DNDEV_BUILD_ID,Ut=_e?.routingMode||"app";if(y.info(`
575
- \u{1F3D7}\uFE0F DnDev Framework - Building for ${ze}${gt?` [build:${gt}]`:""}`),y.info(` Platform: Next.js | Routing: ${Ut}
576
- `),ue){let pe=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${pe}`,C&&(y.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&y.debug(`Port configured: ${pe} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||y.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let Y=Mn({debug:C,verbose:J,generateManifest:R,routeOptions:_e,themeOptions:Ne,i18nOptions:Be,assetOptions:Ie,seoOptions:fe,pwaOptions:X,serverShimOptions:rt,isDev:ue,logger:y}),ge=zn(Y,y);return async function(qt={}){let st=D.getInstance(),pt=de?Vr():[];C&&pt.length>0&&y.debug(`Discovered ${pt.length} packages: ${pt.join(", ")}`);let{missing:Gt}=jr(st.getAppRoot());C&&Gt.length>0&&y.debug(`Missing optional deps (will alias to empty): ${Gt.join(", ")}`);let Tr=st.getAppRoot();if(de&&!te){let Ht=st.resolveAppPath(".dndev-build"),Wt=process.env.DNDEV_BUILD_ID;try{st.readSync(Ht,{format:"text"})?.trim()===Wt?(y.debug("Discoveries already completed by another worker, skipping"),te=!0):(Kt(Tr,y),await Qt(Y,y),te=!0)}catch{Kt(Tr,y),await Qt(Y,y),te=!0}}let Ce=typeof qt=="object"&&qt!==null?qt:{},{webpack:Un,rewrites:qn,...Gn}=Ce;de&&!Fe&&(Fe=await rs(Y.assetHandler,y,Fe));let Hn=ge.routeConfig(Ce),Wn=ge.themeConfig(Ce),Vn=ge.i18nConfig(Ce),Jn=ge.assetConfig(Ce),Xn=ge.seoConfig(Ce),Yn=ge.pwaConfig(Ce),Kn=ge.serverShimConfig(),Qn=Qr({originalWebpack:Un,unusedFeaturePackages:A,usedFeaturePackages:U,logger:y,debug:C}),Zn=Zr({originalRewrites:qn,handlers:[Y.routeHandler,Y.themeHandler,Y.i18nHandler,Y.assetHandler,Y.pwaHandler],logger:y}),ea={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()}),...process.env.NEXT_PUBLIC_APP_URL?{NEXT_PUBLIC_APP_URL:process.env.NEXT_PUBLIC_APP_URL}:{},...process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY?{NEXT_PUBLIC_DONOTDEV_LICENSE_KEY:process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY}:{}},ta=es({routeResult:Hn,themeResult:Wn,i18nResult:Vn,assetResult:Jn,seoResult:Xn,pwaResult:Yn,serverShimResult:Kn,restNextConfig:Gn,discoveredPackages:pt,webpackConfig:Qn,rewritesConfig:Zn,missingOptionalDeps:Gt,env:ea,logger:y});if(y.debug("Next.js config generated"),de){let Ht=o?.name||"app",Wt=st.getAppRoot();y.info(`Name: ${Ht}`),y.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),y.info("\u{1F527} Features: auto-detected"),y.info(`App root (final): ${Wt}`)}return ta}}var Bn=tu;export{Bn as default,Bn as defineNextConfig};
577
- /*! Bundled license information:
578
-
579
- sharp/lib/is.js:
580
- sharp/lib/libvips.js:
581
- sharp/lib/sharp.js:
582
- sharp/lib/constructor.js:
583
- sharp/lib/input.js:
584
- sharp/lib/resize.js:
585
- sharp/lib/composite.js:
586
- sharp/lib/operation.js:
587
- sharp/lib/colour.js:
588
- sharp/lib/channel.js:
589
- sharp/lib/output.js:
590
- sharp/lib/utility.js:
591
- sharp/lib/index.js:
592
- (*!
593
- Copyright 2013 Lovell Fuller and others.
594
- SPDX-License-Identifier: Apache-2.0
595
- *)
596
- */
573
+ `}};function Pt(l={}){return new Me(l)}function Rt({debug:l,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:a,seoOptions:n,pwaOptions:i,serverShimOptions:p,appUrl:c,isDev:u,logger:h}){let g=s.debug??l,d=r.debug??l,w=o.debug??l,A=a.debug??l,Z=n.debug??l,T=i.debug??l,V=p.debug??l,J=s.verbose??e,Q=r.verbose??e,q=o.verbose??e,_=a.verbose??e,j=n.verbose??e,re=i.verbose??e,ee=p.verbose??e,f={debug:l,verbose:e,generateManifest:t},W=s.disabled?null:vt({...f,...s,debug:g,verbose:J});l&&h.debug(`Route handler created: ${W?"enabled":"disabled"} (debug: ${g})`);let M=Pt({...f,...r,debug:d,verbose:Q}),C=pt({...f,...o,debug:w,verbose:q}),Y=ct({...f,...a,debug:A,verbose:_}),v=yt({...f,...n,debug:Z,verbose:j,appUrl:c,isDev:u}),b=ut({...f,...i,debug:T,verbose:re}),y=wt({...f,...p,debug:V,verbose:ee});return{routeHandler:W,themeHandler:M,i18nHandler:C,assetHandler:Y,seoHandler:v,pwaHandler:b,serverShimHandler:y}}function St(l,e){let t={};if(l.routeHandler)try{t.routeConfig=l.routeHandler.createNextConfig()}catch(r){e.error(`Route handler failed during config creation: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.routeConfig=()=>({})}else t.routeConfig=()=>({});let s=[{name:"theme",handler:l.themeHandler},{name:"i18n",handler:l.i18nHandler},{name:"asset",handler:l.assetHandler},{name:"seo",handler:l.seoHandler},{name:"pwa",handler:l.pwaHandler}];for(let{name:r,handler:o}of s)try{t[`${r}Config`]=o.createNextConfig()}catch(a){e.error(`${r.charAt(0).toUpperCase()+r.slice(1)} handler failed: ${a.message}`),e.error(`Stack: ${a.stack||"No stack trace available"}`),t[`${r}Config`]=()=>({})}try{t.serverShimConfig=l.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}import{readFileSync as os}from"node:fs";import{createRequire as as}from"node:module";import{join as ns}from"node:path";var is=as(import.meta.url);function ls(l){if(!l)return[];try{let e=ns(l,"package.json"),t=JSON.parse(os(e,"utf8")),s=new Set;if(t.peerDependenciesMeta)for(let[r,o]of Object.entries(t.peerDependenciesMeta))o?.optional&&s.add(r);if(t.optionalDependencies)for(let r of Object.keys(t.optionalDependencies))s.add(r);return Array.from(s)}catch{return[]}}function cs(l){let e=he.optionalFeatures||[],t=ls(l);return[...new Set([...e,...t])]}function ze(l){let e=cs(l),t=[],s=[];for(let r of e)try{is.resolve(r,{paths:[l||process.cwd()]}),s.push(r)}catch{t.push(r)}return{missing:t,installed:s}}function ps(l={}){let{port:e,...t}=l;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let L=process.env.CI==="true";process.env.DNDEV_BUILD_ID=L?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let{appConfig:s,...r}=t;if(!s)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let o=s?.features?{debug:s.features.debug}:void 0,a=s?.seo&&typeof s.seo!="boolean"?{...s.seo,siteName:s.seo.siteName||s.app?.name}:s?.app?.name?{siteName:s.app.name}:void 0,n=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:i,seo:p,...c}=r,u={...o?{features:o}:{},...a?{seo:a}:{},...c},h=it(u),g=lt(h);if(!g)throw new Error("normalizeOptions returned undefined");let{generateManifest:d,debug:w,verbose:A,mode:Z,isDev:T,routeOptions:V,themeOptions:J,i18nOptions:Q,assetOptions:q,pwaOptions:_,seoOptions:j,serverShimOptions:re,nextConfigOptions:ee}=g,f=k("next-config",w,A),{appRoot:W,appRootSet:M}=Ye({logger:f,debug:w}),C=!1,Y=!1,{installed:v}=ze(process.cwd()),b=Object.values(Ge.packageNames),y=b.filter(L=>!v.includes(L)),S=b.filter(L=>v.includes(L)),pe=process.env.DNDEV_BUILD_ID,Pe=V?.routingMode||"app";if(f.info(`
574
+ \u{1F3D7}\uFE0F DnDev Framework - Building for ${Z}${pe?` [build:${pe}]`:""}`),f.info(` Platform: Next.js | Routing: ${Pe}
575
+ `),T){let L=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${L}`,w&&(f.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&f.debug(`Port configured: ${L} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||f.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let E=Rt({debug:w,verbose:A,generateManifest:d,routeOptions:V,themeOptions:J,i18nOptions:Q,assetOptions:q,seoOptions:j,pwaOptions:_,serverShimOptions:re,isDev:T,logger:f}),z=St(E,f);return async function(Re={}){let oe=P.getInstance(),ue=M?Ke():[];w&&ue.length>0&&f.debug(`Discovered ${ue.length} packages: ${ue.join(", ")}`);let{missing:Se}=ze(oe.getAppRoot());w&&Se.length>0&&f.debug(`Missing optional deps (will alias to empty): ${Se.join(", ")}`);let Le=oe.getAppRoot();if(M&&!C){let $e=oe.resolveAppPath(".dndev-build"),xe=process.env.DNDEV_BUILD_ID;try{oe.readSync($e,{format:"text"})?.trim()===xe?(f.debug("Discoveries already completed by another worker, skipping"),C=!0):(Ne(Le,f),await Fe(E,f),C=!0)}catch{Ne(Le,f),await Fe(E,f),C=!0}}let K=typeof Re=="object"&&Re!==null?Re:{},{webpack:xt,rewrites:kt,...At}=K;M&&!Y&&(Y=await at(E.assetHandler,f,Y));let _t=z.routeConfig(K),Et=z.themeConfig(K),Nt=z.i18nConfig(K),Ft=z.assetConfig(K),Dt=z.seoConfig(K),Ct=z.pwaConfig(K),Ot=z.serverShimConfig(),It=tt({originalWebpack:xt,unusedFeaturePackages:y,usedFeaturePackages:S,logger:f,debug:w}),Tt=st({originalRewrites:kt,handlers:[E.routeHandler,E.themeHandler,E.i18nHandler,E.assetHandler,E.pwaHandler],logger:f}),jt={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()}),...process.env.NEXT_PUBLIC_APP_URL?{NEXT_PUBLIC_APP_URL:process.env.NEXT_PUBLIC_APP_URL}:{},...process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY?{NEXT_PUBLIC_DONOTDEV_LICENSE_KEY:process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY}:{}},Mt=rt({routeResult:_t,themeResult:Et,i18nResult:Nt,assetResult:Ft,seoResult:Dt,pwaResult:Ct,serverShimResult:Ot,restNextConfig:At,discoveredPackages:ue,webpackConfig:It,rewritesConfig:Tt,missingOptionalDeps:Se,env:jt,logger:f});if(f.debug("Next.js config generated"),M){let $e=n?.name||"app",xe=oe.getAppRoot();f.info(`Name: ${$e}`),f.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),f.info("\u{1F527} Features: auto-detected"),f.info(`App root (final): ${xe}`)}return Mt}}var $t=ps;export{$t as default,$t as defineNextConfig};