@donotdev/core 0.0.45 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE.md +3 -3
  2. package/empty.cjs +2 -2
  3. package/empty.js +5 -2
  4. package/functions/index.d.ts +11 -11
  5. package/functions/index.js +7 -7
  6. package/index.d.ts +1125 -841
  7. package/index.js +37 -37
  8. package/next/index.d.ts +51 -18
  9. package/next/index.js +69 -59
  10. package/package.json +2 -2
  11. package/server.d.ts +718 -590
  12. package/server.js +1 -1
  13. package/vite/index.d.ts +57 -24
  14. package/vite/index.js +92 -76
  15. package/i18n/locales/lazy/entityFormTemplate_ar.json +0 -85
  16. package/i18n/locales/lazy/entityFormTemplate_da.json +0 -85
  17. package/i18n/locales/lazy/entityFormTemplate_de.json +0 -85
  18. package/i18n/locales/lazy/entityFormTemplate_en.json +0 -85
  19. package/i18n/locales/lazy/entityFormTemplate_es.json +0 -85
  20. package/i18n/locales/lazy/entityFormTemplate_fr.json +0 -85
  21. package/i18n/locales/lazy/entityFormTemplate_it.json +0 -85
  22. package/i18n/locales/lazy/entityFormTemplate_ja.json +0 -85
  23. package/i18n/locales/lazy/entityFormTemplate_ko.json +0 -85
  24. package/i18n/locales/lazy/entityFormTemplate_nl.json +0 -85
  25. package/i18n/locales/lazy/loginTemplate_ar.json +0 -26
  26. package/i18n/locales/lazy/loginTemplate_da.json +0 -21
  27. package/i18n/locales/lazy/loginTemplate_de.json +0 -26
  28. package/i18n/locales/lazy/loginTemplate_en.json +0 -26
  29. package/i18n/locales/lazy/loginTemplate_es.json +0 -26
  30. package/i18n/locales/lazy/loginTemplate_fr.json +0 -26
  31. package/i18n/locales/lazy/loginTemplate_it.json +0 -26
  32. package/i18n/locales/lazy/loginTemplate_ja.json +0 -26
  33. package/i18n/locales/lazy/loginTemplate_ko.json +0 -26
  34. package/i18n/locales/lazy/loginTemplate_nl.json +0 -21
  35. package/i18n/locales/lazy/profileDBTemplate_ar.json +0 -73
  36. package/i18n/locales/lazy/profileDBTemplate_da.json +0 -73
  37. package/i18n/locales/lazy/profileDBTemplate_de.json +0 -73
  38. package/i18n/locales/lazy/profileDBTemplate_en.json +0 -73
  39. package/i18n/locales/lazy/profileDBTemplate_es.json +0 -73
  40. package/i18n/locales/lazy/profileDBTemplate_fr.json +0 -73
  41. package/i18n/locales/lazy/profileDBTemplate_it.json +0 -73
  42. package/i18n/locales/lazy/profileDBTemplate_ja.json +0 -73
  43. package/i18n/locales/lazy/profileDBTemplate_ko.json +0 -73
  44. package/i18n/locales/lazy/profileDBTemplate_nl.json +0 -73
  45. package/i18n/locales/lazy/profileTemplate_ar.json +0 -85
  46. package/i18n/locales/lazy/profileTemplate_da.json +0 -85
  47. package/i18n/locales/lazy/profileTemplate_de.json +0 -85
  48. package/i18n/locales/lazy/profileTemplate_en.json +0 -85
  49. package/i18n/locales/lazy/profileTemplate_es.json +0 -85
  50. package/i18n/locales/lazy/profileTemplate_fr.json +0 -85
  51. package/i18n/locales/lazy/profileTemplate_it.json +0 -85
  52. package/i18n/locales/lazy/profileTemplate_ja.json +0 -85
  53. package/i18n/locales/lazy/profileTemplate_ko.json +0 -85
  54. package/i18n/locales/lazy/profileTemplate_nl.json +0 -85
package/vite/index.js CHANGED
@@ -1,11 +1,11 @@
1
- var es=Object.defineProperty;var Ue=(n,e)=>()=>(n&&(e=n(n=0)),e);var ts=(n,e)=>{for(var t in e)es(n,t,{get:e[t],enumerable:!0})};function it(n,e=null){let t=se[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Te(n){return nt[n]||nt.base}var Ge,M,V,j,Be,Ee,Oe,se,ye,at,Ve,He,Re,Je,nt,L=Ue(()=>{"use strict";Ge={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},M={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env"},V={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},j={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",configEnv:"src/config/dndev-config-env.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"}},Be={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},Ee={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Oe={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"},se={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:[`${Oe.SOURCE_EAGER}/*_*.json`],lazy:[`${Oe.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/**"]},ye={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"],optionalFeatures:[],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"]},at=["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"],Ve=["@donotdev/core/functions","@donotdev/core/server"],He={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)/}},Re={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},Je=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],nt={base:{absolute:!0,onlyFiles:!0,ignore:se.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...se.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...se.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:se.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:se.globalIgnore}}});import*as E from"node:fs";import"node:fs";import{createRequire as ls}from"node:module";import{resolve as Fe,join as fe,dirname as be,relative as lt,normalize as cs,sep as ct,extname as us}from"node:path";import"node:url";import ps from"fast-glob";function ut(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var we,U,pt,$,B=Ue(()=>{"use strict";L();we={getGlobOptionsFor:Te||void 0,SCAN_PATTERNS:se||void 0,getPatternsFor:it||void 0,I18N_PATHS:Oe||void 0},U={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};pt={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"},$=class n{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._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,n._instance=this}normalizePath(e){if(!e)return"";try{return cs(e).split(ct).join("/")}catch{return String(e).split(ct).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=lt(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(be(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=ls(fe(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/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}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=Fe(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Fe(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=Fe(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=E.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:us(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 E.promises.readFile(e);let a=await E.promises.readFile(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&U.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 E.readFileSync(e);let a=E.readFileSync(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&U.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(be(l)),c=this.pathExists(l);if(c&&!o)return i&&U.info(`Skipping existing file: ${l}`),!1;if(a)return U.info(`[DRY RUN] Would write file: ${l}`),!0;try{await E.promises.mkdir(u,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await ut(async()=>(Buffer.isBuffer(g)?await E.promises.writeFile(l,g):await E.promises.writeFile(l,g,"utf8"),i&&U.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(be(l)),c=this.pathExists(l);if(c&&!o)return i&&U.info(`Skipping existing file: ${l}`),!1;if(a)return U.info(`[DRY RUN] Would write file: ${l}`),!0;try{E.mkdirSync(u,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return Buffer.isBuffer(g)?E.writeFileSync(l,g):E.writeFileSync(l,g,"utf8"),i&&U.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(d){throw new Error(`Failed to write file: ${l}: ${d instanceof Error?d.message:String(d)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&U.info(`Skipping existing file: ${i}`),!1;if(o)return U.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(be(i));try{await E.promises.mkdir(u,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await ut(async()=>(await E.promises.copyFile(e,i),a&&U.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&U.info(`Skipping existing file: ${i}`),!1;if(o)return U.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(be(i));try{E.mkdirSync(u,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return E.copyFileSync(e,i),a&&U.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return E.existsSync(e)}catch(s){return t||U.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 E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return E.readdirSync(e,t)}catch(s){return this.options.debug&&U.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return E.statSync(e)}catch(t){return this.options.debug&&U.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return E.realpathSync(e)}watch(e,t,s){return E.watch(e,t,s)}lstatSync(e){try{return E.lstatSync(e)}catch(t){return this.options.debug&&U.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await E.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{E.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await E.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){E.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return E.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=fe(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Fe(e)),s=this.getAppRoot(),r=lt(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(fe(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=r.startsWith(a)?r.slice(a.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:we.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=we.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(fe(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await ps(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=we.getGlobOptionsFor?we.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),i=e.framework.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),u={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=i.length>0?await this._globWithNormalization(i,u):[],p=await this._globWithNormalization(l,u);return{frameworkFiles:c,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!we.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=we.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=r,u={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let a=r,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(fe(t,pt.TOOLING)),a=this.normalizePath(fe(t,pt.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=fe(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(fe(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(be(t))===t)return t;let u=this.normalizePath(be(t));if(u===t)break;t=u,s++}return this.normalizePath(e)}}});var Kt={};ts(Kt,{createDndevPlugin:()=>xr});import{execSync as K,execFileSync as et,spawn as Js}from"node:child_process";function J(){return $.getInstance()}function Z(){return J().getRepoRoot()}function Ht(){return J().resolveRepoPath(".dndev")}function f(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function ge(n,e=qs){return new Promise((t,s)=>{let r="",o=0;n.on("data",a=>{if(o+=a.length,o>e){n.destroy(),s(new Error("Request body too large"));return}r+=a.toString()}),n.on("end",()=>t(r)),n.on("error",s)})}function Ys(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function Ks(){let n=J(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",o=K(r,{encoding:"utf8"}).trim().split(`
2
- `)[0];e.push(o)}catch{}let s=[process.env.NVM_DIR,n.resolvePath(".nvm",t)].filter(Boolean);for(let r of s)try{let o=n.resolvePath("versions/node",r),a=n.readdirSync(o).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/bin/node`,o))}catch{}if(process.env.NVM_BIN&&e.push(n.resolvePath("node",process.env.NVM_BIN)),process.platform==="win32"){e.push("C:\\Program Files\\nodejs\\node.exe");let r=process.env.APPDATA||"";if(r)try{let o=n.resolvePath("nvm",r),a=n.readdirSync(o).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/node.exe`,o))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let r of e)try{let o=n.realpathSync(r);if(o.includes("bun")||!n.pathExists(o))continue;return r}catch{continue}return"node"}function Jt(n){if(!n||typeof n!="string"||n.includes("\0"))return!1;let e=n.split(/[/\\]/).filter(Boolean);for(let t of e)if(t==="."||t===".."||t==="node_modules"||t===".git"||t.startsWith(".")&&t!==".dndev")return!1;return!0}function Zs(n){return n.includes("..")?!1:n.startsWith(".dndev/")||n.startsWith("docs/")||n.startsWith("guides/")}function qt(n){let e=J(),t=e.getRepoRoot(),s=e.resolvePath(n,t),r=e.normalizePath(t),o=e.normalizePath(s);return!o.startsWith(r+"/")&&o!==r?null:s}async function Qs(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!s)return f(e,{error:"path parameter required"},400);if(!Jt(s))return f(e,{error:"Access denied"},403);let r=qt(s);if(!r)return f(e,{error:"Access denied"},403);let o=J();if(!o.pathExists(r))return f(e,{error:"File not found"},404);let a=Ys(r);if(Xs.has(a)){let i=o.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":Yt[a]||"application/octet-stream","Content-Length":i.byteLength}),void e.end(Buffer.from(i))):f(e,{error:"Failed to read file"},500)}if(a===".json")try{let i=await o.read(r);return i===null?f(e,{error:"Failed to read file"},500):f(e,{path:s,content:i})}catch{return f(e,{error:"Invalid JSON"},500)}try{let i=await o.read(r,{format:"text"});if(i===null)return f(e,{error:"Failed to read file"},500);f(e,{path:s,content:i})}catch{f(e,{error:"Failed to read file"},500)}}function er(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("dir"),r=J(),o=r.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(c,p){try{let g=r.readdirSync(c,{withFileTypes:!0});for(let d of g){let h=p?`${p}/${d.name}`:d.name;d.isDirectory()&&i.has(d.name)||(d.isDirectory()?(a.push({path:h,name:d.name,isDirectory:!0}),l(r.resolvePath(d.name,c),h)):d.name.endsWith(".md")&&a.push({path:h,name:d.name,isDirectory:!1}))}}catch{}}let u=[".dndev","docs","guides"];if(s){if(s.includes("..")||s.includes("\0"))return f(e,{error:"Access denied"},403);if(!u.includes(s)&&!u.some(d=>s.startsWith(d+"/")))return f(e,{error:"Directory not allowed"},403);let c=r.resolvePath(s,o),p=r.normalizePath(o);if(!r.normalizePath(c).startsWith(p+"/"))return f(e,{error:"Access denied"},403);r.pathExists(c)&&(a.push({path:s,name:r.getBasename(s),isDirectory:!0}),l(c,s))}else{for(let c of u){let p=r.resolveRepoPath(c);r.pathExists(p)&&(a.push({path:c,name:c,isDirectory:!0}),l(p,c))}try{let c=r.readdirSync(o,{withFileTypes:!0});for(let p of c)!p.isDirectory()&&p.name.endsWith(".md")&&a.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}f(e,{entries:a})}async function tr(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!s)return f(e,{error:"path parameter required"},400);if(!Jt(s))return f(e,{error:"Access denied"},403);if(!Zs(s))return f(e,{error:"Write not allowed to this path"},403);let r=qt(s);if(!r)return f(e,{error:"Access denied"},403);try{let o=await ge(n),{content:a}=JSON.parse(o);if(a===void 0)return f(e,{error:"content field required"},400);let i=typeof a=="string"?a:JSON.stringify(a,null,2);await J().write(r,i,{overwrite:!0}),f(e,{ok:!0})}catch{f(e,{error:"Failed to write file"},500)}}async function sr(n,e){try{let t=await ge(n),{line:s,checked:r}=JSON.parse(t);if(typeof s!="number")return f(e,{error:"line number required"},400);let o=J(),a=o.resolveRepoPath(".dndev/implementation.md");if(!o.pathExists(a))return f(e,{error:"implementation.md not found"},404);let i=await o.read(a,{format:"text"});if(i===null)return f(e,{error:"Failed to read file"},500);let l=i.split(`
3
- `);if(s<0||s>=l.length)return f(e,{error:"Line out of range"},400);let u=l[s];l[s]=r?u.replace("- [ ]","- [x]"):u.replace("- [x]","- [ ]"),await o.write(a,l.join(`
4
- `),{overwrite:!0}),f(e,{ok:!0,line:l[s]})}catch{f(e,{error:"Failed to update progress"},500)}}async function rr(n,e){try{let t=await ge(n),{id:s,data:r}=JSON.parse(t);if(!s||!r)return f(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(s))return f(e,{error:"Invalid screenshot ID"},400);let o=J(),a=o.resolveRepoPath(".dndev/bugs");o.ensureDirSync(a);let i=Buffer.from(r,"base64"),l=o.resolvePath(`${s}.png`,a);await o.write(l,i,{overwrite:!0}),f(e,{ok:!0,path:`.dndev/bugs/${s}.png`})}catch{f(e,{error:"Failed to save screenshot"},500)}}async function or(n,e){try{let t=await ge(n),{action:s,phase:r}=JSON.parse(t);if(!s||typeof r!="number")return f(e,{error:"action and phase required"},400);let o=J(),a=Ht();o.ensureDirSync(a);let i=o.resolvePath("protocol.json",a),l={currentPhase:0,phases:{}};if(o.pathExists(i))try{let u=await o.read(i);u&&(l=u)}catch{}s==="start"?(l.currentPhase=r,l.phases[r]||(l.phases[r]={}),l.phases[r].status="active",l.phases[r].startedAt=new Date().toISOString()):s==="complete"&&(l.phases[r]||(l.phases[r]={}),l.phases[r].status="completed",l.phases[r].completedAt=new Date().toISOString()),await o.write(i,l,{overwrite:!0}),f(e,{ok:!0,protocol:l})}catch{f(e,{error:"Failed to update phase"},500)}}function nr(n,e){try{let t=Z(),s=K("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=K("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();f(e,{commit:s,branch:r})}catch{f(e,{commit:"unknown",branch:"unknown"})}}async function ar(n,e){try{let t=await ge(n),s=JSON.parse(t);if(!s.id||!s.type||!s.result)return f(e,{error:"id, type, and result required"},400);let r=J(),o=Ht();r.ensureDirSync(o);let a=r.resolvePath("health.json",o),i={actions:[]};if(r.pathExists(a))try{let u=await r.read(a);u&&(i=u)}catch{}Array.isArray(i.actions)||(i.actions=[]);let l=i.actions.findIndex(u=>u.id===s.id);l>=0?i.actions[l]={...i.actions[l],...s}:i.actions.unshift(s),await r.write(a,i,{overwrite:!0}),f(e,{ok:!0})}catch{f(e,{error:"Failed to append action"},500)}}function ir(n,e){let t=J(),s=t.resolveRepoPath("apps");try{let o=t.readdirSync(s).filter(a=>{if(a==="dndev")return!1;let i=t.resolvePath(a,s);return t.statSync(i)?.isDirectory()&&t.pathExists(t.resolvePath("package.json",i))}).map(a=>{try{let i=t.resolvePath(`${a}/package.json`,s),l=t.readSync(i);return{name:a,packageName:l?.name||a}}catch{return{name:a,packageName:a}}});f(e,{apps:o})}catch{f(e,{apps:[]})}}function lr(n,e){try{let t=Z(),s=K("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),r=[],o={};for(let a of s.split(`
5
- `))a.startsWith("worktree ")?(o.path&&r.push(o),o={path:a.slice(9)}):a.startsWith("HEAD ")?o.head=a.slice(5):a.startsWith("branch ")?(o.branch=a.slice(7),o.shortBranch=o.branch.replace("refs/heads/","")):a==="detached"&&(o.detached=!0);o.path&&r.push(o),f(e,{worktrees:r})}catch(t){f(e,{error:t.message},500)}}async function cr(n,e){try{let t=await ge(n),{branch:s}=JSON.parse(t);if(!s||typeof s!="string")return f(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(s))return f(e,{error:"Invalid branch name"},400);let r=Z(),o=J(),a=o.resolvePath("..",r),i=o.getBasename(r),l=o.resolvePath(`${i}-${s.replace(/\//g,"-")}`,a);K(`git worktree add "${l}" -b "${s}"`,{cwd:r,encoding:"utf-8",timeout:3e4}),f(e,{ok:!0,path:l,branch:s})}catch(t){f(e,{error:t.message},500)}}async function ur(n,e){try{let t=await ge(n),{path:s}=JSON.parse(t);if(!s||typeof s!="string")return f(e,{error:"path required"},400);let r=Z();et("git",["worktree","remove",s,"--force"],{cwd:r,encoding:"utf-8",timeout:1e4}),f(e,{ok:!0})}catch(t){f(e,{error:t.message},500)}}function pr(n,e){try{let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("branch");if(!s)return f(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(s))return f(e,{error:"Invalid branch name"},400);let r=Z(),o=K(`git diff main...${s} --stat`,{cwd:r,encoding:"utf-8",timeout:1e4}).trim(),a=K(`git diff main...${s}`,{cwd:r,encoding:"utf-8",timeout:3e4});f(e,{stat:o,diff:a})}catch(t){f(e,{error:t.message},500)}}async function gr(n,e){try{let t=await ge(n),{branch:s,title:r,bodyText:o}=JSON.parse(t);if(!s)return f(e,{error:"branch required"},400);let a=Z(),i=["pr","create","--head",s];r&&i.push("--title",r),o&&i.push("--body",o);let l=et("gh",i,{cwd:a,encoding:"utf-8",timeout:3e4}).trim();f(e,{ok:!0,url:l})}catch(t){f(e,{error:t.message},500)}}function dr(n,e){try{let t=Z(),s=K("git remote get-url origin",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=null;s.includes("github.com")?r="github":s.includes("gitlab")&&(r="gitlab"),f(e,{platform:r,remoteUrl:s})}catch{f(e,{platform:null,remoteUrl:null})}}function fr(n,e){try{let t=Z(),s=K("gh pr list --json number,title,state,author,headRefName,url,isDraft,reviewDecision,statusCheckRollup --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});f(e,{prs:JSON.parse(s)})}catch(t){f(e,{prs:[],error:t.message})}}function mr(n,e){try{let t=Z(),s=K("gh issue list --json number,title,state,labels,assignees --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});f(e,{issues:JSON.parse(s)})}catch(t){f(e,{issues:[],error:t.message})}}function hr(n,e){try{let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("number");if(!s||!/^\d+$/.test(s))return f(e,{error:"PR number required"},400);let r=Z(),o=K(`gh pr diff ${s}`,{cwd:r,encoding:"utf-8",timeout:3e4});f(e,{diff:o})}catch(t){f(e,{error:t.message},500)}}function vr(n,e){try{let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("number");if(!s||!/^\d+$/.test(s))return f(e,{error:"PR number required"},400);let r=Z(),o=K(`gh pr checks ${s} --json name,state,status`,{cwd:r,encoding:"utf-8",timeout:15e3});f(e,{checks:JSON.parse(o)})}catch(t){f(e,{checks:[],error:t.message})}}async function yr(n,e){try{let t=await ge(n),{number:s,action:r,comment:o}=JSON.parse(t);if(!s||!r)return f(e,{error:"number and action required"},400);let a=["approve","request-changes","comment"];if(!a.includes(r))return f(e,{error:`Invalid action. Use: ${a.join(", ")}`},400);let i=Z(),l=["pr","review",String(s),`--${r}`];o&&l.push("--body",o),et("gh",l,{cwd:i,encoding:"utf-8",timeout:15e3}),f(e,{ok:!0})}catch(t){f(e,{error:t.message},500)}}function br(n){if(Xe)return;let e=J(),t=e.normalizePath(n.config.root),s=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(s))return;try{let i=K(`fuser ${Vt}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}Xe=!0;let r=e.getRepoRoot(),o=Ks(),a=Js(o,[s],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(Vt),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{Xe=!1}),process.on("exit",()=>{a.kill()})}function wr(n){let e=J(),t=e.getRepoRoot(),s=[".dndev","docs","guides"];for(let r of s){let o=e.resolveRepoPath(r);if(!e.pathExists(o))continue;let a=e.watch(o,{recursive:!0},(i,l)=>{if(!l||l==="dashboard.json")return;let u=`${r}/${l}`,c=`change:${u}`;Qe.has(c)||(Qe.set(c,!0),setTimeout(()=>Qe.delete(c),300),n.hot.send("dndev:file-changed",{path:u,timestamp:Date.now()}))});n.httpServer?.on("close",()=>a.close())}}function xr(n={}){return{name:"dndev",configureServer(e){let t=Z();n.debug,e.middlewares.use((s,r,o)=>{let a=s.url;if(!a?.startsWith(Bt))return o();let l=new URL(a,`http://${s.headers.host}`).pathname.slice(Bt.length),u=s.method?.toUpperCase();if(u==="GET")return l==="/file"?void Qs(s,r):l==="/tree"?void er(s,r):l==="/git/head"?void nr(s,r):l==="/apps"?void ir(s,r):l==="/worktrees"?void lr(s,r):l==="/worktrees/diff"?void pr(s,r):l==="/git/platform"?void dr(s,r):l==="/git/prs"?void fr(s,r):l==="/git/issues"?void mr(s,r):l==="/git/pr/diff"?void hr(s,r):l==="/git/pr/checks"?void vr(s,r):f(r,{error:"Not found"},404);if(u==="POST")return l==="/file"?void tr(s,r):l==="/progress/toggle"?void sr(s,r):l==="/bugs/screenshot"?void rr(s,r):l==="/phase"?void or(s,r):l==="/actions/append"?void ar(s,r):l==="/worktrees/add"?void cr(s,r):l==="/worktrees/remove"?void ur(s,r):l==="/worktrees/pr"?void gr(s,r):l==="/git/pr/review"?void yr(s,r):f(r,{error:"Not found"},404);f(r,{error:"Method not allowed"},405)}),br(e),wr(e)}}}var Bt,qs,Yt,Xs,Vt,Xe,Qe,Zt=Ue(()=>{"use strict";B();Bt="/api/dndev";qs=5*1024*1024;Yt={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},Xs=new Set(Object.keys(Yt));Vt=24681,Xe=!1;Qe=new Map});import ds from"@rollup/plugin-strip";import{visualizer as fs}from"rollup-plugin-visualizer";var We=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-day-picker/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],ss={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/i18next-http-backend/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function rs(n){let e=n.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function st(n){let e=n.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function rt(n,e=We){return e.some(t=>n.includes(t))}function os(n){for(let[e,t]of Object.entries(ss))if(t.some(s=>n.includes(s)))return e}function ns(n){let e=rs(n);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=st(n);if(!t)return;if(rt(t))return"react-core";let s=os(t);if(s)return s}function as(n=[]){let e=n.filter(s=>!We.includes(s)),t=[...We,...e];return function(s){let r=st(s);if(r&&rt(r,t))return"react-core"}}var tt={development:{manualChunks:void 0},production:{manualChunks:ns}};function ot(n,e={}){let t=tt[n]||tt.production,s=e.reactCore||[];return s.length>0?{manualChunks:as(s)}:t}B();import*as Y from"@clack/prompts";var ae={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 gs(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function ce(n,e){return gs()?`${e}${n}${ae.reset}`:n}function F(n,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,a=$.getInstance(),i=null;if(o){let c=a.resolveAppPath(r);a.pathExists(c)||a.mkdir(c),i=a.resolveAppPath(`${r}/${n.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${n} Log Started at ${new Date().toISOString()} ===
6
- `;a.writeSync(i,p)}let l=(c,p,g)=>{if(i){let d=new Date().toISOString(),h=g.length>0?" "+g.map(O=>typeof O=="object"?JSON.stringify(O,null,2):String(O)).join(" "):"",D=`${d} [${c}] ${p}${h}
7
- `;a.appendFile(i,D)}},u=(c,p)=>{if(p.length===0)return c;let g=p.map(d=>typeof d=="object"?JSON.stringify(d,null,2):String(d)).join(" ");return`${c} ${g}`};return{debug:(c,...p)=>{e&&(o?l("DEBUG",c,p):Y.log.message(ce(u(c,p),ae.gray)))},verbose:(c,...p)=>{t&&(o?l("VERBOSE",c,p):Y.log.message(u(c,p)))},info:(c,...p)=>{o?l("INFO",c,p):Y.log.info(ce(u(c,p),ae.brightCyan))},warn:(c,...p)=>{e&&o?l("WARN",c,p):Y.log.warn(ce(u(c,p),ae.brightYellow))},error:(c,...p)=>{e&&o?l("ERROR",c,p):Y.log.error(ce(u(c,p),ae.brightRed))},success:(c,...p)=>{e&&o?l("SUCCESS",c,p):Y.log.success(ce(u(c,p),ae.brightGreen))},when:(c,p="debug")=>(g,...d)=>{if(c){let h=u(g,d);switch(p){case"verbose":t&&(Y.log.message(h),l("VERBOSE",g,d));break;case"info":Y.log.info(ce(h,ae.brightCyan)),l("INFO",g,d);break;case"warn":Y.log.warn(ce(h,ae.brightYellow)),l("WARN",g,d);break;case"error":Y.log.error(ce(h,ae.brightRed)),l("ERROR",g,d);break;case"success":Y.log.success(ce(h,ae.brightGreen)),l("SUCCESS",g,d);break;default:e&&(Y.log.message(ce(h,ae.gray)),l("DEBUG",g,d))}}},getLogFilePath:()=>i}}B();function gt(n={}){let{mode:e="development",chunkingOptions:t={},debug:s,verbose:r=!0,isDev:o,isDebug:a,shouldAnalyze:i,build:l={}}=n,u=F("build",s,r),c=ot(e,t);return u.debug("\u{1F41B} DEBUG MODE ENABLED:"),u.debug(" - Minification: DISABLED"),u.debug(" - Sourcemaps: ENABLED"),u.debug(" - Console logs: PRESERVED"),u.debug(" - Debugger statements: PRESERVED"),i&&(u.info("\u{1F4CA} Bundle analysis enabled"),u.info(` Visual treemap will open after build (stats.html)
8
- `)),{outDir:"dist",sourcemap:o||a,cacheDir:"node_modules/.vite",target:"baseline-widely-available",minify:a?!1:"esbuild",reportCompressedSize:!1,chunkSizeWarningLimit:2048,assetsInlineLimit:0,esbuild:{format:"esm",drop:a?[]:["console","debugger"],legalComments:"none"},cssMinify:a?!1:"esbuild",cssCodeSplit:!0,rollupOptions:{external:ms(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...c.manualChunks&&{manualChunks:c.manualChunks},compact:!0},onwarn(g,d){g.code!=="MODULE_LEVEL_DIRECTIVE"&&d(g)},plugins:[...a?[]:[ds({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let g=$.getInstance(),d=g.getAppRoot(),h="dist",D=g.resolveAppPath(`${h}/stats.html`),O=()=>{try{let R=g.resolveAppPath(h);g.pathExists(R)||g.mkdir(R)}catch{}},y=fs({filename:D,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:o||a,projectRoot:d});if(y.buildStart){let R=y.buildStart.bind(y);y.buildStart=function(...b){O();let S=R.apply(this,b);return S&&typeof S.then=="function"?S.catch(v=>{}):S}}else y.buildStart=function(){O()};let k=["generateBundle","writeBundle","closeBundle"];for(let R of k)if(y[R]){let b=y[R];y[R]=function(...S){try{O();let v=b.apply(this,S);return v&&typeof v.then=="function"?v.catch(A=>{let T=A?.message||A?.toString()||String(A)||"Unknown error";u.warn(`Bundle visualizer warning in ${R}: ${T}`),R==="closeBundle"&&u.warn(`You can manually open ${D} to view the bundle analysis`)}):v}catch(v){let A=v?.message||v?.toString()||String(v)||"Unknown error";buildLogger.warn(`Bundle visualizer warning in ${R}: ${A}`),R==="closeBundle"&&buildLogger.warn(` You can manually open ${D} to view the bundle analysis`)}}}return y})()]:[]]}}}function ms(n){return n?["firebase-admin","gcp-metadata","google-logging-utils","@google-cloud/firestore",/\.node$/,"esbuild",/@esbuild\/.*/]:["gcp-metadata","google-logging-utils","payload","file-type","firebase-admin","firebase-admin/app","firebase-admin/auth","firebase-admin/firestore","firebase-admin/functions","firebase-admin/credential","@google-cloud/firestore","google-auth-library","google-gax","googleapis-common"]}function hs(){let n=!1,e=$.getInstance();if((e.pathExists("/.dockerenv")||e.pathExists("/run/.containerenv"))&&(n=!0),!n&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(n=!0),!n&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(n=!0),!n&&process.platform==="linux"&&e.pathExists("/proc/self/cgroup"))try{let r=e.readSync("/proc/self/cgroup");r&&(r.includes("docker")||r.includes("containerd"))&&(n=!0)}catch{}let t=!1;if((process.env.WSL_DISTRO_NAME||process.env.WSLENV)&&(t=!0),!t&&process.platform==="linux"&&e.pathExists("/proc/version"))try{let r=(e.readSync("/proc/version")||"").toLowerCase();t=r.includes("microsoft")||r.includes("wsl")}catch{}if(!t&&process.platform==="linux"&&e.pathExists("/proc/sys/kernel/osrelease"))try{let r=(e.readSync("/proc/sys/kernel/osrelease")||"").toLowerCase()||"";(r.includes("microsoft")||r.includes("wsl"))&&(t=!0)}catch{}if(!t&&process.platform==="win32"){let r=process.cwd();r&&(r.includes("\\wsl$")||r.includes("\\wsl.localhost"))&&(t=!0)}let s=typeof process.versions?.bun=="string";return{isDocker:n,isWSL2:t,isBun:s}}function vs(n,e){if(n!==void 0)return n;let{isDocker:t,isWSL2:s,isBun:r}=hs();if(t||s||r){let o=t?"Docker":s?"WSL2":"Bun";return e.info(`Detected ${o} environment - enabling polling mode for file watching`),!0}}function dt(n,e={},t){let s=$.getInstance(),r=s.getRepoRoot(),{watch:o,hmr:a,host:i,...l}=e||{},u=a||{},c=i===!0?"localhost":i||"localhost",p={...u.port&&{port:u.port},...u.clientPort&&{clientPort:u.clientPort},host:u.host??c,...u.protocol&&{protocol:u.protocol},overlay:u.overlay??!0,timeout:u.timeout??5e3},g=i!==void 0?i:!0,d=l.https===!0;return{port:n,host:g,open:e.open!==void 0?e.open:!0,https:d,fs:{allow:[r,s.resolveRepoPath("packages"),s.resolveRepoPath("node_modules")],strict:!1},watch:(()=>{let h=vs(e?.watch?.usePolling,t);return{usePolling:h,interval:e?.watch?.interval??2e3,...h&&{awaitWriteFinish:{stabilityThreshold:300,pollInterval:100}},...e?.watch||{}}})(),hmr:{...p,...u},headers:{"Cross-Origin-Opener-Policy":"same-origin-allow-popups","Cross-Origin-Embedder-Policy":"unsafe-none"},middlewareMode:!1,...l}}function ft(n={}){let e=n.https===!0;return{...n,https:e}}L();var re={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function me(n,e,t,s={}){let{protectedKeys:r=[],onConflict:o}=s;if(e==null)return n;switch(t){case re.CONCATENATE_DEDUPE:{if(!Array.isArray(n)||!Array.isArray(e))return e;let a=[...n,...e];return[...new Set(a)]}case re.SHALLOW_MERGE:return typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e)?e:{...n,...e};case re.DEEP_MERGE:{if(typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e))return e;let a={...n};for(let i in e){if(r.includes(i)){o&&o(i,n[i],e[i]);continue}typeof a[i]=="object"&&typeof e[i]=="object"&&a[i]!==null&&e[i]!==null&&!Array.isArray(a[i])&&!Array.isArray(e[i])?a[i]=me(a[i],e[i],re.DEEP_MERGE,{protectedKeys:r,onConflict:o}):a[i]=e[i]}return a}case re.REPLACE:default:return e}}function mt(n,e,t=[],s){let r=[...n,...e||[]],o=[...new Set(r)];return[...new Set([...o,...t])]}var xe={base:"/",mode:process.env.NODE_ENV==="production"?"production":"development",debug:!1,verbose:process.env.CI!=="true",server:{port:3e3,strictPort:!0,host:!0,open:!0,cors:!0,https:!0,hmr:{overlay:!0,timeout:5e3,usePolling:void 0,interval:2e3},watch:{usePolling:void 0,interval:2e3}},build:{sourcemap:!0,target:"es2020",minify:"esbuild",cssMinify:"esbuild",analyze:!0},preview:{port:4173,strictPort:!0,host:!0,open:!1,cors:!0,https:!0},routes:{hmr:!0},themes:{},i18n:{},assets:{},features:{},pwa:{enabled:!1},seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0},chunking:{reactCore:[]},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},pluginFactory:{verbose:!0,disableHmr:!1,hmrSmartDetection:!0,hmrDebounceMs:500,hmrCacheTimeout:3e4},resolve:{alias:{"@":"/src"},preserveSymlinks:!1},define:{__DEV__:JSON.stringify(process.env.NODE_ENV==="development"),__PROD__:JSON.stringify(process.env.NODE_ENV==="production")},optimizeDeps:{include:[...ye.mandatoryIncludes],exclude:[...ye.buildTools,...Object.values(M)],esbuildOptions:{format:"esm",target:"es2020",platform:"browser",define:{"process.env.NODE_ENV":JSON.stringify(process.env.NODE_ENV||"development")},external:["next","next/*"]}},plugins:[],css:{},envDir:void 0};function ht(n={},e={}){let{onConflict:t}=e,s={...xe},r=[],o=(a,i,l,u)=>{r.push({key:a,frameworkValue:i,userValue:l,reason:u}),t&&t(a,i,l,u)};return Object.keys(n).forEach(a=>{let i=n[a],l=s[a];if(a==="optimizeDeps"&&typeof i=="object"&&i!==null){let u=l?.include||[],c=l?.exclude||[],p=i.include||[],g=i.exclude||[],d=u.filter(k=>!k.startsWith("@donotdev/")),h=g.filter(k=>d.includes(k));if(h.length>0)for(let k of h)o("optimizeDeps.exclude",k,"excluded",`Framework requires ${k} to be included. It will be included despite your exclusion.`);let D=mt(u,p,d),O=me(c,g,re.CONCATENATE_DEDUPE),y=me(l?.esbuildOptions||{},i.esbuildOptions||{},re.DEEP_MERGE,{protectedKeys:["external"],onConflict:k=>o(`optimizeDeps.esbuildOptions.${k}`,l?.esbuildOptions?.[k],i.esbuildOptions?.[k],`Framework requires ${k} to remain as configured.`)});s[a]={...l,include:D,exclude:O,esbuildOptions:y,...Object.fromEntries(Object.entries(i).filter(([k])=>!["include","exclude","esbuildOptions"].includes(k)))};return}if(a==="css"&&typeof i=="object"&&i!==null){s[a]=me(l||{},i,re.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>o("css.postcss","framework PostCSS config",i.postcss,"Framework PostCSS config is required and cannot be overridden. Your postcss config is ignored.")});return}if(a==="define"&&typeof i=="object"&&i!==null){s[a]=me(l||{},i,re.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:u=>o(`define.${u}`,l?.[u],i[u],`Framework requires ${u} to remain as configured.`)});return}if(Array.isArray(i)){Array.isArray(l)?s[a]=me(l,i,re.CONCATENATE_DEDUPE):s[a]=i;return}if(typeof i=="object"&&i!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){s[a]=me(l,i,re.SHALLOW_MERGE);return}s[a]=i}),s}function vt(n){let{server:e={},preview:t={},mode:s,build:r={},resolve:o={},routes:a={},themes:i={},i18n:l={},assets:u={},features:c={},seo:p={},pwa:g={},serverShim:d={},chunking:h={},discovery:D={},pluginFactory:O={},debug:y,verbose:k,base:R,define:b={},optimizeDeps:S={},plugins:v=[],css:A={},envDir:T,...X}=n,P=s!=="production",x=y||P,W=s==="production"&&(r.analyze??xe.build.analyze);return{mode:s,debug:y,verbose:k,isDev:P,isDebug:x,shouldAnalyze:W,serverOptions:e,previewOptions:t,buildOverrides:r,resolveOptions:o,routeOptions:a,themeOptions:i,i18nOptions:l,assetOptions:u,featureOptions:c,seoOptions:p,pwaOptions:g,serverShimOptions:d,chunkingOptions:h,discoveryOptions:D,pluginFactoryOptions:O,base:R,defineOptions:b,optimizeDepsOptions:S,pluginsOptions:v,cssOptions:A,envDir:T,restOptions:X}}B();import ys from"autoprefixer";import bs from"postcss-import";import ws from"postcss-nesting";function yt({postcssImport:n,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?n({resolve:s}):n,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function bt(n={}){if(n.postcss)return n.postcss;let e=$.getInstance();return yt({postcssImport:bs,postcssNesting:ws,autoprefixer:ys,resolve:(s,r)=>{let o=e.resolvePackage(s,r);if(o)return o;if(s.startsWith("@donotdev/")){let a=s.split("/")[0]+"/"+s.split("/")[1],i=s.split("/").slice(2).join("/"),l=e.resolveFrameworkPackage(a,r);if(l&&i){let u=e.resolvePath(i,l);if(e.pathExists(u))return u}}return e.resolvePath(s,r)}})}import Ws from"@vitejs/plugin-basic-ssl";import Gs from"@vitejs/plugin-react";import Bs from"vite-tsconfig-paths";var H=class{static generateVirtualModule(e,t,s=!1,r=void 0,o=void 0){return t.isEmpty(e)?t.generateEmpty(e,s,r,o):t.generateModule(e,s,o)}static generateInspection(e,t,s,r){return t.generateInspection.length>=3?t.generateInspection(e,s,r):t.generateInspection(e,s)}static wrapVirtualModule(e,t){return`// Virtual module: ${e}
1
+ var bs=Object.defineProperty;var He=(n,e)=>()=>(n&&(e=n(n=0)),e);var ws=(n,e)=>{for(var t in e)bs(n,t,{get:e[t],enumerable:!0})};function vt(n,e=null){let t=te[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function ze(n){return dt[n]||dt.base}var qe,j,H,ie,Ye,Ne,je,te,xe,mt,Ke,Ze,Oe,ht,Xe,dt,U=He(()=>{"use strict";qe={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},j={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env"},H={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},ie={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",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js"},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"}},Ye={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"},je={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"},te={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:[`${je.SOURCE_EAGER}/*_*.json`],lazy:[`${je.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/**"]},xe={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"],optionalFeatures:[],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"]},mt=["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"],Ke=["@donotdev/core/functions","@donotdev/core/server"],Ze={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)/}},Oe={inter:[300,400,600,700],"playfair-display":[400,500,600,700],roboto:[400,700],"space-grotesk":[300,400,500,600,700],"press-start-2p":[400]},ht={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin"],cs:["latin"],sk:["latin"],hr:["latin"],sl:["latin"],hu:["latin"],ro:["latin"],et:["latin"],lv:["latin"],lt:["latin"],mt:["latin"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},Xe=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],dt={base:{absolute:!0,onlyFiles:!0,ignore:te.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...te.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...te.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:te.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:te.globalIgnore}}});import*as A from"node:fs";import"node:fs";import{createRequire as _s}from"node:module";import{resolve as Te,join as me,dirname as he,relative as yt,normalize as ks,sep as bt,extname as Ds}from"node:path";import{fileURLToPath as As}from"node:url";import Ns from"fast-glob";function wt(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Re,W,xt,E,L=He(()=>{"use strict";U();Re={getGlobOptionsFor:ze||void 0,SCAN_PATTERNS:te||void 0,getPatternsFor:vt||void 0,I18N_PATHS:je||void 0},W={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};xt={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"},E=class n{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._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,n._instance=this}normalizePath(e){if(!e)return"";try{return ks(e).split(bt).join("/")}catch{return String(e).split(bt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=yt(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(he(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=_s(me(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/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}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=Te(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Te(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=Te(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=A.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:Ds(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 A.promises.readFile(e);let a=await A.promises.readFile(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&W.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 A.readFileSync(e);let a=A.readFileSync(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&W.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),c=this.normalizePath(he(l)),u=this.pathExists(l);if(u&&!o)return i&&W.info(`Skipping existing file: ${l}`),!1;if(a)return W.info(`[DRY RUN] Would write file: ${l}`),!0;try{await A.promises.mkdir(c,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await wt(async()=>(Buffer.isBuffer(g)?await A.promises.writeFile(l,g):await A.promises.writeFile(l,g,"utf8"),i&&W.info(`${u?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),c=this.normalizePath(he(l)),u=this.pathExists(l);if(u&&!o)return i&&W.info(`Skipping existing file: ${l}`),!1;if(a)return W.info(`[DRY RUN] Would write file: ${l}`),!0;try{A.mkdirSync(c,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return Buffer.isBuffer(g)?A.writeFileSync(l,g):A.writeFileSync(l,g,"utf8"),i&&W.info(`${u?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&W.info(`Skipping existing file: ${i}`),!1;if(o)return W.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(he(i));try{await A.promises.mkdir(c,{recursive:!0})}catch(u){if(u?.code!=="EEXIST")throw u}try{return await wt(async()=>(await A.promises.copyFile(e,i),a&&W.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&W.info(`Skipping existing file: ${i}`),!1;if(o)return W.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(he(i));try{A.mkdirSync(c,{recursive:!0})}catch(u){if(u?.code!=="EEXIST")throw u}try{return A.copyFileSync(e,i),a&&W.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return A.existsSync(e)}catch(s){return t||W.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 A.existsSync(t)||A.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return A.readdirSync(e,t)}catch(s){return this.options.debug&&W.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return A.statSync(e)}catch(t){return this.options.debug&&W.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return A.realpathSync(e)}watch(e,t,s){return A.watch(e,t,s)}lstatSync(e){try{return A.lstatSync(e)}catch(t){return this.options.debug&&W.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await A.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{A.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await A.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){A.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return A.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=me(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Te(e)),s=this.getAppRoot(),r=yt(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(me(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=r.startsWith(a)?r.slice(a.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:Re.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Re.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(me(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await Ns(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 u of s)if(typeof u!="string"||u.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=Re.getGlobOptionsFor?Re.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),i=e.framework.map(u=>{let p=this.normalizePath(u);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(u=>{let p=this.normalizePath(u);return p.startsWith(a)?p.slice(a.length+1):p}),c={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let u=i.length>0?await this._globWithNormalization(i,c):[],p=await this._globWithNormalization(l,c);return{frameworkFiles:u,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!Re.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=Re.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=r,c={eager:l.eager.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),lazy:l.lazy.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),framework:{eager:o?(l.framework?.eager||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean))},all:[]};return c.all=[...c.eager,...c.lazy,...c.framework.eager,...c.framework.lazy],c}let a=r,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyFlagModulePath(){let e=he(As(import.meta.url));return this.normalizePath(Te(e,"emptyFlag.js"))}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(me(t,xt.TOOLING)),a=this.normalizePath(me(t,xt.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=me(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(me(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(he(t))===t)return t;let c=this.normalizePath(he(t));if(c===t)break;t=c,s++}return this.normalizePath(e)}}});var ds={};ws(ds,{createDndevPlugin:()=>Jr});import{execSync as ue,execFileSync as ke,spawn as br}from"node:child_process";function J(){return E.getInstance()}function Z(){return J().getRepoRoot()}function us(){return J().resolveRepoPath(".dndev")}function h(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function fe(n,e=wr){return new Promise((t,s)=>{let r="",o=0;n.on("data",a=>{if(o+=a.length,o>e){n.destroy(),s(new Error("Request body too large"));return}r+=a.toString()}),n.on("end",()=>t(r)),n.on("error",s)})}function xr(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function Sr(){let n=J(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",o=ue(r,{encoding:"utf8"}).trim().split(`
2
+ `)[0];e.push(o)}catch{}let s=[process.env.NVM_DIR,n.resolvePath(".nvm",t)].filter(Boolean);for(let r of s)try{let o=n.resolvePath("versions/node",r),a=n.readdirSync(o).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/bin/node`,o))}catch{}if(process.env.NVM_BIN&&e.push(n.resolvePath("node",process.env.NVM_BIN)),process.platform==="win32"){e.push("C:\\Program Files\\nodejs\\node.exe");let r=process.env.APPDATA||"";if(r)try{let o=n.resolvePath("nvm",r),a=n.readdirSync(o).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/node.exe`,o))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let r of e)try{let o=n.realpathSync(r);if(o.includes("bun")||!n.pathExists(o))continue;return r}catch{continue}return"node"}function ps(n){if(!n||typeof n!="string"||n.includes("\0"))return!1;let e=n.split(/[/\\]/).filter(Boolean);for(let t of e)if(t==="."||t===".."||t==="node_modules"||t===".git"||t.startsWith(".")&&t!==".dndev")return!1;return!0}function Pr(n){return n.includes("..")?!1:n.startsWith(".dndev/")||n.startsWith("docs/")||n.startsWith("guides/")}function gs(n){let e=J(),t=e.getRepoRoot(),s=e.resolvePath(n,t),r=e.normalizePath(t),o=e.normalizePath(s);return!o.startsWith(r+"/")&&o!==r?null:s}async function $r(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!s)return h(e,{error:"path parameter required"},400);if(!ps(s))return h(e,{error:"Access denied"},403);let r=gs(s);if(!r)return h(e,{error:"Access denied"},403);let o=J();if(!o.pathExists(r))return h(e,{error:"File not found"},404);let a=xr(r);if(Rr.has(a)){let i=o.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":fs[a]||"application/octet-stream","Content-Length":i.byteLength}),void e.end(Buffer.from(i))):h(e,{error:"Failed to read file"},500)}if(a===".json")try{let i=await o.read(r);return i===null?h(e,{error:"Failed to read file"},500):h(e,{path:s,content:i})}catch{return h(e,{error:"Invalid JSON"},500)}try{let i=await o.read(r,{format:"text"});if(i===null)return h(e,{error:"Failed to read file"},500);h(e,{path:s,content:i})}catch{h(e,{error:"Failed to read file"},500)}}function Er(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("dir"),r=J(),o=r.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(u,p){try{let g=r.readdirSync(u,{withFileTypes:!0});for(let f of g){let m=p?`${p}/${f.name}`:f.name;f.isDirectory()&&i.has(f.name)||(f.isDirectory()?(a.push({path:m,name:f.name,isDirectory:!0}),l(r.resolvePath(f.name,u),m)):f.name.endsWith(".md")&&a.push({path:m,name:f.name,isDirectory:!1}))}}catch{}}let c=[".dndev","docs","guides"];if(s){if(s.includes("..")||s.includes("\0"))return h(e,{error:"Access denied"},403);if(!c.includes(s)&&!c.some(f=>s.startsWith(f+"/")))return h(e,{error:"Directory not allowed"},403);let u=r.resolvePath(s,o),p=r.normalizePath(o);if(!r.normalizePath(u).startsWith(p+"/"))return h(e,{error:"Access denied"},403);r.pathExists(u)&&(a.push({path:s,name:r.getBasename(s),isDirectory:!0}),l(u,s))}else{for(let u of c){let p=r.resolveRepoPath(u);r.pathExists(p)&&(a.push({path:u,name:u,isDirectory:!0}),l(p,u))}try{let u=r.readdirSync(o,{withFileTypes:!0});for(let p of u)!p.isDirectory()&&p.name.endsWith(".md")&&a.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}h(e,{entries:a})}async function _r(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!s)return h(e,{error:"path parameter required"},400);if(!ps(s))return h(e,{error:"Access denied"},403);if(!Pr(s))return h(e,{error:"Write not allowed to this path"},403);let r=gs(s);if(!r)return h(e,{error:"Access denied"},403);try{let o=await fe(n),{content:a}=JSON.parse(o);if(a===void 0)return h(e,{error:"content field required"},400);let i=typeof a=="string"?a:JSON.stringify(a,null,2);await J().write(r,i,{overwrite:!0}),h(e,{ok:!0})}catch{h(e,{error:"Failed to write file"},500)}}async function kr(n,e){try{let t=await fe(n),{line:s,checked:r}=JSON.parse(t);if(typeof s!="number")return h(e,{error:"line number required"},400);let o=J(),a=o.resolveRepoPath(".dndev/implementation.md");if(!o.pathExists(a))return h(e,{error:"implementation.md not found"},404);let i=await o.read(a,{format:"text"});if(i===null)return h(e,{error:"Failed to read file"},500);let l=i.split(`
3
+ `);if(s<0||s>=l.length)return h(e,{error:"Line out of range"},400);let c=l[s];l[s]=r?c.replace("- [ ]","- [x]"):c.replace("- [x]","- [ ]"),await o.write(a,l.join(`
4
+ `),{overwrite:!0}),h(e,{ok:!0,line:l[s]})}catch{h(e,{error:"Failed to update progress"},500)}}async function Dr(n,e){try{let t=await fe(n),{id:s,data:r}=JSON.parse(t);if(!s||!r)return h(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(s))return h(e,{error:"Invalid screenshot ID"},400);let o=J(),a=o.resolveRepoPath(".dndev/bugs");o.ensureDirSync(a);let i=Buffer.from(r,"base64"),l=o.resolvePath(`${s}.png`,a);await o.write(l,i,{overwrite:!0}),h(e,{ok:!0,path:`.dndev/bugs/${s}.png`})}catch{h(e,{error:"Failed to save screenshot"},500)}}async function Ar(n,e){try{let t=await fe(n),{action:s,phase:r}=JSON.parse(t);if(!s||typeof r!="number")return h(e,{error:"action and phase required"},400);let o=J(),a=us();o.ensureDirSync(a);let i=o.resolvePath("protocol.json",a),l={currentPhase:0,phases:{}};if(o.pathExists(i))try{let c=await o.read(i);c&&(l=c)}catch{}s==="start"?(l.currentPhase=r,l.phases[r]||(l.phases[r]={}),l.phases[r].status="active",l.phases[r].startedAt=new Date().toISOString()):s==="complete"&&(l.phases[r]||(l.phases[r]={}),l.phases[r].status="completed",l.phases[r].completedAt=new Date().toISOString()),await o.write(i,l,{overwrite:!0}),h(e,{ok:!0,protocol:l})}catch{h(e,{error:"Failed to update phase"},500)}}function Nr(n,e){try{let t=Z(),s=ue("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=ue("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();h(e,{commit:s,branch:r})}catch{h(e,{commit:"unknown",branch:"unknown"})}}async function Or(n,e){try{let t=await fe(n),s=JSON.parse(t);if(!s.id||!s.type||!s.result)return h(e,{error:"id, type, and result required"},400);let r=J(),o=us();r.ensureDirSync(o);let a=r.resolvePath("health.json",o),i={actions:[]};if(r.pathExists(a))try{let c=await r.read(a);c&&(i=c)}catch{}Array.isArray(i.actions)||(i.actions=[]);let l=i.actions.findIndex(c=>c.id===s.id);l>=0?i.actions[l]={...i.actions[l],...s}:i.actions.unshift(s),await r.write(a,i,{overwrite:!0}),h(e,{ok:!0})}catch{h(e,{error:"Failed to append action"},500)}}function Tr(n,e){let t=J(),s=t.resolveRepoPath("apps");try{let o=t.readdirSync(s).filter(a=>{if(a==="dndev")return!1;let i=t.resolvePath(a,s);return t.statSync(i)?.isDirectory()&&t.pathExists(t.resolvePath("package.json",i))}).map(a=>{try{let i=t.resolvePath(`${a}/package.json`,s),l=t.readSync(i);return{name:a,packageName:l?.name||a}}catch{return{name:a,packageName:a}}});h(e,{apps:o})}catch{h(e,{apps:[]})}}function Fr(n,e){try{let t=Z(),s=ue("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),r=[],o={};for(let a of s.split(`
5
+ `))a.startsWith("worktree ")?(o.path&&r.push(o),o={path:a.slice(9)}):a.startsWith("HEAD ")?o.head=a.slice(5):a.startsWith("branch ")?(o.branch=a.slice(7),o.shortBranch=o.branch.replace("refs/heads/","")):a==="detached"&&(o.detached=!0);o.path&&r.push(o),h(e,{worktrees:r})}catch(t){h(e,{error:t.message},500)}}async function Cr(n,e){try{let t=await fe(n),{branch:s}=JSON.parse(t);if(!s||typeof s!="string")return h(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(s))return h(e,{error:"Invalid branch name"},400);let r=Z(),o=J(),a=o.resolvePath("..",r),i=o.getBasename(r),l=o.resolvePath(`${i}-${s.replace(/\//g,"-")}`,a);ke("git",["worktree","add",l,"-b",s],{cwd:r,encoding:"utf-8",timeout:3e4}),h(e,{ok:!0,path:l,branch:s})}catch(t){h(e,{error:t.message},500)}}async function Ir(n,e){try{let t=await fe(n),{path:s}=JSON.parse(t);if(!s||typeof s!="string")return h(e,{error:"path required"},400);let r=Z();ke("git",["worktree","remove",s,"--force"],{cwd:r,encoding:"utf-8",timeout:1e4}),h(e,{ok:!0})}catch(t){h(e,{error:t.message},500)}}function Mr(n,e){try{let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("branch");if(!s)return h(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(s))return h(e,{error:"Invalid branch name"},400);let r=Z(),o=ke("git",["diff",`main...${s}`,"--stat"],{cwd:r,encoding:"utf-8",timeout:1e4}).trim(),a=ke("git",["diff",`main...${s}`],{cwd:r,encoding:"utf-8",timeout:3e4});h(e,{stat:o,diff:a})}catch(t){h(e,{error:t.message},500)}}async function jr(n,e){try{let t=await fe(n),{branch:s,title:r,bodyText:o}=JSON.parse(t);if(!s)return h(e,{error:"branch required"},400);let a=Z(),i=["pr","create","--head",s];r&&i.push("--title",r),o&&i.push("--body",o);let l=ke("gh",i,{cwd:a,encoding:"utf-8",timeout:3e4}).trim();h(e,{ok:!0,url:l})}catch(t){h(e,{error:t.message},500)}}function zr(n,e){try{let t=Z(),s=ue("git remote get-url origin",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=null;s.includes("github.com")?r="github":s.includes("gitlab")&&(r="gitlab"),h(e,{platform:r,remoteUrl:s})}catch{h(e,{platform:null,remoteUrl:null})}}function Lr(n,e){try{let t=Z(),s=ue("gh pr list --json number,title,state,author,headRefName,url,isDraft,reviewDecision,statusCheckRollup --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});h(e,{prs:JSON.parse(s)})}catch(t){h(e,{prs:[],error:t.message})}}function Ur(n,e){try{let t=Z(),s=ue("gh issue list --json number,title,state,labels,assignees --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});h(e,{issues:JSON.parse(s)})}catch(t){h(e,{issues:[],error:t.message})}}function Wr(n,e){try{let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("number");if(!s||!/^\d+$/.test(s))return h(e,{error:"PR number required"},400);let r=Z(),o=ue(`gh pr diff ${s}`,{cwd:r,encoding:"utf-8",timeout:3e4});h(e,{diff:o})}catch(t){h(e,{error:t.message},500)}}function Gr(n,e){try{let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("number");if(!s||!/^\d+$/.test(s))return h(e,{error:"PR number required"},400);let r=Z(),o=ue(`gh pr checks ${s} --json name,state,status`,{cwd:r,encoding:"utf-8",timeout:15e3});h(e,{checks:JSON.parse(o)})}catch(t){h(e,{checks:[],error:t.message})}}async function Br(n,e){try{let t=await fe(n),{number:s,action:r,comment:o}=JSON.parse(t);if(!s||!r)return h(e,{error:"number and action required"},400);let a=["approve","request-changes","comment"];if(!a.includes(r))return h(e,{error:`Invalid action. Use: ${a.join(", ")}`},400);let i=Z(),l=["pr","review",String(s),`--${r}`];o&&l.push("--body",o),ke("gh",l,{cwd:i,encoding:"utf-8",timeout:15e3}),h(e,{ok:!0})}catch(t){h(e,{error:t.message},500)}}function Vr(n){if(it)return;let e=J(),t=e.normalizePath(n.config.root),s=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(s))return;try{let i=ue(`fuser ${cs}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}it=!0;let r=e.getRepoRoot(),o=Sr(),a=br(o,[s],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(cs),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{it=!1}),process.on("exit",()=>{a.kill()})}function Hr(n){let e=J(),t=e.getRepoRoot(),s=[".dndev","docs","guides"];for(let r of s){let o=e.resolveRepoPath(r);if(!e.pathExists(o))continue;let a=e.watch(o,{recursive:!0},(i,l)=>{if(!l||l==="dashboard.json")return;let c=`${r}/${l}`,u=`change:${c}`;lt.has(u)||(lt.set(u,!0),setTimeout(()=>lt.delete(u),300),n.hot.send("dndev:file-changed",{path:c,timestamp:Date.now()}))});n.httpServer?.on("close",()=>a.close())}}function Jr(n={}){return{name:"dndev",configureServer(e){let t=Z();n.debug,e.middlewares.use((s,r,o)=>{let a=s.url;if(!a?.startsWith(ls))return o();let l=new URL(a,`http://${s.headers.host}`).pathname.slice(ls.length),c=s.method?.toUpperCase();if(c==="GET")return l==="/file"?void $r(s,r):l==="/tree"?void Er(s,r):l==="/git/head"?void Nr(s,r):l==="/apps"?void Tr(s,r):l==="/worktrees"?void Fr(s,r):l==="/worktrees/diff"?void Mr(s,r):l==="/git/platform"?void zr(s,r):l==="/git/prs"?void Lr(s,r):l==="/git/issues"?void Ur(s,r):l==="/git/pr/diff"?void Wr(s,r):l==="/git/pr/checks"?void Gr(s,r):h(r,{error:"Not found"},404);if(c==="POST")return l==="/file"?void _r(s,r):l==="/progress/toggle"?void kr(s,r):l==="/bugs/screenshot"?void Dr(s,r):l==="/phase"?void Ar(s,r):l==="/actions/append"?void Or(s,r):l==="/worktrees/add"?void Cr(s,r):l==="/worktrees/remove"?void Ir(s,r):l==="/worktrees/pr"?void jr(s,r):l==="/git/pr/review"?void Br(s,r):h(r,{error:"Not found"},404);h(r,{error:"Method not allowed"},405)}),Vr(e),Hr(e)}}}var ls,wr,fs,Rr,cs,it,lt,ms=He(()=>{"use strict";L();ls="/api/dndev";wr=5*1024*1024;fs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},Rr=new Set(Object.keys(fs));cs=24681,it=!1;lt=new Map});import Ts from"@rollup/plugin-strip";import{visualizer as Fs}from"rollup-plugin-visualizer";var Je=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-day-picker/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],xs={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/i18next-http-backend/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function Ss(n){let e=n.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function pt(n){let e=n.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function gt(n,e=Je){return e.some(t=>n.includes(t))}function Ps(n){for(let[e,t]of Object.entries(xs))if(t.some(s=>n.includes(s)))return e}function Rs(n){let e=Ss(n);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=pt(n);if(!t)return;if(gt(t))return"react-core";let s=Ps(t);if(s)return s}function $s(n=[]){let e=n.filter(s=>!Je.includes(s)),t=[...Je,...e];return function(s){let r=pt(s);if(r&&gt(r,t))return"react-core"}}var ut={development:{manualChunks:void 0},production:{manualChunks:Rs}};function ft(n,e={}){let t=ut[n]||ut.production,s=e.reactCore||[];return s.length>0?{manualChunks:$s(s)}:t}L();import*as K from"@clack/prompts";var ne={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 Os(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function le(n,e){return Os()?`${e}${n}${ne.reset}`:n}function C(n,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,a=E.getInstance(),i=null;if(o){let u=a.resolveAppPath(r);a.pathExists(u)||a.mkdir(u),i=a.resolveAppPath(`${r}/${n.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${n} Log Started at ${new Date().toISOString()} ===
6
+ `;a.writeSync(i,p)}let l=(u,p,g)=>{if(i){let f=new Date().toISOString(),m=g.length>0?" "+g.map(P=>typeof P=="object"?JSON.stringify(P,null,2):String(P)).join(" "):"",d=`${f} [${u}] ${p}${m}
7
+ `;a.appendFile(i,d)}},c=(u,p)=>{if(p.length===0)return u;let g=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${u} ${g}`};return{debug:(u,...p)=>{e&&(o?l("DEBUG",u,p):K.log.message(le(c(u,p),ne.gray)))},verbose:(u,...p)=>{t&&(o?l("VERBOSE",u,p):K.log.message(c(u,p)))},info:(u,...p)=>{o?l("INFO",u,p):K.log.info(le(c(u,p),ne.brightCyan))},warn:(u,...p)=>{e&&o?l("WARN",u,p):K.log.warn(le(c(u,p),ne.brightYellow))},error:(u,...p)=>{e&&o?l("ERROR",u,p):K.log.error(le(c(u,p),ne.brightRed))},success:(u,...p)=>{e&&o?l("SUCCESS",u,p):K.log.success(le(c(u,p),ne.brightGreen))},when:(u,p="debug")=>(g,...f)=>{if(u){let m=c(g,f);switch(p){case"verbose":t&&(K.log.message(m),l("VERBOSE",g,f));break;case"info":K.log.info(le(m,ne.brightCyan)),l("INFO",g,f);break;case"warn":K.log.warn(le(m,ne.brightYellow)),l("WARN",g,f);break;case"error":K.log.error(le(m,ne.brightRed)),l("ERROR",g,f);break;case"success":K.log.success(le(m,ne.brightGreen)),l("SUCCESS",g,f);break;default:e&&(K.log.message(le(m,ne.gray)),l("DEBUG",g,f))}}},getLogFilePath:()=>i}}L();function St(n={}){let{mode:e="development",chunkingOptions:t={},debug:s,verbose:r=!0,isDev:o,isDebug:a,shouldAnalyze:i,build:l={}}=n,c=C("build",s,r),u=ft(e,t);return c.debug("\u{1F41B} DEBUG MODE ENABLED:"),c.debug(" - Minification: DISABLED"),c.debug(" - Sourcemaps: ENABLED"),c.debug(" - Console logs: PRESERVED"),c.debug(" - Debugger statements: PRESERVED"),i&&(c.info("\u{1F4CA} Bundle analysis enabled"),c.info(` Visual treemap will open after build (stats.html)
8
+ `)),{outDir:"dist",sourcemap:o||a,cacheDir:"node_modules/.vite",target:"baseline-widely-available",minify:a?!1:"esbuild",reportCompressedSize:!1,chunkSizeWarningLimit:2048,assetsInlineLimit:0,esbuild:{format:"esm",drop:a?[]:["console","debugger"],legalComments:"none"},cssMinify:a?!1:"esbuild",cssCodeSplit:!0,rollupOptions:{external:Cs(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...u.manualChunks&&{manualChunks:u.manualChunks},compact:!0},onwarn(g,f){g.code!=="MODULE_LEVEL_DIRECTIVE"&&f(g)},plugins:[...a?[]:[Ts({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let g=E.getInstance(),f=g.getAppRoot(),m="dist",d=g.resolveAppPath(`${m}/stats.html`),P=()=>{try{let T=g.resolveAppPath(m);g.pathExists(T)||g.mkdir(T)}catch{}},w=Fs({filename:d,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:o||a,projectRoot:f});if(w.buildStart){let T=w.buildStart.bind(w);w.buildStart=function(...S){P();let D=T.apply(this,S);return D&&typeof D.then=="function"?D.catch(N=>{}):D}}else w.buildStart=function(){P()};let _=["generateBundle","writeBundle","closeBundle"];for(let T of _)if(w[T]){let S=w[T];w[T]=function(...D){try{P();let N=S.apply(this,D);return N&&typeof N.then=="function"?N.catch(v=>{let b=v?.message||v?.toString()||String(v)||"Unknown error";c.warn(`Bundle visualizer warning in ${T}: ${b}`),T==="closeBundle"&&c.warn(`You can manually open ${d} to view the bundle analysis`)}):N}catch(N){let v=N?.message||N?.toString()||String(N)||"Unknown error";c.warn(`Bundle visualizer warning in ${T}: ${v}`),T==="closeBundle"&&c.warn(` You can manually open ${d} to view the bundle analysis`)}}}return w})()]:[]]}}}function Cs(n){return n?["firebase-admin","gcp-metadata","google-logging-utils","@google-cloud/firestore",/\.node$/,"esbuild",/@esbuild\/.*/]:["gcp-metadata","google-logging-utils","payload","file-type","firebase-admin","firebase-admin/app","firebase-admin/auth","firebase-admin/firestore","firebase-admin/functions","firebase-admin/credential","@google-cloud/firestore","google-auth-library","google-gax","googleapis-common"]}function Is(){let n=!1,e=E.getInstance();if((e.pathExists("/.dockerenv")||e.pathExists("/run/.containerenv"))&&(n=!0),!n&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(n=!0),!n&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(n=!0),!n&&process.platform==="linux"&&e.pathExists("/proc/self/cgroup"))try{let r=e.readSync("/proc/self/cgroup");r&&(r.includes("docker")||r.includes("containerd"))&&(n=!0)}catch{}let t=!1;if((process.env.WSL_DISTRO_NAME||process.env.WSLENV)&&(t=!0),!t&&process.platform==="linux"&&e.pathExists("/proc/version"))try{let r=(e.readSync("/proc/version")||"").toLowerCase();t=r.includes("microsoft")||r.includes("wsl")}catch{}if(!t&&process.platform==="linux"&&e.pathExists("/proc/sys/kernel/osrelease"))try{let r=(e.readSync("/proc/sys/kernel/osrelease")||"").toLowerCase()||"";(r.includes("microsoft")||r.includes("wsl"))&&(t=!0)}catch{}if(!t&&process.platform==="win32"){let r=process.cwd();r&&(r.includes("\\wsl$")||r.includes("\\wsl.localhost"))&&(t=!0)}let s=typeof process.versions?.bun=="string";return{isDocker:n,isWSL2:t,isBun:s}}function Ms(n,e){if(n!==void 0)return n;let{isDocker:t,isWSL2:s,isBun:r}=Is();if(t||s||r){let o=t?"Docker":s?"WSL2":"Bun";return e.info(`Detected ${o} environment - enabling polling mode for file watching`),!0}}function Pt(n,e={},t){let s=E.getInstance(),r=s.getRepoRoot(),{watch:o,hmr:a,host:i,...l}=e||{},c=a||{},u=i===!0?"localhost":i||"localhost",p={...c.port&&{port:c.port},...c.clientPort&&{clientPort:c.clientPort},host:c.host??u,...c.protocol&&{protocol:c.protocol},overlay:c.overlay??!0,timeout:c.timeout??5e3},g=i!==void 0?i:!0,f=l.https===!0;return{port:n,host:g,open:e.open!==void 0?e.open:!0,https:f,fs:{allow:[r,s.resolveRepoPath("packages"),s.resolveRepoPath("node_modules")],strict:!1},watch:(()=>{let m=Ms(e?.watch?.usePolling,t);return{usePolling:m,interval:e?.watch?.interval??2e3,...m&&{awaitWriteFinish:{stabilityThreshold:300,pollInterval:100}},...e?.watch||{}}})(),hmr:{...p,...c},headers:{"Cross-Origin-Opener-Policy":"same-origin-allow-popups","Cross-Origin-Embedder-Policy":"unsafe-none"},middlewareMode:!1,...l}}function Rt(n={}){let e=n.https===!0;return{...n,https:e}}U();var $t={debug:!1,verbose:process.env.CI!=="true",seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1,aiCrawlers:"recommended",llmsTxt:!0,speculationRules:!0,hreflang:!0,breadcrumbSchema:!0,websiteSchema:!0,organizationSchema:!0},serverShim:{enabled:!0},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},features:{}};var se={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function ve(n,e,t,s={}){let{protectedKeys:r=[],onConflict:o}=s;if(e==null)return n;switch(t){case se.CONCATENATE_DEDUPE:{if(!Array.isArray(n)||!Array.isArray(e))return e;let a=[...n,...e];return[...new Set(a)]}case se.SHALLOW_MERGE:return typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e)?e:{...n,...e};case se.DEEP_MERGE:{if(typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e))return e;let a={...n};for(let i in e){if(r.includes(i)){o&&o(i,n[i],e[i]);continue}typeof a[i]=="object"&&typeof e[i]=="object"&&a[i]!==null&&e[i]!==null&&!Array.isArray(a[i])&&!Array.isArray(e[i])?a[i]=ve(a[i],e[i],se.DEEP_MERGE,{protectedKeys:r,onConflict:o}):a[i]=e[i]}return a}case se.REPLACE:default:return e}}function Et(n,e,t=[],s){let r=[...n,...e||[]],o=[...new Set(r)];return[...new Set([...o,...t])]}var $e={...$t,base:"/",mode:process.env.NODE_ENV==="production"?"production":"development",logLevel:process.env.NODE_ENV==="production"?"warn":"info",server:{port:3e3,strictPort:!0,host:!0,open:!0,cors:!0,https:!1,hmr:{overlay:!0,timeout:5e3,usePolling:void 0,interval:2e3},watch:{usePolling:void 0,interval:2e3}},build:{sourcemap:!0,target:"es2020",minify:"esbuild",cssMinify:"esbuild",analyze:!1},preview:{port:4173,strictPort:!0,host:!0,open:!1,cors:!0,https:!1},routes:{hmr:!0},themes:{},i18n:{},assets:{},pwa:{enabled:!1},prerender:{routes:"auto",waitForSelector:"#root > *",timeout:3e4,concurrency:4},chunking:{reactCore:[]},pluginFactory:{verbose:!0,disableHmr:!1,hmrSmartDetection:!0,hmrDebounceMs:500,hmrCacheTimeout:3e4},resolve:{alias:{"@":"/src"},preserveSymlinks:!1},define:{__DEV__:JSON.stringify(process.env.NODE_ENV==="development"),__PROD__:JSON.stringify(process.env.NODE_ENV==="production")},optimizeDeps:{include:[...xe.mandatoryIncludes],exclude:[...xe.buildTools,...Object.values(j)],esbuildOptions:{format:"esm",target:"es2020",platform:"browser",define:{"process.env.NODE_ENV":JSON.stringify(process.env.NODE_ENV||"development")},external:["next","next/*"]}},plugins:[],css:{},envDir:void 0};function _t(n={},e={}){let{onConflict:t}=e,s={...$e},r=[],o=(a,i,l,c)=>{r.push({key:a,frameworkValue:i,userValue:l,reason:c}),t&&t(a,i,l,c)};if("prerender"in n){let a=n.prerender;a===!1?n.prerender={routes:[]}:a===!0?n.prerender={routes:"auto"}:Array.isArray(a)&&(n.prerender={routes:a})}return Object.keys(n).forEach(a=>{let i=n[a],l=s[a];if(a==="optimizeDeps"&&typeof i=="object"&&i!==null){let c=l?.include||[],u=l?.exclude||[],p=i.include||[],g=i.exclude||[],f=c.filter(_=>!_.startsWith("@donotdev/")),m=g.filter(_=>f.includes(_));if(m.length>0)for(let _ of m)o("optimizeDeps.exclude",_,"excluded",`Framework requires ${_} to be included. It will be included despite your exclusion.`);let d=Et(c,p,f),P=ve(u,g,se.CONCATENATE_DEDUPE),w=ve(l?.esbuildOptions||{},i.esbuildOptions||{},se.DEEP_MERGE,{protectedKeys:["external"],onConflict:_=>o(`optimizeDeps.esbuildOptions.${_}`,l?.esbuildOptions?.[_],i.esbuildOptions?.[_],`Framework requires ${_} to remain as configured.`)});s[a]={...l,include:d,exclude:P,esbuildOptions:w,...Object.fromEntries(Object.entries(i).filter(([_])=>!["include","exclude","esbuildOptions"].includes(_)))};return}if(a==="css"&&typeof i=="object"&&i!==null){s[a]=ve(l||{},i,se.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>o("css.postcss","framework PostCSS config",i.postcss,"Framework PostCSS config is required and cannot be overridden. Your postcss config is ignored.")});return}if(a==="define"&&typeof i=="object"&&i!==null){s[a]=ve(l||{},i,se.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:c=>o(`define.${c}`,l?.[c],i[c],`Framework requires ${c} to remain as configured.`)});return}if(Array.isArray(i)){Array.isArray(l)?s[a]=ve(l,i,se.CONCATENATE_DEDUPE):s[a]=i;return}if(typeof i=="object"&&i!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){s[a]=ve(l,i,se.SHALLOW_MERGE);return}s[a]=i}),s}function kt(n){let{server:e={},preview:t={},mode:s,build:r={},resolve:o={},routes:a={},themes:i={},i18n:l={},assets:c={},features:u={},seo:p={},prerender:g={},pwa:f={},serverShim:m={},chunking:d={},discovery:P={},pluginFactory:w={},debug:_,verbose:T,base:S,define:D={},optimizeDeps:N={},plugins:v=[],css:b={},envDir:k,...O}=n,R=s!=="production",V=_||R,z=s==="production"&&(r.analyze??$e.build.analyze);return{mode:s,debug:_,verbose:T,isDev:R,isDebug:V,shouldAnalyze:z,serverOptions:e,previewOptions:t,buildOverrides:r,resolveOptions:o,routeOptions:a,themeOptions:i,i18nOptions:l,assetOptions:c,featureOptions:u,seoOptions:p,prerenderOptions:g,pwaOptions:f,serverShimOptions:m,chunkingOptions:d,discoveryOptions:P,pluginFactoryOptions:w,base:S,defineOptions:D,optimizeDepsOptions:N,pluginsOptions:v,cssOptions:b,envDir:k,restOptions:O}}L();import js from"autoprefixer";import zs from"postcss-import";import Ls from"postcss-nesting";function Dt({postcssImport:n,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?n({resolve:s}):n,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function At(n={}){if(n.postcss)return n.postcss;let e=E.getInstance();return Dt({postcssImport:zs,postcssNesting:Ls,autoprefixer:js,resolve:(s,r)=>{let o=e.resolvePackage(s,r);if(o)return o;if(s.startsWith("@donotdev/")){let a=s.split("/")[0]+"/"+s.split("/")[1],i=s.split("/").slice(2).join("/"),l=e.resolveFrameworkPackage(a,r);if(l&&i){let c=e.resolvePath(i,l);if(e.pathExists(c))return c}}return e.resolvePath(s,r)}})}import dr from"@vitejs/plugin-basic-ssl";import mr from"@vitejs/plugin-react";import hr from"vite-tsconfig-paths";var Y=class{static generateVirtualModule(e,t,s=!1,r=void 0,o=void 0){return t.isEmpty(e)?t.generateEmpty(e,s,r,o):t.generateModule(e,s,o)}static generateInspection(e,t,s,r){return t.generateInspection.length>=3?t.generateInspection(e,s,r):t.generateInspection(e,s)}static wrapVirtualModule(e,t){return`// Virtual module: ${e}
9
9
  // Generated by @donotdev/config discovery
10
10
  // Version: 1.0.0
11
11
 
@@ -41,13 +41,13 @@ var es=Object.defineProperty;var Ue=(n,e)=>()=>(n&&(e=n(n=0)),e);var ts=(n,e)=>{
41
41
  `);return`// Helper functions for ${e}
42
42
  // Generated by @donotdev/config
43
43
 
44
- ${s}`}static validateTemplates(e){return["isEmpty","generateModule","generateEmpty","generateInspection"].every(s=>e[s]&&typeof e[s]=="function")}static createTemplateConfig(e,t){let{isEmpty:s=()=>!1,generateModule:r=()=>"",generateEmpty:o=()=>"",generateInspection:a=()=>"",generateManifest:i=()=>({}),logConfig:l=()=>{},logStats:u=()=>{},logManifest:c=()=>{}}=t;return{isEmpty:s,generateModule:r,generateEmpty:o,generateInspection:a,generateManifest:i,logConfig:l,logStats:u,logManifest:c,pluginName:e,version:"1.0.0",createdAt:new Date().toISOString()}}static getEmptyResultWithError(e,t){let s=t?.message||t||"Unknown error";if(e&&typeof e._getEmptyResult=="function")try{let r=e._getEmptyResult();return r.errors&&Array.isArray(r.errors)?r.errors.push(s):r.errors===void 0&&(r.errors=[s]),r.source==="empty"&&(r.source="error"),r}catch{return{errors:[s],source:"error"}}return{errors:[s],source:"error"}}};B();function ue(n){let{pluginName:e,icon:t,virtualModuleId:s,DiscoveryClass:r,discoveryMethod:o,filePatterns:a,templates:i,defaultInspectionPath:l,manifestFileName:u,createDiscovery:c,discoveryOptions:p={},configKey:g}=n;return function(h={}){let{debug:D,verbose:O,virtualModuleId:y=s,inspectionFilePath:k=l,hmrDebounceMs:R,hmrCacheTimeout:b,hmrSmartDetection:S,disableHmr:v,...A}=h;if(!H.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let T={...xe.discovery,...p,debug:D,verbose:O,...A},X=g||(()=>{let m=e.match(/dndev-vite-(\w+)-discovery/);return m?m[1]:null})(),P=F(e,D,O,{fileLogging:T.fileLogging,logDir:T.logDir}),x=$.getInstance(),W=()=>{let m=x.getAppRoot(),w=x.getRepoRoot();return m&&m!==w},Se=Date.now(),Q=c?c(x,T):new r(x,T),ie="\0"+y,_="",N=!1,C=null,I=0,ee=!1,G=null,pe=!1,de=null,ve=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(Q.clearCache(),G=null,P.info("Discovery cache cleared manually"),"Cache cleared"));function je(m){let z=H.generateVirtualModule(m,i,D,T,X).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!v&&N&&(z+=`
44
+ ${s}`}static validateTemplates(e){return["isEmpty","generateModule","generateEmpty","generateInspection"].every(s=>e[s]&&typeof e[s]=="function")}static createTemplateConfig(e,t){let{isEmpty:s=()=>!1,generateModule:r=()=>"",generateEmpty:o=()=>"",generateInspection:a=()=>"",generateManifest:i=()=>({}),logConfig:l=()=>{},logStats:c=()=>{},logManifest:u=()=>{}}=t;return{isEmpty:s,generateModule:r,generateEmpty:o,generateInspection:a,generateManifest:i,logConfig:l,logStats:c,logManifest:u,pluginName:e,version:"1.0.0",createdAt:new Date().toISOString()}}static getEmptyResultWithError(e,t){let s=t?.message||t||"Unknown error";if(e&&typeof e._getEmptyResult=="function")try{let r=e._getEmptyResult();return r.errors&&Array.isArray(r.errors)?r.errors.push(s):r.errors===void 0&&(r.errors=[s]),r.source==="empty"&&(r.source="error"),r}catch{return{errors:[s],source:"error"}}return{errors:[s],source:"error"}}};L();function ce(n){let{pluginName:e,icon:t,virtualModuleId:s,DiscoveryClass:r,discoveryMethod:o,filePatterns:a,templates:i,manifestFileName:l,createDiscovery:c,discoveryOptions:u={},configKey:p}=n;return function(f={}){let{debug:m,verbose:d,virtualModuleId:P=s,hmrDebounceMs:w,hmrCacheTimeout:_,hmrSmartDetection:T,disableHmr:S,...D}=f;if(!Y.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let N={...$e.discovery,...u,debug:m,verbose:d,...D},v=p||(()=>{let y=e.match(/dndev-vite-(\w+)-discovery/);return y?y[1]:null})(),b=C(e,m,d,{fileLogging:N.fileLogging,logDir:N.logDir}),k=E.getInstance(),O=()=>{let y=k.getAppRoot(),$=k.getRepoRoot();return y&&y!==$},R=Date.now(),V=c?c(k,N):new r(k,N),z="\0"+P,ae="",de=!1,pe=null,ge=0,be=!1,x=null,F=!1,M=null,I=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(V.clearCache(),x=null,b.info("Discovery cache cleared manually"),"Cache cleared"));function X(y){let B=Y.generateVirtualModule(y,i,m,N,v).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!S&&de&&(B+=`
45
45
 
46
46
  // HMR boundary for ${e}
47
47
  if (import.meta.hot) {
48
48
  import.meta.hot.accept();
49
49
  }
50
- `),z}function Le(m){return H.generateInspection(m,i,_,T)}async function Pe(){if(_)try{let m=await Q[o](),w=Le(m),z=x.resolveAppPath(k);await x.write(z,w),P.debug(`Generated inspection file: ${x.getRelativePath(z)}`)}catch(m){P.error(`${e} failed to write inspection file (${k}): ${m.message}`),P.error(`Stack: ${m.stack||"No stack trace available"}`)}}function De(m){let w=m.replace(/\\/g,"/");if(v||w.includes("/node_modules/")||w.includes("/.git/")||w.includes("/dist/")||w.includes("/build/")||w.includes("/coverage/")||w.includes("/.vite/")||w.includes("/.turbo/")||w.endsWith(".d.ts")||w.endsWith(".tsbuildinfo")||w.endsWith(".map")||w.endsWith(".css.map")||w.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(w))return!1;let z=x.getRelativePath(w);if(z.startsWith("packages/"))return!1;let le=z.startsWith("src/")&&/\.(ts|tsx)$/.test(z);return le?Array.isArray(a)&&a.length>0?a.some(ne=>typeof ne=="function"?ne(w):typeof ne=="string"?ne.startsWith("**/")?w.endsWith(ne.slice(3)):w.endsWith(ne):!1):le:!1}function Ne(m){if(v)return P.debug("Virtual modules are static - HMR disabled"),[];let w=Date.now();return pe?(P.debug("HMR already in progress, skipping update"),[]):w-I<R?(ee||(ee=!0,C=setTimeout(()=>{ee=!1,I=Date.now(),Ae(m)},R)),[]):(I=w,Ae(m))}function Ae(m){let w=Date.now();if(de===m.file&&w-I<100)return P.debug(`Same file processed too recently: ${m.file}`),[];if(!De(m.file))return P.debug(`Skipping irrelevant file change: ${m.file}`),[];P.debug(`Relevant file changed: ${m.file}`),pe=!0,de=m.file;try{let z=Date.now()-(G?.timestamp||0);if(z<b&&G){P.debug(`Using cached discovery data (age: ${z}ms)`);let ne=m.server.moduleGraph.getModuleById(ie);return ne&&m.server.reloadModule(ne),[]}Q.clearCache();let le=m.server.moduleGraph.getModuleById(ie);return le&&m.server.reloadModule(le),C&&clearTimeout(C),C=setTimeout(()=>{Pe()},500),[]}finally{pe=!1,setTimeout(()=>{de===m.file&&(de=null)},200)}}return{name:e,enforce:"pre",configResolved(m){_=m.root,N=m.command==="serve",D&&P.debug(`${t} ${e} initialized`),N&&P.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),i.logConfig&&i.logConfig(T)},config(m){return m.optimizeDeps||(m.optimizeDeps={}),m.optimizeDeps.exclude||(m.optimizeDeps.exclude=[]),m.optimizeDeps.exclude.includes(y)||m.optimizeDeps.exclude.push(y),m},resolveId(m){return m===y?(P.debug(`Resolving virtual module: ${m}`),{id:ie,moduleSideEffects:!0}):null},async load(m){if(m!==ie)return null;if(P.debug(`Loading virtual module: ${m}`),!W()){P.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let w=0;for(;!W()&&w<100;)await new Promise(z=>setTimeout(z,10)),w++;if(!W())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let w;return G?(P.debug("Using cached discovery data for virtual module"),w=G):(P.warn(`\u26A0\uFE0F No cached discovery data found for ${e} - running discovery in load() hook. This may indicate buildStart() hook did not run or failed. Performance may be impacted.`),w=await Q[o](),G=w,P.debug("Discovery completed for virtual module")),je(w)}catch(w){return P.error(`${e} virtual module (${ie}) failed to load: ${w.message}`),P.error(`Stack: ${w.stack||"No stack trace available"}`),i.generateEmpty({},D,T,X)}},async buildStart(){if(ve=!1,!W()){P.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let m=0;for(;!W()&&m<100;)await new Promise(w=>setTimeout(w,10)),m++;if(!W())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let m=await Q[o](!G);G=m,await Pe(),i.logStats&&i.logStats(m,t,P)}catch(m){P.error(`${e} discovery failed during file scanning: ${m.message}`),P.error(`Stack: ${m.stack||"No stack trace available"}`),G=H.getEmptyResultWithError(Q,m)}finally{ve=!0}},configureServer(){ve=!0},handleHotUpdate(m){return v?[]:ve?Ne(m):(P.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!G){P.warn("No cached discovery data for manifest generation - skipping");return}try{let m=H.generateManifest(G,i.generateManifest);this.emitFile({type:"asset",fileName:u,source:JSON.stringify(m,null,2)}),O&&i.logManifest&&i.logManifest(G,e)}catch(m){P.error(`${e} manifest generation failed: ${m.message}`),P.error(`Stack: ${m.stack||"No stack trace available"}`)}},transform(m,w){return w===ie?{code:m,map:null}:null}}}}var no={generateGlobals:H.generateGlobals,generateExports:H.generateExports,generateDefaultExport:H.generateDefaultExport,wrapVirtualModule:H.wrapVirtualModule,generateInspectionHeader:H.generateInspectionHeader,validateTemplates:H.validateTemplates,createTemplateConfig:H.createTemplateConfig};L();var oe=class n{constructor(e,t={}){if(this.constructor===n)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=F(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}};L();var Ie=class extends oe{constructor(e,t={}){super(e,{assets:se.assets.fallback,assetPatterns:se.assets.patterns,frameworkPackage:Be.package,assetsPath:Be.assetsPath,modernFormats:se.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=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(a=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,u=await this._processAssetFiles(l),c=this._buildAssetManifest(u),p=await this._readLogoSvgContent("/logo.svg",t);return{assets:u,manifest:{...c,logoSvgContent:p},copiedAssets:s,generatedAssets:a,pwaIcons:this._extractPWAIcons(u)}}_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(Ee.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(`${Ee.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(`${Ee.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(Ee.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=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let p=`${s}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,l),a.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),i.push(c.name)}}let u=await import("sharp").catch(()=>null);if(!u)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(c=>c.name));else for(let c of r){let p=`${s}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{let g=u.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),d;c.format==="ico"?d=await g.toFormat("png").toBuffer():d=await g.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,d),a.push(c.name)}catch(g){this.logger.debug(`Failed to generate ${c.name}: ${g.message}`),i.push(c.name)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(u=>u.name),error:l.message}}}};B();var qe={data:null},xs={isEmpty:n=>!n.manifest||n.assets?.length===0,generateModule:(n,e,t="assets")=>{let{manifest:s,assets:r,copiedAssets:o}=n,a=s.logoSvgContent||null,i={totalAssets:r.length,copiedAssets:o.length,hasLogo:s.logo.optimal!==null,hasFavicon:s.favicon.optimal!==null,hasManifest:s.manifest!==null,timestamp:new Date().toISOString()};return`// ${M.assets} - Generated asset manifest
50
+ `),B}function De(y){let $=y.replace(/\\/g,"/");if(S||$.includes("/node_modules/")||$.includes("/.git/")||$.includes("/dist/")||$.includes("/build/")||$.includes("/coverage/")||$.includes("/.vite/")||$.includes("/.turbo/")||$.endsWith(".d.ts")||$.endsWith(".tsbuildinfo")||$.endsWith(".map")||$.endsWith(".css.map")||$.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test($))return!1;let B=k.getRelativePath($);if(B.startsWith("packages/"))return!1;let Q=B.startsWith("src/")&&/\.(ts|tsx)$/.test(B);return Q?Array.isArray(a)&&a.length>0?a.some(oe=>typeof oe=="function"?oe($):typeof oe=="string"?oe.startsWith("**/")?$.endsWith(oe.slice(3)):$.endsWith(oe):!1):Q:!1}function we(y){if(S)return b.debug("Virtual modules are static - HMR disabled"),[];let $=Date.now();return F?(b.debug("HMR already in progress, skipping update"),[]):$-ge<w?(be||(be=!0,pe=setTimeout(()=>{be=!1,ge=Date.now(),Pe(y)},w)),[]):(ge=$,Pe(y))}function Pe(y){let $=Date.now();if(M===y.file&&$-ge<100)return b.debug(`Same file processed too recently: ${y.file}`),[];if(!De(y.file))return b.debug(`Skipping irrelevant file change: ${y.file}`),[];b.debug(`Relevant file changed: ${y.file}`),F=!0,M=y.file;try{let B=Date.now()-(x?.timestamp||0);if(B<_&&x){b.debug(`Using cached discovery data (age: ${B}ms)`);let oe=y.server.moduleGraph.getModuleById(z);return oe&&y.server.reloadModule(oe),[]}V.clearCache();let Q=y.server.moduleGraph.getModuleById(z);return Q&&y.server.reloadModule(Q),[]}finally{F=!1,setTimeout(()=>{M===y.file&&(M=null)},200)}}return{name:e,enforce:"pre",configResolved(y){ae=y.root,de=y.command==="serve",m&&b.debug(`${t} ${e} initialized`),de&&b.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),i.logConfig&&i.logConfig(N)},config(y){return y.optimizeDeps||(y.optimizeDeps={}),y.optimizeDeps.exclude||(y.optimizeDeps.exclude=[]),y.optimizeDeps.exclude.includes(P)||y.optimizeDeps.exclude.push(P),y},resolveId(y){return y===P?(b.debug(`Resolving virtual module: ${y}`),{id:z,moduleSideEffects:!0}):null},async load(y){if(y!==z)return null;if(b.debug(`Loading virtual module: ${y}`),!O()){b.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let $=0;for(;!O()&&$<100;)await new Promise(B=>setTimeout(B,10)),$++;if(!O())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let $;return x?(b.debug("Using cached discovery data for virtual module"),$=x):(b.warn(`\u26A0\uFE0F No cached discovery data found for ${e} - running discovery in load() hook. This may indicate buildStart() hook did not run or failed. Performance may be impacted.`),$=await V[o](),x=$,b.debug("Discovery completed for virtual module")),X($)}catch($){return b.error(`${e} virtual module (${z}) failed to load: ${$.message}`),b.error(`Stack: ${$.stack||"No stack trace available"}`),i.generateEmpty({},m,N,v)}},async buildStart(){if(I=!1,!O()){b.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let y=0;for(;!O()&&y<100;)await new Promise($=>setTimeout($,10)),y++;if(!O())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let y=await V[o](!x);if(x=y,l&&p==="routes"&&y?.routes)try{let $={routes:y.routes.map(Q=>({path:Q.path,auth:Q.auth,meta:Q.meta})),source:y.source||"auto-discovery",totalRoutes:y.routes.length,generatedAt:new Date().toISOString()},B=k.resolveAppPath(`public/${l}`);await k.write(B,JSON.stringify($,null,2)),b.debug(`Generated route manifest: public/${l}`)}catch($){b.error(`Failed to write route manifest: ${$.message}`)}i.logStats&&i.logStats(y,t,b)}catch(y){b.error(`${e} discovery failed during file scanning: ${y.message}`),b.error(`Stack: ${y.stack||"No stack trace available"}`),x=Y.getEmptyResultWithError(V,y)}finally{I=!0}},configureServer(){I=!0},handleHotUpdate(y){return S?[]:I?we(y):(b.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!x){b.warn("No cached discovery data for manifest generation - skipping");return}try{let y=Y.generateManifest(x,i.generateManifest);this.emitFile({type:"asset",fileName:l,source:JSON.stringify(y,null,2)}),d&&i.logManifest&&i.logManifest(x,e)}catch(y){b.error(`${e} manifest generation failed: ${y.message}`),b.error(`Stack: ${y.stack||"No stack trace available"}`)}},transform(y,$){return $===z?{code:y,map:null}:null}}}}var To={generateGlobals:Y.generateGlobals,generateExports:Y.generateExports,generateDefaultExport:Y.generateDefaultExport,wrapVirtualModule:Y.wrapVirtualModule,generateInspectionHeader:Y.generateInspectionHeader,validateTemplates:Y.validateTemplates,createTemplateConfig:Y.createTemplateConfig};U();var re=class n{constructor(e,t={}){if(this.constructor===n)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=C(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}};U();var Le=class extends re{constructor(e,t={}){super(e,{assets:te.assets.fallback,assetPatterns:te.assets.patterns,frameworkPackage:Ye.package,assetsPath:Ye.assetsPath,modernFormats:te.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=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(a=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,c=await this._processAssetFiles(l),u=this._buildAssetManifest(c),p=await this._readLogoSvgContent("/logo.svg",t);return{assets:c,manifest:{...u,logoSvgContent:p},copiedAssets:s,generatedAssets:a,pwaIcons:this._extractPWAIcons(c)}}_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=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...r].map(u=>u.name),error:"Failed to read logo.svg"};for(let u of o){let p=`${s}/${u.name}`;if(this.pathResolver.pathExists(p)){i.push(u.name);continue}try{await this.pathResolver.write(`public/${u.name}`,l),a.push(u.name)}catch(g){this.logger.debug(`Failed to copy ${u.name}: ${g.message}`),i.push(u.name)}}let c=await import("sharp").catch(()=>null);if(!c)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(u=>u.name));else for(let u of r){let p=`${s}/${u.name}`;if(this.pathResolver.pathExists(p)){i.push(u.name);continue}try{let g=c.default(t).resize(u.size,u.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),f;u.format==="ico"?f=await g.toFormat("png").toBuffer():f=await g.toFormat(u.format).toBuffer(),await this.pathResolver.write(`public/${u.name}`,f),a.push(u.name)}catch(g){this.logger.debug(`Failed to generate ${u.name}: ${g.message}`),i.push(u.name)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(c=>c.name),error:l.message}}}};L();var Nt={data:null},Us={isEmpty:n=>!n.manifest||n.assets?.length===0,generateModule:(n,e,t="assets")=>{let{manifest:s,assets:r,copiedAssets:o}=n,a=s.logoSvgContent||null,i={totalAssets:r.length,copiedAssets:o.length,hasLogo:s.logo.optimal!==null,hasFavicon:s.favicon.optimal!==null,hasManifest:s.manifest!==null,timestamp:new Date().toISOString()};return`// ${j.assets} - Generated asset manifest
51
51
  const assetManifest = ${JSON.stringify(s,null,2)};
52
52
  const assetStats = ${JSON.stringify(i,null,2)};
53
53
 
@@ -65,7 +65,7 @@ if (typeof globalThis !== 'undefined') {
65
65
  }
66
66
 
67
67
  // Populate assets configuration
68
- globalThis._DNDEV_CONFIG_.${V[t]} = {
68
+ globalThis._DNDEV_CONFIG_.${H[t]} = {
69
69
  mapping: assetManifest,
70
70
  logoSvgContent: ${JSON.stringify(a)},
71
71
  manifest: {
@@ -117,7 +117,7 @@ export default {
117
117
  getManifest,
118
118
  getAllAssets
119
119
  };
120
- `},generateEmpty:(n,e,t,s="assets")=>{let r={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${M.assets} - Empty asset manifest
120
+ `},generateEmpty:(n,e,t,s="assets")=>{let r={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${j.assets} - Empty asset manifest
121
121
  const assetManifest = {
122
122
  logo: { optimal: null, fallback: null },
123
123
  favicon: { optimal: null, fallback: null },
@@ -143,7 +143,7 @@ if (typeof globalThis !== 'undefined') {
143
143
  }
144
144
 
145
145
  // Populate empty assets configuration
146
- globalThis._DNDEV_CONFIG_.${V[s]} = {
146
+ globalThis._DNDEV_CONFIG_.${H[s]} = {
147
147
  mapping: assetManifest,
148
148
  logoSvgContent: null,
149
149
  manifest: {
@@ -216,7 +216,7 @@ export default discoveredAssets;
216
216
  `:`/**
217
217
  * Generated Asset Discovery Results
218
218
  * Generated at: ${new Date().toISOString()}
219
- * Import from '${M.assets}'
219
+ * Import from '${j.assets}'
220
220
  */
221
221
 
222
222
  export const discoveredAssets = ${JSON.stringify(e,null,2)};
@@ -233,7 +233,7 @@ export const assetStats = {
233
233
  };
234
234
 
235
235
  export default discoveredAssets;
236
- `},generateManifest:n=>({assets:n.assets?.length||0,copied:n.copiedAssets?.length||0,timestamp:Date.now(),hasLogo:n.manifest?.logo?.optimal!==null,hasFavicon:n.manifest?.favicon?.optimal!==null}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.assets?.length||0,r=n.generatedAssets?.length||0;t&&(r>0?t.info(`${e} Assets: ${s} found, ${r} generated`):t.info(`${e} Assets: ${s} found`))}},Ss=[n=>n.includes("/public/"),n=>n.endsWith(".png")||n.endsWith(".svg")||n.endsWith(".ico"),n=>n.includes("favicon")||n.includes("logo")||n.includes("manifest")];function wt(n={}){let e=ue({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:M.assets,DiscoveryClass:Ie,discoveryMethod:"discoverAssets",filePatterns:Ss,templates:xs,defaultInspectionPath:j.vite.assetInspection,manifestFileName:j.manifests.asset,configKey:"assets"})(n),t=$.getInstance(),s=F("asset-plugin",n.debug,n.verbose),r=e.buildStart;return e.buildStart=async function(...o){r&&await r.apply(this,o);let a=null;try{let i=t.resolveAppPath(j.vite.assetInspection);if(t.pathExists(i)){let l=t.readSync(i,{format:"json"});l&&(a=l,qe.data=a)}}catch(i){s.debug(`Could not cache asset data: ${i.message}`)}},e}import{loadEnv as Ps}from"vite";L();var xt={isEmpty:n=>!n.env||Object.keys(n.env).length===0,generateModule:(n,e,t="env")=>{let{env:s,mode:r}=n;if(!s||Object.keys(s).length===0)return xt.generateEmpty(n,e,void 0,t);let o={totalVars:Object.keys(s).length,mode:r,source:n.source,generatedAt:new Date().toISOString()};return`// ${M.env} - Generated environment variables
236
+ `},generateManifest:n=>({assets:n.assets?.length||0,copied:n.copiedAssets?.length||0,timestamp:Date.now(),hasLogo:n.manifest?.logo?.optimal!==null,hasFavicon:n.manifest?.favicon?.optimal!==null}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.assets?.length||0,r=n.generatedAssets?.length||0;t&&(r>0?t.info(`${e} Assets: ${s} found, ${r} generated`):t.info(`${e} Assets: ${s} found`))}},Ws=[n=>n.includes("/public/"),n=>n.endsWith(".png")||n.endsWith(".svg")||n.endsWith(".ico"),n=>n.includes("favicon")||n.includes("logo")||n.includes("manifest")];function Ot(n={}){let e=ce({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:j.assets,DiscoveryClass:Le,discoveryMethod:"discoverAssets",filePatterns:Ws,templates:Us,manifestFileName:ie.manifests.asset,configKey:"assets"})(n),t=E.getInstance(),s=C("asset-plugin",n.debug,n.verbose),r=e.buildStart;return e.buildStart=async function(...o){r&&await r.apply(this,o)},e}import{loadEnv as Gs}from"vite";U();var Tt={isEmpty:n=>!n.env||Object.keys(n.env).length===0,generateModule:(n,e,t="env")=>{let{env:s,mode:r}=n;if(!s||Object.keys(s).length===0)return Tt.generateEmpty(n,e,void 0,t);let o={totalVars:Object.keys(s).length,mode:r,source:n.source,generatedAt:new Date().toISOString()};return`// ${j.env} - Generated environment variables
237
237
 
238
238
  const envData = ${JSON.stringify(s,null,2)};
239
239
  const envManifest = ${JSON.stringify(o,null,2)};
@@ -262,7 +262,7 @@ if (typeof globalThis !== 'undefined') {
262
262
  }
263
263
 
264
264
  // Populate env configuration (frozen to prevent tampering)
265
- globalThis._DNDEV_CONFIG_.${V[t]} = envData;
265
+ globalThis._DNDEV_CONFIG_.${H[t]} = envData;
266
266
  // Only freeze the env property, not the entire config (other plugins need to add properties)
267
267
  }
268
268
 
@@ -273,7 +273,7 @@ export const source = '${n.source}';
273
273
 
274
274
  // Default export
275
275
  export default envData;
276
- `},generateEmpty:(n,e,t,s="env")=>{let r={totalVars:0,mode:n.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${M.env} - Empty environment data
276
+ `},generateEmpty:(n,e,t,s="env")=>{let r={totalVars:0,mode:n.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${j.env} - Empty environment data
277
277
 
278
278
  const envData = {};
279
279
  const envManifest = ${JSON.stringify(r,null,2)};
@@ -302,7 +302,7 @@ if (typeof globalThis !== 'undefined') {
302
302
  }
303
303
 
304
304
  // Populate empty env configuration (frozen to prevent tampering)
305
- globalThis._DNDEV_CONFIG_.${V[s]} = envData;
305
+ globalThis._DNDEV_CONFIG_.${H[s]} = envData;
306
306
  // Only freeze the env property, not the entire config (other plugins need to add properties)
307
307
  }
308
308
 
@@ -312,20 +312,20 @@ export const source = 'empty';
312
312
 
313
313
  export default envData;
314
314
  `},generateInspection:n=>{let{env:e,mode:t}=n;return["/**"," * Generated Environment Variables",` * Mode: ${t}`,` * Generated at: ${new Date().toISOString()}`,` * Total variables: ${Object.keys(e).length}`," */","","```json",JSON.stringify(e,null,2),"```"].join(`
315
- `)},generateManifest:n=>({totalVars:Object.keys(n?.env||{}).length,mode:n?.mode||"development",variables:Object.keys(n?.env||{}),timestamp:Date.now()}),logStats:(n,e,t)=>{let s=Object.keys(n.env).length;t&&t.info(`${e} Env: ${s} VITE_* variables`)}},Ye=class{constructor(e,t={}){this.pathResolver=e,this.options=t,this.mode=t.mode||"development",this.appRoot=null}async discoverEnv(){try{let e=this.pathResolver.getAppRoot();if(!e)throw new Error("App root not available in EnvDiscovery");let s={...Ps(this.mode,e,"VITE_")};return this.mode==="production"&&(delete s.VITE_USE_FIREBASE_EMULATOR,delete s.VITE_FIREBASE_EMULATOR_HOST,delete s.VITE_FIREBASE_AUTH_EMULATOR_HOST,delete s.VITE_FIREBASE_FIRESTORE_EMULATOR_HOST,delete s.VITE_FIREBASE_FUNCTIONS_EMULATOR_PORT),s.MODE=this.mode,s.DEV=this.mode==="development",s.PROD=this.mode==="production",s.SSR=!1,{env:s,mode:this.mode,source:`${e}/.env`,errors:[]}}catch(e){return{env:{},mode:this.mode,source:"error",errors:[e.message]}}}};function St(n={}){return ue({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:M.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:xt,defaultInspectionPath:j.vite.envInspection,manifestFileName:j.manifests.env,configKey:"env",createDiscovery:(e,t)=>new Ye(e,{...t,mode:n.mode||t.mode||"development"})})({...n,disableHmr:!0})}L();L();var Pt=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,he=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:{...He.selectors,...this.options.customPatterns?.selectors},themes:{...He.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,i)=>{let l=a.replace(/[^a-zA-Z0-9]/g,"");return l?i===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.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),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(i))!==null;){let[,u,c,p]=o;if(!u||!p)continue;let g=c.match(this.patterns.themes.themeIcon),d=c.match(this.patterns.themes.themeIsDark),h={name:u,displayName:p,isDark:d?d[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${u} (${p})`),r.push(h),s.themes.set(u,{name:u,displayName:p,isDark:h.isDark,file:a,variables:new Set,meta:h.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(Pt.lastIndex=0;(r=Pt.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||"")}};B();var Es=3,Ke="<!-- DNDEV_FONT_PRELOADS -->";function Et(n={}){let{debug:e=!1}=n,t=F("font-preload",e,!1),s,r={},o=[],a=[];return{name:"vite-font-preload-plugin",enforce:"post",configResolved(i){r={root:i.root,base:i.base&&i.base!=="/"?i.base.replace(/\/$/,""):"",outDir:i.build?.outDir??"dist"};try{s=$.getInstance()}catch(l){t.debug(`Font preload: PathResolver not ready: ${l?.message}`)}},async buildStart(){if(!(!s||!s.getAppRoot()))try{let l=await s.resolvePatterns("css"),{consumerFiles:u}=await s.resolveFiles(l,"css");if(!u?.length){o=[Re.Inter],t.debug("Font preload: no consumer CSS, using default Inter");return}let c=new he(s,{debug:e,logger:t}),p=new Set;for(let d of u)try{let h=await s.read(d,{format:"text"});h&&c.extractFontFamilies(h).forEach(O=>p.add(O))}catch(h){t.debug(`Font preload: skip read ${d}: ${h?.message}`)}if(p.size===0){o=[Re.Inter],t.debug("Font preload: no font families in CSS, using default Inter");return}let g=new Set;for(let d of p){let h=Re[d];h&&g.add(h)}o=Array.from(g),t.debug(`Font preload: stems ${o.join(", ")} from CSS`)}catch(l){t.debug(`Font preload: discovery failed, use Inter: ${l?.message}`),o=[Re.Inter]}},generateBundle(i,l){if(!o.length)return;let u=r.base||"",c=[];for(let[p,g]of Object.entries(l)){if(g.type!=="asset"||!p.endsWith(".woff2")&&!p.endsWith(".woff"))continue;let d=p.toLowerCase();if(o.some(D=>d.includes(D))){let D=u?`${u}/${p}`:`/${p}`;c.push(D)}}a=c.slice(0,Es)},writeBundle(){if(!a.length)return;let i=s||$.getInstance(),l=r.root||process.cwd(),u=r.outDir||"dist",c=i.resolvePath(`${u}/index.html`,l);try{if(!i.pathExists(c)){t.debug(`Font preload: index.html not found at ${c}`);return}let p=i.readSync(c,{format:"text"}),g=a.map(d=>`<link rel="preload" as="font" href="${d}" type="font/woff2" crossorigin="anonymous" />`).join(`
316
- `);if(p.includes(Ke))p=p.replace(Ke,`${Ke}
317
- ${g}`);else{let d=p.indexOf("<!-- Fonts:"),h=d!==-1?p.indexOf("-->",d)+3:p.indexOf("</head>");h!==-1&&(p=p.slice(0,h)+`
318
- ${g}`+p.slice(h))}i.writeSync(c,p,{overwrite:!0}),t.debug(`Font preload: injected ${a.length} link(s)`)}catch(p){t.debug(`Font preload: write failed: ${p?.message}`)}}}}L();L();var $e=class extends oe{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=Te("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(_=>{let N=_.endsWith(".json")?_:`${_}/*_*.json`;return this.pathResolver.resolveAppPath(N)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let u=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${u.join(", ")}, framework lazy: ${c.join(", ")}`),u.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),d=(_,N)=>{let C=this.pathResolver.normalizePath(_),I=this.pathResolver.normalizePath(N);return C.startsWith(I)?C.slice(I.length+1):C},h=a.map(_=>d(_,t)),O=[...i,...l].map(_=>d(_,t)),y=u.map(_=>d(_,s)),k=c.map(_=>d(_,s)),R={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},b=await this.pathResolver._globWithNormalization(h,R),S=await this.pathResolver._globWithNormalization(O,R),v={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(_=>_!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(v.ignore)}`);let A=await this.pathResolver._globWithNormalization(y,v),T=await this.pathResolver._globWithNormalization(k,v);this.logger.debug(`Found ${b.length} eager, ${S.length} lazy, ${A.length} framework eager, ${T.length} framework lazy files`),A.length>0?this.logger.debug(`Framework eager files (first 3): ${A.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${u.join(", ")}`),T.length>0?this.logger.debug(`Framework lazy files (first 3): ${T.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let X=[...new Set([...b,...S,...A,...T])],P=new Set([...b,...A]),x={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},W=new Map,Se=[...A,...T];for(let _ of Se){let N=this._processTranslationFile(_,A.includes(_),t);if(N){let C=`${N.namespace}_${N.language}`;W.set(C,N),x.allNamespaces.add(N.namespace),x.supportedLanguages.add(N.language),A.includes(_)&&x.eagerNamespaces.add(N.namespace)}}let Q=new Set;for(let _ of X){if(Se.includes(_))continue;let N=this._processTranslationFile(_,P.has(_),t);if(N){let{namespace:C,language:I,importPath:ee,content:G}=N,pe=`${N.namespace}_${N.language}`;if(W.has(pe)){let de=W.get(pe);N.content=this._mergeTranslations(de.content,G)}x.allNamespaces.add(C),x.supportedLanguages.add(I),Q.add(I),P.has(_)&&x.eagerNamespaces.add(C),x.mapping[C]||(x.mapping[C]={}),x.mapping[C][I]=ee,N.content&&(x.content[C]||(x.content[C]={}),x.content[C][I]=N.content),x.files.push({path:_,relativePath:this.pathResolver.getRelativePath(_),namespace:C,language:I,eager:P.has(_),size:N.content?JSON.stringify(N.content).length:0})}}for(let[_,N]of W){let C=_.lastIndexOf("_"),I=_.slice(0,C),ee=_.slice(C+1);(!x.mapping[I]||!x.mapping[I][ee])&&(x.mapping[I]||(x.mapping[I]={}),x.mapping[I][ee]=N.importPath,x.content[I]||(x.content[I]={}),x.content[I][ee]=N.content,x.files.push({path:N.absolutePath,relativePath:this.pathResolver.getRelativePath(N.absolutePath),namespace:I,language:ee,eager:x.eagerNamespaces.has(I),size:N.content?JSON.stringify(N.content).length:0}))}let ie=Q.size>0?[...Q].sort():[this.options.fallbackLanguage];return{mapping:x.mapping,content:x.content,eagerNamespaces:[...x.eagerNamespaces].sort(),allNamespaces:[...x.allNamespaces].sort(),supportedLanguages:ie,fallbackLanguage:this.options.fallbackLanguage,files:x.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,i=r.match(/^([^_]+)_([^.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,a]=i,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let u="./"+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(p){return this.logger.debug(`Error parsing JSON from ${e}: ${p.message}`),null}return{namespace:o,language:a,importPath:u,absolutePath:e,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}};B();var Rt={isEmpty:n=>!n.mapping||Object.keys(n.mapping).length===0,generateModule:(n,e,t="i18n",s=!1)=>{let{mapping:r,eagerNamespaces:o,supportedLanguages:a,fallbackLanguage:i,stats:l,content:u={},files:c=[]}=n,p=s?Object.keys(u):o,g={};for(let y of p)u[y]&&(g[y]=u[y]);let d=[...new Set([...o,...Object.keys(u)])],h={mapping:r,languages:a,eager:s?d:o,fallback:i,content:g,storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:l?.totalFiles||0,totalNamespaces:l?.totalNamespaces||0,totalLanguages:l?.totalLanguages||0,eagerNamespaces:l?.eagerNamespaces||0,generatedAt:new Date().toISOString()},debug:e},D=[];if(!s)for(let[y,k]of Object.entries(r)){if(o.includes(y))continue;let R=[];for(let b of Object.keys(k))R.push(` '${b}': () => import('virtual:i18n-lazy-${y}-${b}')`);R.length>0&&D.push(` '${y}': {
319
- ${R.join(`,
315
+ `)},generateManifest:n=>({totalVars:Object.keys(n?.env||{}).length,mode:n?.mode||"development",variables:Object.keys(n?.env||{}),timestamp:Date.now()}),logStats:(n,e,t)=>{let s=Object.keys(n.env).length;t&&t.info(`${e} Env: ${s} VITE_* variables`)}},Qe=class{constructor(e,t={}){this.pathResolver=e,this.options=t,this.mode=t.mode||"development",this.appRoot=null}async discoverEnv(){try{let e=this.pathResolver.getAppRoot();if(!e)throw new Error("App root not available in EnvDiscovery");let s={...Gs(this.mode,e,"VITE_")};return this.mode==="production"&&(delete s.VITE_USE_FIREBASE_EMULATOR,delete s.VITE_FIREBASE_EMULATOR_HOST,delete s.VITE_FIREBASE_AUTH_EMULATOR_HOST,delete s.VITE_FIREBASE_FIRESTORE_EMULATOR_HOST,delete s.VITE_FIREBASE_FUNCTIONS_EMULATOR_PORT),s.MODE=this.mode,s.DEV=this.mode==="development",s.PROD=this.mode==="production",s.SSR=!1,{env:s,mode:this.mode,source:`${e}/.env`,errors:[]}}catch(e){return{env:{},mode:this.mode,source:"error",errors:[e.message]}}}};function Ft(n={}){return ce({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:j.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:Tt,manifestFileName:ie.manifests.env,configKey:"env",createDiscovery:(e,t)=>new Qe(e,{...t,mode:n.mode||t.mode||"development"})})({...n,disableHmr:!0})}U();U();function et(n){let e=new Set(Object.keys(Oe)),t=new Set(["latin"]);for(let o of n||[]){let a=ht[o];if(a)for(let i of a)t.add(i)}let s=[],r=new Set;for(let o of e){let a=Oe[o];for(let i of t)for(let l of a){let c=`@fontsource/${o}/${i}-${l}.css`,u=`${o}-${i}-${l}-normal`;s.push(c),r.add(u)}}return{imports:s,stems:r,subsets:t,fontStems:e}}function Ct(n){return n.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}U();L();U();function Bs(n){if(!n)return[];let e=E.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",n);if(!s)return[];let r=e.getDirname(e.getDirname(s)),o;try{o=e.readdirSync(r)}catch{return[]}for(let a of o)try{let i=e.resolvePath(`${a}/package.json`,r),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[c,u]of Object.entries(l.peerDependenciesMeta))u?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function Vs(n){if(!n)return[];let e=E.getInstance();try{let t=e.resolvePath("package.json",n),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[o,a]of Object.entries(s.peerDependenciesMeta))a?.optional&&r.add(o);if(s.optionalDependencies)for(let o of Object.keys(s.optionalDependencies))r.add(o);return Array.from(r)}catch{return[]}}function Hs(n){let e=xe.optionalFeatures||[],t=Bs(n),s=Vs(n);return[...new Set([...e,...t,...s])]}function Js(n){let e=E.getInstance();try{let t=e.resolvePath("package.json",n),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function qs(n,e,t){if(t.resolvePackage(n,e||void 0))return!0;let s=n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0],r=e;for(let o=0;o<10;o++){let a=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(a))return!0;let i=t.getDirname(r);if(i===r)break;r=i}return!1}function Ue(n){let e=Hs(n),t=[],s=[],r=E.getInstance(),o=Js(n);for(let a of e)a.startsWith("@donotdev/")?o.has(a)?s.push(a):t.push(a):o.has(a)&&qs(a,n,r)?s.push(a):t.push(a);return{missing:t,installed:s}}var Se=class n extends re{static LANGUAGE_FLAG_OVERRIDES={en:"gb","en-ca":"ca","es-ar":"ar","fr-be":"be",ar:"sa","ar-ma":"ma","ar-dz":"dz","ar-tn":"tn","ar-ly":"ly","ar-mr":"mr",hi:"in",sl:"si",uk:"ua",ga:"ie",gd:"gb-sct",br:"bzh",co:"fr-cor",am:"et",bn:"bd",gu:"in",kn:"in",ml:"in",mr:"in",ne:"np",pa:"pk",ta:"in",te:"in",ur:"pk",fa:"ir",kk:"kz",ky:"kg",tg:"tj",my:"mm",km:"kh",lo:"la",ka:"ge",hy:"am",be:"by",bs:"ba",sq:"al",ms:"my"};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=ze("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(x=>{let F=x.endsWith(".json")?x:`${x}/*_*.json`;return this.pathResolver.resolveAppPath(F)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let c=r.framework?.eager||[],u=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${u.join(", ")}`),c.length===0&&u.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),f=(x,F)=>{let M=this.pathResolver.normalizePath(x),I=this.pathResolver.normalizePath(F);return M.startsWith(I)?M.slice(I.length+1):M},m=a.map(x=>f(x,t)),P=[...i,...l].map(x=>f(x,t)),w=c.map(x=>f(x,s)),_=u.map(x=>f(x,s)),T={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},S=await this.pathResolver._globWithNormalization(m,T),D=await this.pathResolver._globWithNormalization(P,T),N={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(x=>x!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(N.ignore)}`);let v=await this.pathResolver._globWithNormalization(w,N),b=await this.pathResolver._globWithNormalization(_,N);this.logger.debug(`Found ${S.length} eager, ${D.length} lazy, ${v.length} framework eager, ${b.length} framework lazy files`),v.length>0?this.logger.debug(`Framework eager files (first 3): ${v.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),b.length>0?this.logger.debug(`Framework lazy files (first 3): ${b.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${u.join(", ")}`);let k=[...new Set([...S,...D,...v,...b])],O=new Set([...S,...v]),R={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:V}=Ue(t),z=new Set(V.filter(x=>x.startsWith("@donotdev/")).map(x=>x.replace("@donotdev/","")));z.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...z].join(", ")}] (packages not installed)`);let ae=new Map,de=[...v,...b];for(let x of de){let F=this._processTranslationFile(x,v.includes(x),t);if(F){if(z.has(F.namespace))continue;let M=`${F.namespace}_${F.language}`;ae.set(M,F),R.allNamespaces.add(F.namespace),R.supportedLanguages.add(F.language),v.includes(x)&&R.eagerNamespaces.add(F.namespace)}}let pe=new Set;for(let x of k){if(de.includes(x))continue;let F=this._processTranslationFile(x,O.has(x),t);if(F){let{namespace:M,language:I,importPath:X,content:De}=F,we=`${F.namespace}_${F.language}`;if(ae.has(we)){let Pe=ae.get(we);F.content=this._mergeTranslations(Pe.content,De)}R.allNamespaces.add(M),R.supportedLanguages.add(I),pe.add(I),O.has(x)&&R.eagerNamespaces.add(M),R.mapping[M]||(R.mapping[M]={}),R.mapping[M][I]=X,F.content&&(R.content[M]||(R.content[M]={}),R.content[M][I]=F.content),R.files.push({path:x,relativePath:this.pathResolver.getRelativePath(x),namespace:M,language:I,eager:O.has(x),size:F.content?JSON.stringify(F.content).length:0})}}for(let[x,F]of ae){let M=x.lastIndexOf("_"),I=x.slice(0,M),X=x.slice(M+1);pe.size>0&&!pe.has(X)||(!R.mapping[I]||!R.mapping[I][X])&&(R.mapping[I]||(R.mapping[I]={}),R.mapping[I][X]=F.importPath,R.content[I]||(R.content[I]={}),R.content[I][X]=F.content,R.files.push({path:F.absolutePath,relativePath:this.pathResolver.getRelativePath(F.absolutePath),namespace:I,language:X,eager:R.eagerNamespaces.has(I),size:F.content?JSON.stringify(F.content).length:0}))}let ge=pe.size>0?[...pe].sort():[this.options.fallbackLanguage],be=[...new Set(ge.map(x=>n.LANGUAGE_FLAG_OVERRIDES[x]||x))];return{mapping:R.mapping,content:R.content,eagerNamespaces:[...R.eagerNamespaces].sort(),allNamespaces:[...R.allNamespaces].sort(),supportedLanguages:ge,fallbackLanguage:this.options.fallbackLanguage,flagCodes:be,files:R.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[n.LANGUAGE_FLAG_OVERRIDES[this.options.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,i=r.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,a]=i,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),u;try{if(u=this.pathResolver.readSync(e,{format:"json"}),!u)return this.logger.debug(`Could not read file: ${e}`),null}catch(p){return this.logger.debug(`Error parsing JSON from ${e}: ${p.message}`),null}return{namespace:o,language:a,importPath:c,absolutePath:e,content:u}}_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}};L();var Ys=3,tt="<!-- DNDEV_FONT_PRELOADS -->",st=Object.keys(Oe);function It(n={}){let{debug:e=!1}=n,t=C("font-preload",e,!1),s,r={},o=new Set,a=[];return{name:"vite-font-preload-plugin",enforce:"post",configResolved(i){r={root:i.root,base:i.base&&i.base!=="/"?i.base.replace(/\/$/,""):"",outDir:i.build?.outDir??"dist"};try{s=E.getInstance()}catch(l){t.debug(`Font preload: PathResolver not ready: ${l?.message}`)}},async buildStart(){if(!(!s||!s.getAppRoot()))try{let l=["en"];try{let p=await new Se(s,{fallbackLanguage:"en"}).discoverTranslations();p?.supportedLanguages?.length&&(l=p.supportedLanguages)}catch(u){t.debug(`Font preload: i18n discovery failed, using 'en': ${u?.message}`)}let c=et(l);o=c.stems,t.debug(`Font filter: ${c.fontStems.size} font(s), ${c.subsets.size} subset(s), ${o.size} allowed stem(s)`)}catch(l){t.debug(`Font preload: discovery failed, using defaults: ${l?.message}`),o=et(["en"]).stems}},generateBundle(i,l){if(o.size===0)return;let c=0,u=0;for(let f of Object.keys(l)){if(l[f].type!=="asset")continue;let d=f.toLowerCase();f.endsWith(".woff")?st.some(P=>d.includes(P))&&(delete l[f],c++):f.endsWith(".woff2")&&st.some(w=>d.includes(w))&&(Array.from(o).some(_=>d.includes(_))||(delete l[f],u++))}t.debug(`Font filter: deleted ${c} .woff + ${u} .woff2 from bundle`);for(let[f,m]of Object.entries(l)){if(m.type!=="asset"||!f.endsWith(".css")||typeof m.source!="string")continue;let d=m.source,P=d.replace(/@font-face\s*\{[\s\S]*?\}/g,w=>st.some(S=>w.includes(S))?Array.from(o).some(S=>w.includes(S))?Ct(w):"":w);P!==d&&(m.source=P)}let p=r.base||"",g=[];for(let[f,m]of Object.entries(l)){if(m.type!=="asset"||!f.endsWith(".woff2"))continue;let d=f.toLowerCase();if(Array.from(o).some(P=>d.includes(P))){let P=p?`${p}/${f}`:`/${f}`;g.push(P)}}a=g.slice(0,Ys)},writeBundle(){if(!a.length)return;let i=s||E.getInstance(),l=r.root||process.cwd(),c=r.outDir||"dist",u=i.resolvePath(`${c}/index.html`,l);try{if(!i.pathExists(u)){t.debug(`Font preload: index.html not found at ${u}`);return}let p=i.readSync(u,{format:"text"}),g=a.map(f=>`<link rel="preload" as="font" href="${f}" type="font/woff2" crossorigin="anonymous" />`).join(`
316
+ `);if(p.includes(tt))p=p.replace(tt,`${tt}
317
+ ${g}`);else{let f=p.indexOf("<!-- Fonts:"),m=f!==-1?p.indexOf("-->",f)+3:p.indexOf("</head>");m!==-1&&(p=p.slice(0,m)+`
318
+ ${g}`+p.slice(m))}i.writeSync(u,p,{overwrite:!0}),t.debug(`Font preload: injected ${a.length} link(s)`)}catch(p){t.debug(`Font preload: write failed: ${p?.message}`)}}}}U();L();var Mt={isEmpty:n=>!n.mapping||Object.keys(n.mapping).length===0,generateModule:(n,e,t="i18n",s=!1)=>{let{mapping:r,eagerNamespaces:o,supportedLanguages:a,fallbackLanguage:i,stats:l,content:c={},files:u=[]}=n,p=s?Object.keys(c):o,g={};for(let w of p)c[w]&&(g[w]=c[w]);let f=[...new Set([...o,...Object.keys(c)])],m={mapping:r,languages:a,eager:s?f:o,fallback:i,content:g,storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:l?.totalFiles||0,totalNamespaces:l?.totalNamespaces||0,totalLanguages:l?.totalLanguages||0,eagerNamespaces:l?.eagerNamespaces||0,generatedAt:new Date().toISOString()},debug:e},d=[];if(!s)for(let[w,_]of Object.entries(r)){if(o.includes(w))continue;let T=[];for(let S of Object.keys(_))T.push(` '${S}': () => import('virtual:i18n-lazy-${w}-${S}')`);T.length>0&&d.push(` '${w}': {
319
+ ${T.join(`,
320
320
  `)}
321
- }`)}let O=D.length>0?`{
322
- ${D.join(`,
321
+ }`)}let P=d.length>0?`{
322
+ ${d.join(`,
323
323
  `)}
324
- }`:"{}";return`// ${M.i18n} - Generated by @donotdev/config
324
+ }`:"{}";return`// ${j.i18n} - Generated by @donotdev/config
325
325
  // Generated at: ${new Date().toISOString()}
326
326
 
327
327
  // ===== STATIC EXPORTS =====
328
- export const I18N_CONFIG = ${JSON.stringify(h,null,2)};
328
+ export const I18N_CONFIG = ${JSON.stringify(m,null,2)};
329
329
  export const LANGUAGES = ${JSON.stringify(a,null,2)};
330
330
  export const FALLBACK_LANGUAGE = '${i}';
331
331
  export const EAGER_NAMESPACES = ${JSON.stringify(o,null,2)};
@@ -334,7 +334,7 @@ const i18nPluginConfig = I18N_CONFIG;
334
334
 
335
335
  // ===== LAZY LOADERS =====
336
336
  // Static import() calls \u2014 Vite bundles each JSON as a separate async chunk
337
- const _lazyLoaders = ${O};
337
+ const _lazyLoaders = ${P};
338
338
 
339
339
  // ============================================================================
340
340
  // INITIALIZE DnDev CONFIG FOUNDATION
@@ -352,7 +352,7 @@ if (typeof globalThis !== 'undefined') {
352
352
  }
353
353
 
354
354
  // Add i18n plugin configuration + lazy loaders (functions, not serializable)
355
- globalThis._DNDEV_CONFIG_.${V[t]} = {
355
+ globalThis._DNDEV_CONFIG_.${H[t]} = {
356
356
  ...i18nPluginConfig,
357
357
  loaders: _lazyLoaders,
358
358
  };
@@ -446,7 +446,7 @@ export default {
446
446
  getInlineContent,
447
447
  };
448
448
 
449
- `},generateEmpty:(n,e,t,s="i18n")=>{let r=t.fallbackLanguage||"en",o={mapping:{},languages:[r],eager:[],fallback:r,content:{},storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:0,totalNamespaces:0,totalLanguages:1,eagerNamespaces:0,generatedAt:new Date().toISOString()},debug:e};return`// ${M.i18n} - Empty i18n configuration
449
+ `},generateEmpty:(n,e,t,s="i18n")=>{let r=t.fallbackLanguage||"en",o={mapping:{},languages:[r],eager:[],fallback:r,content:{},storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:0,totalNamespaces:0,totalLanguages:1,eagerNamespaces:0,generatedAt:new Date().toISOString()},debug:e};return`// ${j.i18n} - Empty i18n configuration
450
450
  // No translation files found - using fallback configuration
451
451
  // Generated at: ${new Date().toISOString()}
452
452
 
@@ -464,7 +464,7 @@ if (typeof globalThis !== 'undefined') {
464
464
  };
465
465
  }
466
466
 
467
- globalThis._DNDEV_CONFIG_.${V[s]} = i18nPluginConfig;
467
+ globalThis._DNDEV_CONFIG_.${H[s]} = i18nPluginConfig;
468
468
  }
469
469
 
470
470
  // Placeholder functions
@@ -566,7 +566,9 @@ export default {
566
566
  files: translationFiles,
567
567
  manifest: i18nManifest,
568
568
  };
569
- `},generateManifest:n=>({namespaces:n.stats?.totalNamespaces||0,languages:n.stats?.totalLanguages||0,fallbackLanguage:n.fallbackLanguage,eagerNamespaces:n.stats?.eagerNamespaces||0,platform:"vite",timestamp:Date.now()}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.supportedLanguages||[],r=Object.keys(n.mapping||{}).filter(o=>o!=="default").length||0;t&&t.info(`${e} I18n: ${s.length} languages, ${r} namespaces`)}},Rs=[n=>n.endsWith(".json")&&n.includes("locale"),n=>/[a-z]+_[a-z]{2}\.json$/i.test(n),n=>n.includes("/locales/")&&n.endsWith(".json")];function $t(n={}){let e=!1,t=new Map,s=$.getInstance(),r={...xe.discovery,fallbackLanguage:n.fallbackLanguage||"en",...n},o=new $e(s,r);function a(c){t.clear();let{content:p,eagerNamespaces:g}=c;for(let[d,h]of Object.entries(p||{}))if(!g.includes(d))for(let[D,O]of Object.entries(h))t.set(`virtual:i18n-lazy-${d}-${D}`,O)}let i={...Rt,generateModule:(c,p,g)=>(e||a(c),Rt.generateModule(c,p,g,e))};return[ue({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:M.i18n,DiscoveryClass:$e,discoveryMethod:"discoverTranslations",filePatterns:Rs,templates:i,defaultInspectionPath:j.vite.i18nInspection,manifestFileName:j.manifests.i18n,configKey:"i18n",discoveryOptions:r})({...n,hmrSmartDetection:!1}),{name:"dndev-i18n-lazy-loader",enforce:"pre",configResolved(c){e=c.command==="serve"},async buildStart(){if(e)return;let c=()=>{let d=s.getAppRoot(),h=s.getRepoRoot();return d&&d!==h},p=0;for(;!c()&&p<100;)await new Promise(d=>setTimeout(d,10)),p++;if(!c())return;let g=await o.discoverTranslations();a(g)},resolveId(c){if(!e&&c.startsWith("virtual:i18n-lazy-"))return"\0"+c},load(c){if(!e&&c.startsWith("\0virtual:i18n-lazy-")){let p=c.slice(1),g=t.get(p);return`export default ${JSON.stringify(g||{})};`}}}]}B();B();L();function $s(n){if(!n)return[];let e=$.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",n);if(!s)return[];let r=e.getDirname(e.getDirname(s)),o;try{o=e.readdirSync(r)}catch{return[]}for(let a of o)try{let i=e.resolvePath(`${a}/package.json`,r),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[u,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(u)}catch{}}catch{}return Array.from(t)}function _s(n){if(!n)return[];let e=$.getInstance();try{let t=e.resolvePath("package.json",n),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[o,a]of Object.entries(s.peerDependenciesMeta))a?.optional&&r.add(o);if(s.optionalDependencies)for(let o of Object.keys(s.optionalDependencies))r.add(o);return Array.from(r)}catch{return[]}}function ks(n){let e=ye.optionalFeatures||[],t=$s(n),s=_s(n);return[...new Set([...e,...t,...s])]}function Ds(n){let e=$.getInstance();try{let t=e.resolvePath("package.json",n),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function Ns(n,e,t){if(t.resolvePackage(n,e||void 0))return!0;let s=n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0],r=e;for(let o=0;o<10;o++){let a=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(a))return!0;let i=t.getDirname(r);if(i===r)break;r=i}return!1}function _t(n){let e=ks(n),t=[],s=[],r=$.getInstance(),o=Ds(n);for(let a of e)a.startsWith("@donotdev/")?o.has(a)?s.push(a):t.push(a):o.has(a)&&Ns(a,n,r)?s.push(a):t.push(a);return{missing:t,installed:s}}function kt(n,e){return e.some(t=>n===t||n.startsWith(t+"/"))}function Dt(n={}){let e=[],t="",s="";return{name:"dndev-optional-dep-resolver",enforce:"pre",config(r){let o={name:"dndev-optional-dep-esbuild",setup(i){i.onResolve({filter:/^[@a-z]/,namespace:"file"},l=>kt(l.path,e)?{path:s,external:!1}:null)}};return{optimizeDeps:{esbuildOptions:{plugins:[...r.optimizeDeps?.esbuildOptions?.plugins||[],o]}}}},configResolved(r){let o=$.getInstance(),a=o.getAppRoot();if(e=_t(a).missing,t=o.getEmptyModulePath(),s=o.getEmptyCjsModulePath(),e.length>0){let l=r.optimizeDeps?.exclude||[];r.optimizeDeps.exclude=[...l,...e]}n.debug&&e.length>0},resolveId(r){return kt(r,e)?{id:t,syntheticNamedExports:!0}:null}}}function Ze(n){return!n||typeof n!="string"?null:n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0]}function As(n){return!n||typeof n!="string"?!1:!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("\\")&&!n.startsWith("\0")}function Os(n,e){if(!n||!e||!e.getRepoRoot())return!1;let s=n;n.startsWith("@fs/")&&(s=n.slice(4));let r=e.resolveRepoPath("packages"),o=e.normalizePath(s);return r&&o.startsWith(r)}function Ts(n,e){if(!n||!e)return null;let t=Ze(n);if(!t)return null;let s=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(s)?e.resolveAppPath(`node_modules/${n}`):null}function Nt(n,e,t){return!As(n)||!Os(e,t)?null:Ts(n,t)}B();function At(n={}){let{debug:e=!1,verbose:t=!0}=n,s=F("peer-dependency-resolver",e,t);return{name:"dndev-peer-dependency-resolver",enforce:"pre",configResolved(r){let o=$.getInstance(),a=o.getAppRoot();if(!a){s.warn("App root not set, peer dependency resolution may fail");return}this.pathResolver=o,this.appRoot=a},resolveId(r,o){if(!o||!this.appRoot||!this.pathResolver)return null;if(Nt(r,o,this.pathResolver)){let i=Ze(r),l=this.pathResolver.resolveAppPath(`node_modules/${r}`),u=this.pathResolver.resolveAppPath(`node_modules/${i}`);return this.pathResolver.pathExists(u)?r===i?((e||t)&&s.debug(`[PeerDeps] Resolving bare import "${r}" from app's node_modules: ${u}`),u):((e||t)&&s.debug(`[PeerDeps] Resolving subpath "${r}" from app's node_modules: ${l}`),l):(e&&s.debug(`[PeerDeps] Package directory not found: ${u}, skipping resolution`),null)}return null}}}import{VitePWA as Fs}from"vite-plugin-pwa";L();var Ce=class extends oe{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),i=a.filter(g=>g.type==="manifest"||g.type==="service-worker");o.push(...i);let l=a.filter(g=>g.type==="icon"),u=new Set(o.filter(g=>g.type==="icon").map(g=>g.path)),c=l.filter(g=>!u.has(g.path));o.push(...c);let p=this._generatePWAManifest(o);return{assets:o,manifest:p,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
569
+ `},generateManifest:n=>({namespaces:n.stats?.totalNamespaces||0,languages:n.stats?.totalLanguages||0,fallbackLanguage:n.fallbackLanguage,eagerNamespaces:n.stats?.eagerNamespaces||0,platform:"vite",timestamp:Date.now()}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.supportedLanguages||[],r=Object.keys(n.mapping||{}).filter(o=>o!=="default").length||0;t&&t.info(`${e} I18n: ${s.length} languages, ${r} namespaces`)}},Ks=[n=>n.endsWith(".json")&&n.includes("locale"),n=>/[a-z]+_[a-z]{2}\.json$/i.test(n),n=>n.includes("/locales/")&&n.endsWith(".json")];function jt(n={}){let e=!1,t=new Map,s=E.getInstance(),r={...$e.discovery,fallbackLanguage:n.fallbackLanguage||"en",...n},o=new Se(s,r);function a(p){t.clear();let{content:g,eagerNamespaces:f}=p;for(let[m,d]of Object.entries(g||{}))if(!f.includes(m))for(let[P,w]of Object.entries(d))t.set(`virtual:i18n-lazy-${m}-${P}`,w)}let i={...Mt,generateModule:(p,g,f)=>(e||a(p),Mt.generateModule(p,g,f,e))};return[ce({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:j.i18n,DiscoveryClass:Se,discoveryMethod:"discoverTranslations",filePatterns:Ks,templates:i,manifestFileName:ie.manifests.i18n,configKey:"i18n",discoveryOptions:r})({...n,hmrSmartDetection:!1}),{name:"dndev-i18n-lazy-loader",enforce:"pre",configResolved(p){e=p.command==="serve"},async buildStart(){if(e)return;let p=()=>{let m=s.getAppRoot(),d=s.getRepoRoot();return m&&m!==d},g=0;for(;!p()&&g<100;)await new Promise(m=>setTimeout(m,10)),g++;if(!p())return;let f=await o.discoverTranslations();a(f)},resolveId(p){if(!e&&p.startsWith("virtual:i18n-lazy-"))return"\0"+p},load(p){if(!e&&p.startsWith("\0virtual:i18n-lazy-")){let g=p.slice(1),f=t.get(g);return`export default ${JSON.stringify(f||{})};`}}},{name:"dndev-i18n-flag-filter",enforce:"pre",async buildStart(){let p=()=>{let d=s.getAppRoot(),P=s.getRepoRoot();return d&&d!==P},g=0;for(;!p()&&g<100;)await new Promise(d=>setTimeout(d,10)),g++;if(!p())return;let m=(await o.discoverTranslations()).flagCodes||[];this._allowedFlags=new Set(m.map(d=>d.toUpperCase()))},resolveId(p,g){if(!g||!p.includes("flag"))return;let f=p.match(/flag([A-Z][A-Z0-9_-]*)\.(tsx|js)$/i);if(!f)return;let m=f[1].toUpperCase();if(m!=="BASE"&&!this._allowedFlags?.has(m))return"\0empty-flag"},load(p){if(p==="\0empty-flag")return"export default () => null;"}}]}L();function zt(n,e){return e.some(t=>n===t||n.startsWith(t+"/"))}function Lt(n={}){let e=[],t="",s="";return{name:"dndev-optional-dep-resolver",enforce:"pre",config(r){let o={name:"dndev-optional-dep-esbuild",setup(i){i.onResolve({filter:/^[@a-z]/,namespace:"file"},l=>zt(l.path,e)?{path:s,external:!1}:null)}};return{optimizeDeps:{esbuildOptions:{plugins:[...r.optimizeDeps?.esbuildOptions?.plugins||[],o]}}}},configResolved(r){let o=E.getInstance(),a=o.getAppRoot();if(e=Ue(a).missing,t=o.getEmptyModulePath(),s=o.getEmptyCjsModulePath(),e.length>0){let l=r.optimizeDeps?.exclude||[];r.optimizeDeps.exclude=[...l,...e]}n.debug&&e.length>0},resolveId(r){return zt(r,e)?{id:t,syntheticNamedExports:!0}:null}}}function rt(n){return!n||typeof n!="string"?null:n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0]}function Zs(n){return!n||typeof n!="string"?!1:!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("\\")&&!n.startsWith("\0")}function Xs(n,e){if(!n||!e||!e.getRepoRoot())return!1;let s=n;n.startsWith("@fs/")&&(s=n.slice(4));let r=e.resolveRepoPath("packages"),o=e.normalizePath(s);return r&&o.startsWith(r)}function Qs(n,e){if(!n||!e)return null;let t=rt(n);if(!t)return null;let s=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(s)?e.resolveAppPath(`node_modules/${n}`):null}function Ut(n,e,t){return!Zs(n)||!Xs(e,t)?null:Qs(n,t)}L();function Wt(n={}){let{debug:e=!1,verbose:t=!0}=n,s=C("peer-dependency-resolver",e,t);return{name:"dndev-peer-dependency-resolver",enforce:"pre",configResolved(r){let o=E.getInstance(),a=o.getAppRoot();if(!a){s.warn("App root not set, peer dependency resolution may fail");return}this.pathResolver=o,this.appRoot=a},resolveId(r,o){if(!o||!this.appRoot||!this.pathResolver)return null;if(Ut(r,o,this.pathResolver)){let i=rt(r),l=this.pathResolver.resolveAppPath(`node_modules/${r}`),c=this.pathResolver.resolveAppPath(`node_modules/${i}`);return this.pathResolver.pathExists(c)?r===i?((e||t)&&s.debug(`[PeerDeps] Resolving bare import "${r}" from app's node_modules: ${c}`),c):((e||t)&&s.debug(`[PeerDeps] Resolving subpath "${r}" from app's node_modules: ${l}`),l):(e&&s.debug(`[PeerDeps] Package directory not found: ${c}, skipping resolution`),null)}return null}}}L();import{createServer as er}from"node:http";import{readFile as Vt,writeFile as tr,mkdir as sr,stat as rr}from"node:fs/promises";import{join as Ee,extname as ot,dirname as or}from"node:path";L();function Gt(n,e={}){let{blogPath:t="/blog"}=e,s=E.getInstance(),r=e.appRoot||s.getAppRoot();if(!n.some(a=>{let i=a.path||a;return typeof i=="string"&&i.startsWith(t+"/")&&i.includes(":")}))return[];try{let a=s.resolvePath("src/content/blog",r);if(!s.pathExists(a))return[];let i=s.readdirSync(a).filter(c=>c.endsWith("_en.md"));if(i.length===0)return[];let l=i.map(c=>c.replace(/_en\.md$/,""));return[t,...l.map(c=>`${t}/${c}`)]}catch{return[]}}function ye(n={}){let{logger:e}=n,t=E.getInstance(),s=n.appRoot||t.getAppRoot();try{let r=t.resolvePath("public/route-manifest.json",s),o=t.readSync(r,{format:"json"});if(!o)return e?.error?.(`Route manifest not found at ${r}. Routes will be empty.`),{routes:[],errors:[`Route manifest missing: ${r}`],source:"fallback"};let a=o.routes||[];return{routes:a,errors:[],source:o.source||"generated",totalFiles:a.length}}catch(r){return e?.warn?.(`Error parsing route manifest: ${r.message}, falling back to empty routes`),{routes:[],errors:[r.message],source:"fallback"}}}function Bt(n){return n.filter(e=>{let t=e.path||e;return!(e.auth&&e.auth.required||typeof t=="string"&&t.includes(":"))}).map(e=>e.path||e)}async function nr(){try{return await import("puppeteer")}catch{try{return await import("puppeteer-core")}catch{throw new Error(`Prerendering requires puppeteer or puppeteer-core.
570
+ Install: bun add -d puppeteer
571
+ Or with puppeteer-core (uses system Chrome): bun add -d puppeteer-core`)}}}var ar={".html":"text/html",".js":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".xml":"application/xml",".txt":"text/plain",".webmanifest":"application/manifest+json"},We=class{constructor(e){this.routes=e.routes||[],this.outDir=e.outDir,this.base=e.base||"/",this.appRoot=e.appRoot,this.waitForSelector=e.waitForSelector||"#root > *",this.timeout=e.timeout||3e4,this.concurrency=e.concurrency||4,this.debug=e.debug||!1,this.logger=e.logger}async run(){let e=await this.expandRoutes();if(e.length===0)return this.logger.warn("No routes to prerender after expansion."),[];let{server:t,port:s}=await this.startStaticServer(),o=await(await nr()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage","--disable-gpu"]}),a=[];try{let i=this.chunkArray(e,this.concurrency);for(let l of i){let c=await Promise.all(l.map(u=>this.renderRoute(o,s,u)));a.push(...c)}}finally{await o.close(),t.close()}return a}async expandRoutes(){let{routes:e,errors:t}=ye({appRoot:this.appRoot,logger:this.logger});if(e.length===0)return t.length>0&&this.logger.warn("Route manifest unavailable. Using explicit routes only."),this.routes.filter(r=>!r.includes("*"));let s=new Set;for(let r of this.routes)if(r.includes("*")){let o=r.replace(/\/?\*.*$/,"");for(let a of e){let i=a.path||a;i.startsWith(o)&&!this.isAuthProtected(a)&&s.add(i)}if(this.debug){let a=[...s].filter(i=>i.startsWith(o));this.logger.debug(` Pattern "${r}" matched ${a.length} route(s)`)}}else{let o=e.find(a=>(a.path||a)===r);o&&this.isAuthProtected(o)?this.logger.warn(` Skipping auth-protected route: ${r}`):o?s.add(r):(s.add(r),this.debug&&this.logger.debug(` Route "${r}" not in manifest, including anyway`))}return[...s]}isAuthProtected(e){return typeof e=="string"?!1:e.auth?.required===!0}startStaticServer(){return new Promise((e,t)=>{let s=er(async(r,o)=>{let a=new URL(r.url,"http://localhost"),i=Ee(this.outDir,a.pathname);try{(await rr(i)).isDirectory()&&(i=Ee(i,"index.html"))}catch{if(ot(a.pathname)){o.writeHead(404),o.end("Not Found");return}i=Ee(this.outDir,"index.html")}try{let l=await Vt(i),c=ot(i),u=ar[c]||"application/octet-stream";o.writeHead(200,{"Content-Type":u}),o.end(l)}catch{if(!ot(a.pathname))try{let c=await Vt(Ee(this.outDir,"index.html"));o.writeHead(200,{"Content-Type":"text/html"}),o.end(c);return}catch{}o.writeHead(404),o.end("Not Found")}});s.listen(0,"127.0.0.1",()=>{let r=s.address().port;this.debug&&this.logger.debug(` Static server on http://127.0.0.1:${r}`),e({server:s,port:r})}),s.on("error",t)})}async renderRoute(e,t,s){let r=await e.newPage(),o=[];r.on("pageerror",a=>o.push(a.message)),r.on("console",a=>{a.type()==="error"&&o.push(a.text())});try{let a=`http://127.0.0.1:${t}${this.base==="/"?"":this.base}${s}`;this.debug&&this.logger.debug(` Rendering: ${s}`),await r.goto(a,{waitUntil:"networkidle2",timeout:this.timeout}),await r.waitForSelector(this.waitForSelector,{timeout:this.timeout}),await new Promise(l=>setTimeout(l,200));let i=await r.content();return i=this.postProcessHtml(i),await this.writePrerenderedFile(s,i),this.debug&&this.logger.debug(` ${s}`),{route:s,ok:!0}}catch(a){let i=o.length>0?`${a.message} | Page errors: ${o.join("; ")}`:a.message;return{route:s,ok:!1,error:i}}finally{await r.close()}}postProcessHtml(e){return e=e.replace(/<div id="shell-loader"[^>]*>[\s\S]*?<\/div>\s*<\/div>\s*<\/div>/,'<div id="shell-loader" style="display:none"></div>'),e}async writePrerenderedFile(e,t){let s;if(e==="/")s=Ee(this.outDir,"index.html");else{let o=e.replace(/^\//,"").replace(/\/$/,"");s=Ee(this.outDir,o,"index.html")}let r=or(s);await sr(r,{recursive:!0}),await tr(s,t,"utf-8")}chunkArray(e,t){let s=[];for(let r=0;r<e.length;r+=t)s.push(e.slice(r,r+t));return s}};function Ht(n={}){let{routes:e="auto",debug:t,verbose:s,...r}=n;if(Array.isArray(e)&&e.length===0)return{name:"prerender-disabled"};let o=C("Prerender",t,s),a=E.getInstance(),i=null;return{name:"dndev-prerender",enforce:"post",configResolved(l){i={root:l.root,outDir:l.build?.outDir||"dist",base:l.base||"/"}},async closeBundle(){if(!i)return;let l=a.getAppRoot(),c=a.resolveAppPath(i.outDir),u=e;if(e==="auto"){let p=ye({appRoot:l,logger:o}),g=Bt(p.routes),f=Gt(p.routes,{appRoot:l});if(u=[...new Set([...g,...f])],u.length===0){o.warn("No public static routes found for prerendering.");return}o.debug(`Auto-discovered ${u.length} route(s) to prerender`)}try{let g=await new We({...r,routes:u,debug:t,outDir:c,base:i.base,appRoot:l,logger:o}).run(),f=g.filter(S=>S.ok).length,m=g.filter(S=>!S.ok),d=g.length,P=g.filter(S=>S.ok&&S.route.startsWith("/blog/")).length,w=f-P,_=[];w>0&&_.push(`${w} static`),P>0&&_.push(`${P} blog`);let T=_.length>0?` (${_.join(", ")})`:"";if(f>0&&o.info(`Prerendered: ${f}/${d} pages${T}`),m.length>0)for(let S of m)o.warn(` Failed: ${S.route} - ${S.error}`)}catch(p){o.warn(`Prerendering failed: ${p.message}`),o.warn("SPA will serve all routes via index.html fallback (no impact on functionality)."),t&&p.stack&&o.debug(p.stack)}}}}import{VitePWA as ir}from"vite-plugin-pwa";var Ge=class extends re{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),i=a.filter(g=>g.type==="manifest"||g.type==="service-worker");o.push(...i);let l=a.filter(g=>g.type==="icon"),c=new Set(o.filter(g=>g.type==="icon").map(g=>g.path)),u=l.filter(g=>!c.has(g.path));o.push(...u);let p=this._generatePWAManifest(o);return{assets:o,manifest:p,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
570
572
  // Generated at ${new Date().toISOString()}
571
573
 
572
574
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
@@ -600,22 +602,22 @@ self.addEventListener('message', (event) => {
600
602
  self.addEventListener('activate', (event) => {
601
603
  event.waitUntil(self.clients.claim());
602
604
  });
603
- `}_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:i={}}=s,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",u;typeof o=="function"?u="({ request }) => request.destination === 'document'":o instanceof RegExp?u=o.toString():u=JSON.stringify(o);let c=[];i.expiration&&c.push(`new ExpirationPlugin({
605
+ `}_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:i={}}=s,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",c;typeof o=="function"?c="({ request }) => request.destination === 'document'":o instanceof RegExp?c=o.toString():c=JSON.stringify(o);let u=[];i.expiration&&u.push(`new ExpirationPlugin({
604
606
  maxEntries: ${i.expiration.maxEntries||50},
605
607
  maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
606
- })`),i.cacheableResponse&&c.push(`new CacheableResponsePlugin({
608
+ })`),i.cacheableResponse&&u.push(`new CacheableResponsePlugin({
607
609
  statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
608
- })`),i.backgroundSync&&c.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
610
+ })`),i.backgroundSync&&u.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
609
611
  maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
610
612
  })`);let p="";return i.cacheName&&(p+=`
611
- cacheName: '${i.cacheName}',`),c.length>0&&(p+=`
613
+ cacheName: '${i.cacheName}',`),u.length>0&&(p+=`
612
614
  plugins: [
613
- ${c.join(`,
615
+ ${u.join(`,
614
616
  `)}
615
617
  ],`),i.networkTimeoutSeconds&&(p+=`
616
618
  networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${i.cacheName||"cache-"+r}
617
619
  registerRoute(
618
- ${u},
620
+ ${c},
619
621
  new ${l}({${p}
620
622
  })
621
623
  );`}).join(`
@@ -634,7 +636,7 @@ registerRoute(
634
636
  }),
635
637
  'POST'
636
638
  );
637
- `}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 i of a){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let u of l){let c=this.pathResolver.getRelativePath(u);if(c.startsWith(`${e}/static/`)){let p=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:p,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()}};B();function Ot(n={}){if(!n.enabled)return null;let e=n.app||{},t=[];if(e.name||t.push("name"),e.shortName||t.push("shortName"),e.description||t.push("description"),t.length>0){let c=F("PWA",n.debug,!0);c.warn(`\u26A0\uFE0F PWA is enabled but appConfig.app is missing required fields: ${t.join(", ")}`),c.warn(" Add these to your src/config/app.ts:"),c.warn(" export const appConfig: AppConfig = {"),c.warn(" app: {"),e.name||c.warn(' name: "Your App Name",'),e.shortName||c.warn(' shortName: "App",'),e.description||c.warn(' description: "Your app description",'),c.warn(" },"),c.warn(" // ... rest of config"),c.warn(" };"),c.warn("")}let s=$.getInstance(),r=qe.data;if(!r)try{let c=s.resolveAppPath(j.vite.assetInspection);s.pathExists(c)}catch{}let o=new Ce(s,{...n,assetData:r}),a=n.devEnabled===!0,i={registerType:n.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let c=n.app||{},g=(await o.discoverPWAAssets()).assets.filter(d=>d.type==="icon").map(d=>({src:`/${d.path}`,sizes:`${d.size.width}x${d.size.height}`,type:`image/${d.format}`,purpose:d.purpose}));return{name:c.name,short_name:c.shortName,description:c.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:g.length>0?g:[]}},workbox:{globPatterns:["**/*.{js,css,html,ico,png,svg,woff2}"],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:c})=>c.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:!0,skipWaiting:!0,clientsClaim:!0,maximumFileSizeToCacheInBytes:5*1024*1024,navigateFallback:"/index.html",navigateFallbackDenylist:[/^\/api\/.*/],manifestTransforms:[c=>{let p=c.find(g=>g.url==="/index.html"||g.url==="index.html");return p&&!c.find(g=>g.url==="/")&&c.push({url:"/",revision:p.revision}),{manifest:c,warnings:[]}}]},devOptions:{enabled:a,type:"module"}},u={...i,manifest:async()=>{let c=await i.manifest();if(n.manifest){if(typeof n.manifest=="function"){let p=await n.manifest();return{...c,...p}}return{...c,...n.manifest}}return c},workbox:{...i.workbox,...n.workbox||{},runtimeCaching:[...i.workbox.runtimeCaching,...n.workbox?.runtimeCaching||[]],manifestTransforms:[...i.workbox.manifestTransforms||[],...n.workbox?.manifestTransforms||[]]}};return Fs(u)}L();L();function Tt(n,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=n.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,u)=>`icon: '${u}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...n.matchAll(o)].forEach(l=>{let u=l[1],c=l[2];r=r.replace(new RegExp(`\\b${u}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var _e=null,Ft=null;function Is(n){let t=(n.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var Me=class extends oe{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(_e&&Ft===s)return this.logger.debug("Using cached route discovery results"),this.routes=_e.routes,this.errors=_e.errors,this.source=_e.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/"),_e={routes:this.routes,errors:this.errors,source:this.source},Ft=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,u=>this._analyzePageFile(u,t)),o=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(o,u=>this._analyzePageFile(u,t)),i=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=i.filter(u=>u.path==="home"||u.path==="/home"?(this.logger.debug(`Filtered reserved route: ${u.path} - Use root "/" instead (${u.file})`),!1):!0);let l=new Map;for(let u of this.routes){let c=u.path;if(l.has(c)){let p=l.get(c);throw new Error(`Route conflict: Multiple routes found for path '${c}'. Routes: ${p.file} and ${u.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}l.set(c,u)}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),i=Is(o),u=i===Ge.HOMEPAGE_COMPONENT?Ge.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:p,action:g,...d}=a||{};return{path:u,component:i,importPath:o,auth:a?.auth||!1,meta:{...c,...d,entity:c.entity,action:c.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=Tt(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(i=>`:${i}`).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,i=null;return o.length>1&&(a=o[o.length-2],s.includes("List")?i="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?i="form":(s.includes("Detail")||s.includes("View"))&&(i="detail")),{title:r,entity:a,action:i,file:e}}};var Cs={isEmpty:n=>!n.routes||n.routes.length===0,generateModule:(n,e,t="routes")=>{let s={totalRoutes:n.routes.length,authRequired:n.routes.filter(o=>o.auth&&o.auth.required).length,publicRoutes:n.routes.filter(o=>!o.auth||o.auth===!1).length,source:n.source,generatedAt:new Date().toISOString(),errors:n.errors.length},r=n.routes.map(o=>` {
639
+ `}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 i of a){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let c of l){let u=this.pathResolver.getRelativePath(c);if(u.startsWith(`${e}/static/`)){let p=`/_next/${u.replace(`${e}/static/`,"")}`;o.push({url:p,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()}};L();function Jt(n={}){if(!n.enabled)return null;let e=n.app||{},t=[];if(e.name||t.push("name"),e.shortName||t.push("shortName"),e.description||t.push("description"),t.length>0){let u=C("PWA",n.debug,!0);u.warn(`\u26A0\uFE0F PWA is enabled but appConfig.app is missing required fields: ${t.join(", ")}`),u.warn(" Add these to your src/config/app.ts:"),u.warn(" export const appConfig: AppConfig = {"),u.warn(" app: {"),e.name||u.warn(' name: "Your App Name",'),e.shortName||u.warn(' shortName: "App",'),e.description||u.warn(' description: "Your app description",'),u.warn(" },"),u.warn(" // ... rest of config"),u.warn(" };"),u.warn("")}let s=E.getInstance(),r=Nt.data,o=new Ge(s,{...n,assetData:r}),a=n.devEnabled===!0,i={registerType:n.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let u=n.app||{},g=(await o.discoverPWAAssets()).assets.filter(f=>f.type==="icon").map(f=>({src:`/${f.path}`,sizes:`${f.size.width}x${f.size.height}`,type:`image/${f.format}`,purpose:f.purpose}));return{name:u.name,short_name:u.shortName,description:u.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:g.length>0?g:[]}},workbox:{globPatterns:["**/*.{js,css,html,ico,png,svg,woff2}"],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:u})=>u.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:!0,skipWaiting:!0,clientsClaim:!0,maximumFileSizeToCacheInBytes:5*1024*1024,navigateFallback:"/index.html",navigateFallbackDenylist:[/^\/api\/.*/],manifestTransforms:[u=>{let p=u.find(g=>g.url==="/index.html"||g.url==="index.html");return p&&!u.find(g=>g.url==="/")&&u.push({url:"/",revision:p.revision}),{manifest:u,warnings:[]}}]},devOptions:{enabled:a,type:"module"}},c={...i,manifest:async()=>{let u=await i.manifest();if(n.manifest){if(typeof n.manifest=="function"){let p=await n.manifest();return{...u,...p}}return{...u,...n.manifest}}return u},workbox:{...i.workbox,...n.workbox||{},runtimeCaching:[...i.workbox.runtimeCaching,...n.workbox?.runtimeCaching||[]],manifestTransforms:[...i.workbox.manifestTransforms||[],...n.workbox?.manifestTransforms||[]]}};return ir(c)}U();U();function qt(n,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=n.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,c)=>`icon: '${c}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...n.matchAll(o)].forEach(l=>{let c=l[1],u=l[2];r=r.replace(new RegExp(`\\b${c}\\b`,"g"),`'${u}'`)}),Function(`return ${r}`)()}catch{return null}}var Fe=null,Yt=null;function lr(n){let t=(n.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var Be=class extends re{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(Fe&&Yt===s)return this.logger.debug("Using cached route discovery results"),this.routes=Fe.routes,this.errors=Fe.errors,this.source=Fe.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/"),Fe={routes:this.routes,errors:this.errors,source:this.source},Yt=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,c=>this._analyzePageFile(c,t)),o=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(o,c=>this._analyzePageFile(c,t)),i=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=i.filter(c=>c.path==="home"||c.path==="/home"?(this.logger.debug(`Filtered reserved route: ${c.path} - Use root "/" instead (${c.file})`),!1):!0);let l=new Map;for(let c of this.routes){let u=c.path;if(l.has(u)){let p=l.get(u);throw new Error(`Route conflict: Multiple routes found for path '${u}'. Routes: ${p.file} and ${c.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}l.set(u,c)}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),i=lr(o),c=i===qe.HOMEPAGE_COMPONENT?qe.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),u=this._extractPageMeta(r,s),{entity:p,action:g,...f}=a||{};return{path:c,component:i,importPath:o,auth:a?.auth||!1,meta:{...u,...f,entity:u.entity,action:u.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=qt(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(i=>`:${i}`).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]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),a=null,i=null;return o.length>1&&(a=o[o.length-2],s.includes("List")?i="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?i="form":(s.includes("Detail")||s.includes("View"))&&(i="detail")),{title:r,entity:a,action:i,file:e}}};var cr={isEmpty:n=>!n.routes||n.routes.length===0,generateModule:(n,e,t="routes")=>{let s={totalRoutes:n.routes.length,authRequired:n.routes.filter(o=>o.auth&&o.auth.required).length,publicRoutes:n.routes.filter(o=>!o.auth||o.auth===!1).length,source:n.source,generatedAt:new Date().toISOString(),errors:n.errors.length},r=n.routes.map(o=>` {
638
640
  path: '${o.path}',
639
641
  component: () => import('${o.importPath}'),
640
642
  auth: ${JSON.stringify(o.auth,null,2).replace(/\n/g,`
@@ -643,7 +645,7 @@ registerRoute(
643
645
  `)}
644
646
  }`).join(`,
645
647
  `);return`
646
- // ${M.routes} - Generated route data
648
+ // ${j.routes} - Generated route data
647
649
  import { lazy } from 'react';
648
650
 
649
651
  const routeData = [
@@ -665,7 +667,7 @@ if (typeof globalThis !== 'undefined') {
665
667
  }
666
668
 
667
669
  // Include all routes in mapping (navigation store will filter by hideFromMenu)
668
- globalThis._DNDEV_CONFIG_.${V[t]} = {
670
+ globalThis._DNDEV_CONFIG_.${H[t]} = {
669
671
  mapping: routeData,
670
672
  manifest: {
671
673
  totalRoutes: ${n.routes.length},
@@ -683,7 +685,7 @@ export const source = '${n.source}';
683
685
 
684
686
  export default { routes: routeData, manifest: routeManifest, source: '${n.source}' };
685
687
  `},generateEmpty:(n,e,t,s="routes")=>{let r={totalRoutes:0,authRequired:0,publicRoutes:0,source:"empty",generatedAt:new Date().toISOString()};return`
686
- // ${M.routes} - Empty route data
688
+ // ${j.routes} - Empty route data
687
689
 
688
690
  const routeData = [];
689
691
  const routeManifest = ${JSON.stringify(r,null,2)};
@@ -702,7 +704,7 @@ if (typeof globalThis !== 'undefined') {
702
704
  }
703
705
 
704
706
  // Populate empty routes configuration
705
- globalThis._DNDEV_CONFIG_.${V[s]} = {
707
+ globalThis._DNDEV_CONFIG_.${H[s]} = {
706
708
  mapping: [],
707
709
  manifest: {
708
710
  totalRoutes: 0,
@@ -747,7 +749,7 @@ export default discoveredRoutes;
747
749
  * Generated Route Discovery Results
748
750
  * Source: ${n.source}
749
751
  * Generated at: ${new Date().toISOString()}
750
- * Import from '${M.routes}'
752
+ * Import from '${j.routes}'
751
753
  */
752
754
 
753
755
  export const discoveredRoutes = [
@@ -761,35 +763,48 @@ export const routeManifest = {
761
763
  };
762
764
 
763
765
  export default discoveredRoutes;
764
- `},generateManifest:n=>({routes:n?.routes?.length||0,source:n?.source||"unknown",timestamp:Date.now(),errors:n?.errors?.length||0}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.routes||[],r=s.filter(a=>a.auth&&a.auth.required).length,o=s.length;t&&t.info(`${e} Routes: ${o} found${r>0?`, ${r} are authguarded`:""}`)}},Ms=[n=>n.endsWith("Page.tsx")];function It(n={}){return ue({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:M.routes,DiscoveryClass:Me,discoveryMethod:"discoverRoutes",filePatterns:Ms,templates:Cs,defaultInspectionPath:j.vite.routeInspection,manifestFileName:j.manifests.route,configKey:"routes"})({...n,disableHmr:n?.hmr===!1,hmrSmartDetection:!1})}import{loadEnv as Us}from"vite";B();import{readFileSync as zs,readdirSync as js,existsSync as Ls}from"fs";import{join as Ct}from"path";var ze=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:a,crawlDelay:i=1,routes:l={},...u}=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:i,routes:l,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...u},this.appRoot=u.appRoot||null,this.logger=F("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(),i={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:o.routes.length,publicRoutes:o.routes.filter(l=>!l.auth||l.auth===!1).length,protectedRoutes:o.routes.filter(l=>l.auth&&l.auth.required).length,blogPosts:a.length};return this.options.generateRobotsTxt&&(i.robotsTxt=await this.generateRobotsTxt(o,t,s)),this.options.generateSitemap&&(i.sitemap=await this.generateSitemap(o,t,s,a)),a.length>0&&(i.rss=await this.generateRSSFeed(a,t,s)),i.manifest=await this.generateManifest(o,t,s),i}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 i=a.path.startsWith("/")?a.path:`/${a.path}`;r.push(i)}}),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(l=>!l.auth||l.auth===!1).map(l=>({url:l.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:l.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 l of r)a.push({url:`/blog/${l.slug}`,lastmod:l.date,changefreq:"monthly",priority:"0.6"})}let i=this.generateSitemapContent(a);return await t("sitemap.xml",i),{fileName:"sitemap.xml",content:i,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=l=>l?l==="*"?"*":l.startsWith("/")?l:`/${l}`:"/",i=["User-agent: *",...s.map(l=>`Disallow: ${a(l)}`),...t.map(l=>`Allow: ${a(l)}`)];return o&&i.push(`Crawl-delay: ${o}`),r&&i.push(`Sitemap: ${r}`),i.join(`
765
- `)}generateSitemapContent(e){return`<?xml version="1.0" encoding="UTF-8"?>
766
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
767
- ${e.map(({url:s,lastmod:r,changefreq:o,priority:a})=>{let i=[` <loc>${this.options.baseUrl}${s}</loc>`];return r&&i.push(` <lastmod>${r}</lastmod>`),o&&i.push(` <changefreq>${o}</changefreq>`),a&&i.push(` <priority>${a}</priority>`),` <url>
768
- ${i.join(`
766
+ `},generateManifest:n=>({routes:n?.routes?.length||0,source:n?.source||"unknown",timestamp:Date.now(),errors:n?.errors?.length||0}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.routes||[],r=s.filter(a=>a.auth&&a.auth.required).length,o=s.length;t&&t.info(`${e} Routes: ${o} found${r>0?`, ${r} are authguarded`:""}`)}},ur=[n=>n.endsWith("Page.tsx")];function Kt(n={}){return ce({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:j.routes,DiscoveryClass:Be,discoveryMethod:"discoverRoutes",filePatterns:ur,templates:cr,manifestFileName:ie.manifests.route,configKey:"routes"})({...n,disableHmr:n?.hmr===!1,hmrSmartDetection:!1})}import{loadEnv as fr}from"vite";L();L();function G(n){return n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}var Ve=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:a,crawlDelay:i=1,aiCrawlers:l="recommended",routes:c={},...u}=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:i,aiCrawlers:l,routes:c,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...u},this.appRoot=u.appRoot||null,this.logger=C("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t){try{let s=this.generateRouteMetaTags(e.routes||[]),r={routes:e.routes||[],routeMetaTags:s,baseUrl:this.options.baseUrl,siteName:this.options.siteName},o=this.discoverBlogPosts(),a={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:r.routes.length,publicRoutes:r.routes.filter(i=>!i.auth||i.auth===!1).length,protectedRoutes:r.routes.filter(i=>i.auth&&i.auth.required).length,blogPosts:o.length};return this.options.generateRobotsTxt&&(a.robotsTxt=await this.generateRobotsTxt(r,t)),this.options.generateSitemap&&(a.sitemap=await this.generateSitemap(r,t,o)),o.length>0&&(a.rss=await this.generateRSSFeed(o,t)),a.manifest=await this.generateManifest(r,t),a}catch(s){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),s}}async generateRobotsTxt(e,t){let s=[];(e.routes||[]).forEach(o=>{if(o.auth&&o.auth.required){let a=o.path.startsWith("/")?o.path:`/${o.path}`;s.push(a)}}),s.push("/admin","/api","/_next","/static");let r=this.generateRobotsTxtContent({disallowedPaths:[...new Set(s)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",r),{fileName:"robots.txt",content:r,disallowedPaths:s.length}}async generateSitemap(e,t,s=[]){let o=(e.routes||[]).filter(i=>!(i.auth&&i.auth!==!1||typeof i.path=="string"&&i.path.includes(":")||s.length>0&&i.path===this.options.blogPath)).map(i=>({url:i.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:i.path==="/"?"1.0":"0.8"}));if(s.length>0){o.push({url:this.options.blogPath,lastmod:s[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let i of s)o.push({url:`${this.options.blogPath}/${i.slug}`,lastmod:i.date,changefreq:"monthly",priority:"0.6",image:i.image||null})}let a=this.generateSitemapContent(o);return await t("sitemap.xml",a),{fileName:"sitemap.xml",content:a,publicRoutes:o.length}}async generateManifest(e,t){let s={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,protectedRoutes:e.routes?.filter(o=>o.auth&&o.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},r=JSON.stringify(s,null,2);return await t("seo-manifest.json",r),{fileName:"seo-manifest.json",content:r,manifest:s}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:o}=e,a=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...s.map(c=>`Disallow: ${a(c)}`),...t.map(c=>`Allow: ${a(c)}`)];o&&i.push(`Crawl-delay: ${o}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...pr(l))),i.join(`
767
+ `)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:o,changefreq:a,priority:i,image:l})=>{let c=[` <loc>${G(this.options.baseUrl)}${G(r)}</loc>`];return o&&c.push(` <lastmod>${o}</lastmod>`),a&&c.push(` <changefreq>${a}</changefreq>`),i&&c.push(` <priority>${i}</priority>`),l&&c.push(` <image:image>
768
+ <image:loc>${G(this.options.baseUrl)}${G(l)}</image:loc>
769
+ </image:image>`),` <url>
770
+ ${c.join(`
769
771
  `)}
770
772
  </url>`}).join(`
771
- `)}
772
- </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(l=>l.charAt(0).toUpperCase()+l.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(l=>l.charAt(0).toUpperCase()+l.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=Ct(this.appRoot,"src","content","blog");try{if(!Ls(e))return[];let t=js(e).filter(r=>r.endsWith("_en.md"));if(t.length===0)return[];let s=[];for(let r of t){let o=zs(Ct(e,r),"utf-8"),a=r.replace(/_en\.md$/,""),i=o.match(/^---\r?\n([\s\S]*?)\r?\n---/),l={};if(i)for(let u of i[1].split(`
773
- `)){let c=u.indexOf(":");c!==-1&&(l[u.slice(0,c).trim()]=u.slice(c+1).trim())}s.push({slug:a,title:l.title||a,description:l.description||"",date:l.date||new Date().toISOString().split("T")[0],tags:l.tags?l.tags.split(",").map(u=>u.trim()):[],image:l.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>
774
- <title><![CDATA[${a.title}]]></title>
775
- <link>${this.options.baseUrl}/blog/${a.slug}</link>
776
- <guid>${this.options.baseUrl}/blog/${a.slug}</guid>
777
- <description><![CDATA[${a.description}]]></description>
778
- <pubDate>${a.date?new Date(a.date).toUTCString():""}</pubDate>${a.tags.length?`
779
- <category>${a.tags.join(", ")}</category>`:""}${a.image?`
780
- <enclosure url="${this.options.baseUrl}${a.image}" type="image/png" length="0"/>`:""}
773
+ `);return`<?xml version="1.0" encoding="UTF-8"?>
774
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
775
+ xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
776
+ ${s}
777
+ </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(l=>l.charAt(0).toUpperCase()+l.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(l=>l.charAt(0).toUpperCase()+l.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=E.getInstance(),t=e.resolvePath("src/content/blog",this.appRoot);try{if(!e.pathExists(t))return[];let s=e.readdirSync(t).filter(o=>o.endsWith("_en.md"));if(s.length===0)return[];let r=[];for(let o of s){let a=e.readSync(e.resolvePath(o,t),{format:"text"}),i=o.replace(/_en\.md$/,""),l=a.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(l)for(let u of l[1].split(`
778
+ `)){let p=u.indexOf(":");p!==-1&&(c[u.slice(0,p).trim()]=u.slice(p+1).trim())}r.push({slug:i,title:c.title||i,description:c.description||"",date:c.date||new Date().toISOString().split("T")[0],tags:c.tags?c.tags.split(",").map(u=>u.trim()):[],image:c.image||null})}return r.sort((o,a)=>a.date.localeCompare(o.date)),this.logger.info(`\u{1F4DD} Discovered ${r.length} blog post(s) in src/content/blog/`),r}catch(s){return this.logger.debug(`Blog content discovery skipped: ${s.message}`),[]}}async generateRSSFeed(e,t){let s=e.map(o=>` <item>
779
+ <title><![CDATA[${o.title}]]></title>
780
+ <link>${G(this.options.baseUrl)}${G(this.options.blogPath)}/${G(o.slug)}</link>
781
+ <guid>${G(this.options.baseUrl)}${G(this.options.blogPath)}/${G(o.slug)}</guid>
782
+ <description><![CDATA[${o.description}]]></description>
783
+ <pubDate>${o.date?new Date(o.date).toUTCString():""}</pubDate>${o.tags.length?`
784
+ <category>${G(o.tags.join(", "))}</category>`:""}${o.image?`
785
+ <enclosure url="${G(this.options.baseUrl)}${G(o.image)}" type="image/png" length="0"/>`:""}
781
786
  </item>`).join(`
782
- `),o=`<?xml version="1.0" encoding="UTF-8"?>
787
+ `),r=`<?xml version="1.0" encoding="UTF-8"?>
783
788
  <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
784
789
  <channel>
785
- <title>${this.options.siteName}</title>
786
- <link>${this.options.baseUrl}/blog</link>
787
- <description>${this.options.siteName} Blog</description>
790
+ <title>${G(this.options.siteName)}</title>
791
+ <link>${G(this.options.baseUrl)}${G(this.options.blogPath)}</link>
792
+ <description>${G(this.options.siteName)} Blog</description>
788
793
  <language>en</language>
789
- <atom:link href="${this.options.baseUrl}/rss.xml" rel="self" type="application/rss+xml"/>
790
- ${r}
794
+ <atom:link href="${G(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
795
+ ${s}
791
796
  </channel>
792
- </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()}}};function Mt(n={}){let{disabled:e=!1,debug:t,generateRobotsTxt:s,generateSitemap:r,routes:o={},baseUrl:a,siteName:i,crawlDelay:l,isDev:u,...c}=n;if(e)return{name:"seo-disabled"};let p=F("SEO Plugin",t,!0),g=$.getInstance(),d=null,h=null,D=!1;async function O(){try{let y=g.resolveAppPath("src/routes.generated.log"),k=g.readSync(y,{format:"text"});if(!k)return p.error(`SEO plugin: routes discovery file not found at ${y}`),p.error("This indicates route discovery failed or did not run. SEO files will be generated with empty routes."),{routes:[],errors:[`Routes file missing: ${y}`],source:"fallback"};let R=k.match(/export const discoveredRoutes = (\[[\s\S]*?\]);/);if(!R)return p.error(`SEO plugin: failed to parse routes from ${y}`),p.error("Expected format: export const discoveredRoutes = [...];"),p.error("This indicates route discovery generated invalid output. SEO files will be generated with empty routes."),{routes:[],errors:[`Invalid routes file format: ${y}`],source:"fallback"};let b=R[1].replace(/component:\s*\(\)\s*=>\s*Promise\.resolve\(\{[^}]*\}\),?/g,"").replace(/component:\s*\(\)\s*=>\s*import\([^)]*\),?/g,"").replace(/component:\s*[^,}\n]+,?/g,"").replace(/,\s*,/g,",").replace(/,\s*}/g,"}").replace(/,\s*]/g,"]"),S=Function(`"use strict"; return ${b}`)();return{routes:S,errors:[],source:"generated",totalFiles:S.length}}catch(y){return p.warn(`Error parsing generated routes: ${y.message}, falling back to empty routes`),{routes:[],errors:[],source:"fallback"}}}return{name:"vite-seo-plugin",enforce:"pre",configResolved(y){let k=g.getAppRoot(),R=y.mode||"production",S=Us(R,k,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;S&&t&&p.debug(`Using app URL from VITE_APP_URL: ${S}`),d=i||null,h=a||S||null,p.verbose(`Name: ${d||"Not found"}`),p.verbose(`URL: ${h||"Not found"}`),d&&p.debug(` - Site name from appConfig: "${d}"`);let v=[];if(h||v.push("baseUrl (VITE_APP_URL in .env)"),d||v.push("siteName (APP_NAME in src/config/app.ts)"),v.length>0){D=!0,p.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),v.forEach(A=>p.warn(` - ${A}`)),p.warn(""),p.warn(" To fix:"),h||p.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),d||(p.warn(" 2. Add APP_NAME export to src/config/app.ts:"),p.warn(' export const APP_NAME = "Your App Name";')),p.warn(""),p.warn(" robots.txt and sitemap.xml will NOT be generated."),p.warn("");return}p.debug(`Generate robots.txt: ${s}`),p.debug(`Generate sitemap: ${r}`)},async generateBundle(){if(!D)try{let y=new ze({debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:h,siteName:d,crawlDelay:l,routes:o,appRoot:g.getAppRoot(),...c}),k=await O(),R=async(v,A)=>{this.emitFile({type:"asset",fileName:v,source:A})},b=async v=>!1,S=await y.generateSEOFiles(k,R,b);S.robotsTxt&&!S.robotsTxt.skipped&&p.info(`\u{1F916} robots.txt: ${S.robotsTxt.disallowedPaths||0} disallowed paths`),S.sitemap&&!S.sitemap.skipped&&p.info(`\u{1F5FA}\uFE0F sitemap.xml: ${S.sitemap.publicRoutes||0} routes`),S.rss&&!S.rss.skipped&&p.info(`\u{1F4E1} rss.xml: ${S.rss.postCount||0} blog posts`),S.manifest&&!S.manifest.skipped&&p.info("\u{1F4C4} seo-manifest.json")}catch(y){p.error(`SEO plugin failed to generate files (robots.txt/sitemap.xml): ${y.message}`),p.error(`Stack: ${y.stack||"No stack trace available"}`)}}}}L();function zt(n={}){let{debug:e}=n;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,s){return t.startsWith("node:")?(F("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):Ve.includes(t)||Ve.some(r=>t.startsWith(`${r}/`))?(F("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):at.includes(t)?(F("server-shim",e,!0).warn(`Blocking server-only import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):null},load(t){return t==="\0virtual:empty-server-module"?`
797
+ </rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,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()}}},nt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],at=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function pr(n){let e=["# AI Crawler Management"];if(n==="block-all"){for(let t of[...nt,...at])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(n==="allow-all"){for(let t of[...nt,...at])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of nt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of at)e.push(`User-agent: ${t}`,"Allow: /","");return e}L();function Zt(n={}){let{siteName:e,baseUrl:t,description:s,blogPosts:r=[],blogPath:o="/blog",logger:a}=n;if(!e||!t)return a?.warn?.("llms.txt generation skipped: missing siteName or baseUrl"),null;let l=ye({appRoot:n.appRoot,logger:a}).routes||[],c=[];c.push(`# ${e}`),c.push(""),s&&(c.push(`> ${s}`),c.push(""));let u=l.filter(p=>!p.auth||p.auth===!1);if(u.length>0){c.push("## Pages"),c.push("");for(let p of u){let g=p.path||"/",f=p.meta?.title||gr(g),m=p.meta?.description||"",d=`${t}${g}`;m?c.push(`- [${f}](${d}): ${m}`):c.push(`- [${f}](${d})`)}c.push("")}if(r.length>0){c.push("## Blog"),c.push("");for(let p of r){let g=`${t}${o}/${p.slug}`;p.description?c.push(`- [${p.title}](${g}): ${p.description}`):c.push(`- [${p.title}](${g})`)}c.push("")}return c.join(`
798
+ `)}function Xt(n={}){let{siteName:e,baseUrl:t,blogPosts:s=[],blogPath:r="/blog",appRoot:o,logger:a}=n;if(!e||!t)return null;if(s.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=E.getInstance(),l=o?i.resolvePath("src/content/blog",o):null;if(!l||!i.pathExists(l))return null;let c=[`# ${e}
799
+ `];n.description&&c.push(`> ${n.description}
800
+ `);for(let u of s){let p=i.resolvePath(`${u.slug}_en.md`,l);try{let g=i.readSync(p,{format:"text"});if(!g)continue;let f=g.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),m=`${t}${r}/${u.slug}`;c.push(`## ${u.title}
801
+ `),c.push(`Source: ${m}
802
+ `),u.date&&c.push(`Date: ${u.date}
803
+ `),c.push(f.trim()),c.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${u.slug}`)}}return c.join(`
804
+ `)}function gr(n){return n==="/"||n===""?"Home":(n.split("/").filter(Boolean).pop()||"Home").split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Qt(n={}){let{disabled:e=!1,debug:t,generateRobotsTxt:s,generateSitemap:r,routes:o={},baseUrl:a,siteName:i,siteDescription:l,crawlDelay:c,aiCrawlers:u,llmsTxt:p=!0,redirects:g,isDev:f,...m}=n;if(e)return{name:"seo-disabled"};let d=C("SEO Plugin",t,!0),P=E.getInstance(),w=null,_=null,T=!1;return{name:"vite-seo-plugin",enforce:"pre",configResolved(S){let D=P.getAppRoot(),N=S.mode||"production",b=fr(N,D,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;b&&t&&d.debug(`Using app URL from VITE_APP_URL: ${b}`),w=i||null;let k=a||b||null;_=k?k.trim().replace(/\/+$/,""):null,d.verbose(`Name: ${w||"Not found"}`),d.verbose(`URL: ${_||"Not found"}
805
+ `),w&&d.debug(` - Site name from appConfig: "${w}"`);let O=[];if(_||O.push("baseUrl (VITE_APP_URL in .env)"),w||O.push("siteName (APP_NAME in src/config/app.ts)"),O.length>0){T=!0,d.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),O.forEach(R=>d.warn(` - ${R}`)),d.warn(""),d.warn(" To fix:"),_||d.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),w||(d.warn(" 2. Add APP_NAME export to src/config/app.ts:"),d.warn(' export const APP_NAME = "Your App Name";')),d.warn(""),d.warn(" robots.txt and sitemap.xml will NOT be generated."),d.warn("");return}d.debug(`Generate robots.txt: ${s}`),d.debug(`Generate sitemap: ${r}`)},async generateBundle(){if(!T)try{let S=new Ve({debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:_,siteName:w,crawlDelay:c,aiCrawlers:u,routes:o,appRoot:P.getAppRoot(),...m}),D=ye({appRoot:P.getAppRoot(),logger:d}),N=async(b,k)=>{this.emitFile({type:"asset",fileName:b,source:k})},v=await S.generateSEOFiles(D,N);if(v.robotsTxt&&!v.robotsTxt.skipped&&d.info(`\u{1F916} robots.txt: ${v.robotsTxt.disallowedPaths||0} disallowed paths`),v.sitemap&&!v.sitemap.skipped&&d.info(`\u{1F5FA}\uFE0F sitemap.xml: ${v.sitemap.publicRoutes||0} routes`),v.rss&&!v.rss.skipped&&d.info(`\u{1F4E1} rss.xml: ${v.rss.postCount||0} blog posts`),v.manifest&&!v.manifest.skipped&&d.info("\u{1F4C4} seo-manifest.json"),p){let b=P.getAppRoot(),k=S.discoverBlogPosts(),O=Zt({siteName:w,baseUrl:_,description:l,appRoot:b,blogPosts:k,logger:d});if(O&&(await N("llms.txt",O),d.info("\u{1F4C4} llms.txt")),k.length>0){let R=Xt({siteName:w,baseUrl:_,description:l,appRoot:b,blogPosts:k,logger:d});R&&(await N("llms-full.txt",R),d.info("\u{1F4C4} llms-full.txt"))}}if(g?.length>0){let b=new Set,k=[];for(let{from:O,to:R,permanent:V}of g){let z=O.replace(/\/+$/,"")||"/",ae=R.replace(/\/+$/,"")||"/";if(z===ae){d.warn(`Redirect loop detected: ${O} \u2192 ${R} (skipped)`);continue}if(!O.startsWith("/")){d.warn(`Redirect source must start with /: "${O}" (skipped)`);continue}if(b.has(z)){d.warn(`Duplicate redirect source: "${O}" (skipped)`);continue}b.add(z),k.push(`${O} ${R} ${V===!1?302:301}`)}k.length>0&&(await N("_redirects",k.join(`
806
+ `)+`
807
+ `),d.info(`\u{1F4CE} _redirects: ${k.length} redirect${k.length>1?"s":""}`))}}catch(S){d.error(`SEO plugin failed to generate files (robots.txt/sitemap.xml): ${S.message}`),d.error(`Stack: ${S.stack||"No stack trace available"}`)}}}}U();function es(n={}){let{debug:e}=n;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,s){return t.startsWith("node:")?(C("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):Ke.includes(t)||Ke.some(r=>t.startsWith(`${r}/`))?(C("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):mt.includes(t)?(C("server-shim",e,!0).warn(`Blocking server-only import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):null},load(t){return t==="\0virtual:empty-server-module"?`
793
808
  // Node.js built-in modules shims for browser compatibility
794
809
  export const URL = globalThis.URL;
795
810
  export const URLSearchParams = globalThis.URLSearchParams;
@@ -1068,7 +1083,7 @@ ${r}
1068
1083
  // Google Logging Utils shims
1069
1084
  export const LoggingWinston = class LoggingWinston {};
1070
1085
  export const LoggingBunyan = class LoggingBunyan {};
1071
- `:null}}}L();L();var ke=class extends oe{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new he(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 Je.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(){Je.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 jt={isEmpty:n=>!n.themes||n.themes.length===0,generateModule:(n,e,t="themes")=>{let{themes:s}=n;if(!s||s.length===0)return jt.generateEmpty(n,e,void 0,t);let r=s.find(a=>a.essential&&a.name==="light")||s[0],o={totalThemes:s.length,defaultTheme:r?.name||"light",hasCustomThemes:s.some(a=>!a.essential),timestamp:new Date().toISOString()};return`// Virtual module: ${M.themes}
1086
+ `:null}}}U();U();U();var ts=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,ss=/['"]([^'"]+)['"]/g,_e=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:{...Ze.selectors,...this.options.customPatterns?.selectors},themes:{...Ze.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,i)=>{let l=a.replace(/[^a-zA-Z0-9]/g,"");return l?i===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.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),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(i))!==null;){let[,c,u,p]=o;if(!c||!p)continue;let g=u.match(this.patterns.themes.themeIcon),f=u.match(this.patterns.themes.themeIsDark),m={name:c,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${p})`),r.push(m),s.themes.set(c,{name:c,displayName:p,isDark:m.isDark,file:a,variables:new Set,meta:m.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(ts.lastIndex=0;(r=ts.exec(t))!==null;){let o=r[1],a;for(ss.lastIndex=0;(a=ss.exec(o))!==null;){let i=a[1].trim();i&&s.add(i)}}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||"")}};var Ce=class extends re{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new _e(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 Xe.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(){Xe.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 rs={isEmpty:n=>!n.themes||n.themes.length===0,generateModule:(n,e,t="themes")=>{let{themes:s}=n;if(!s||s.length===0)return rs.generateEmpty(n,e,void 0,t);let r=s.find(a=>a.essential&&a.name==="light")||s[0],o={totalThemes:s.length,defaultTheme:r?.name||"light",hasCustomThemes:s.some(a=>!a.essential),timestamp:new Date().toISOString()};return`// Virtual module: ${j.themes}
1072
1087
  // \u{1F680} STATIC INJECTION PATTERN - Zero Runtime Loading
1073
1088
  // Generated by @donotdev/config at ${new Date().toISOString()}
1074
1089
 
@@ -1096,7 +1111,7 @@ if (typeof globalThis !== 'undefined') {
1096
1111
  }
1097
1112
 
1098
1113
  // Populate themes configuration
1099
- globalThis._DNDEV_CONFIG_.${V[t]} = {
1114
+ globalThis._DNDEV_CONFIG_.${H[t]} = {
1100
1115
  discovered: themeData,
1101
1116
  mapping: themeData.reduce((acc, theme) => {
1102
1117
  acc[theme.name] = theme;
@@ -1143,7 +1158,7 @@ export default {
1143
1158
  getAllThemes,
1144
1159
  getThemeNames
1145
1160
  };
1146
- `},generateEmpty:(n,e,t,s="themes")=>{let r=n.themes&&n.themes.length>0?n.themes:[{name:"light",displayName:"Light",meta:{icon:"Sun",category:"light"},essential:!0,isDark:!1,source:"built-in",variableCount:0}],o=r.find(i=>i.essential&&i.name==="light")||r[0],a={totalThemes:r.length,defaultTheme:o?.name||"light",hasCustomThemes:r.some(i=>!i.essential),timestamp:new Date().toISOString()};return`// ${M.themes} - Using framework essential themes (fallback)
1161
+ `},generateEmpty:(n,e,t,s="themes")=>{let r=n.themes&&n.themes.length>0?n.themes:[{name:"light",displayName:"Light",meta:{icon:"Sun",category:"light"},essential:!0,isDark:!1,source:"built-in",variableCount:0}],o=r.find(i=>i.essential&&i.name==="light")||r[0],a={totalThemes:r.length,defaultTheme:o?.name||"light",hasCustomThemes:r.some(i=>!i.essential),timestamp:new Date().toISOString()};return`// ${j.themes} - Using framework essential themes (fallback)
1147
1162
  // Generated by @donotdev/config at ${new Date().toISOString()}
1148
1163
 
1149
1164
  export const THEMES = ${JSON.stringify(r,null,2)};
@@ -1167,7 +1182,7 @@ if (typeof globalThis !== 'undefined') {
1167
1182
  };
1168
1183
  }
1169
1184
 
1170
- globalThis._DNDEV_CONFIG_.${V[s]} = {
1185
+ globalThis._DNDEV_CONFIG_.${H[s]} = {
1171
1186
  discovered: themeData,
1172
1187
  mapping: themeData.reduce((acc, theme) => {
1173
1188
  acc[theme.name] = theme;
@@ -1229,7 +1244,7 @@ export default discoveredThemes;
1229
1244
  `;let s=t.find(r=>r.essential&&r.name==="light")||t[0];return`/**
1230
1245
  * Generated Theme Discovery Results
1231
1246
  * Generated at: ${new Date().toISOString()}
1232
- * Import from '${M.themes}'
1247
+ * Import from '${j.themes}'
1233
1248
  */
1234
1249
 
1235
1250
  export const discoveredThemes = ${JSON.stringify(t,null,2)};
@@ -1244,8 +1259,9 @@ export const themeManifest = {
1244
1259
  };
1245
1260
 
1246
1261
  export default discoveredThemes;
1247
- `},generateManifest:n=>({themes:n.themes?.length||0,timestamp:Date.now(),hasCustomThemes:n.themes?.some(e=>!e.essential)||!1}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.themes||[],r=s.filter(a=>!a.essential).length,o=s.length;t&&(o===0?t.warn(`${e} No themes discovered - using framework essential themes fallback`):t.info(`${e} Themes: ${o} discovered${r>0?` (${r} custom)`:""}`))}};function Lt(n={}){let e=Date.now();return F("theme-plugin",n.debug,n.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),ue({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:M.themes,DiscoveryClass:ke,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:jt,defaultInspectionPath:j.vite.themeInspection,manifestFileName:j.manifests.theme,configKey:"themes",createDiscovery:(r,o)=>{let a=new he(r,{debug:o.debug,logger:F("css-extractor",o.debug,o.verbose)});return new ke(a,r,o)}})(n)}B();function Ut(n={}){let e=F("vite-plugins",n.debug,n.verbose);try{let{mode:t,debug:s,verbose:r,isDev:o,server:a={},routes:i={},themes:l={},i18n:u={},assets:c={},seo:p={},pwa:g={},serverShim:d={},pluginFactory:h={}}=n,D=i.debug??s,O=l.debug??s,y=u.debug??s,k=c.debug??s,R=d.debug??s,b=[];b.push(zt({...d,debug:R}));let S;try{S=$.getInstance()}catch(v){throw new Error(`Failed to initialize PathResolver: ${v.message||v}`)}return b.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(v){if(s){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let T={root:v.root,mode:v.mode,envDir:v.envDir,base:v.base,build:v.build?{outDir:v.build.outDir,minify:v.build.minify}:void 0,server:v.server?{port:v.server.port,host:v.server.host}:void 0,plugins:v.plugins?{count:v.plugins.length,names:v.plugins.map(X=>X?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(T,null,2))}S.setAppRoot(v.root);let A=S.getAppRoot();if(o&&v.server?.port){let T=v.server.https?"https":"http";process.env.VITE_APP_URL=`${T}://localhost:${v.server.port}`,(s||r)&&e.debug(`VITE_APP_URL set: ${process.env.VITE_APP_URL}`)}else o&&e.warn("VITE_APP_URL not set in dev mode. Server port not available.");try{let T=S.getRepoRoot();e.verbose(`Repo: ${T}`),e.verbose(`App: ${A}`)}catch(T){e.debug(`Could not log PathResolver values: ${T.message}`)}if(v.server){let T=P=>{let x=P.replace(/\\/g,"/"),W=A.replace(/\\/g,"/");return!x.startsWith(W)};v.server.watch||(v.server.watch={});let X=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];v.server.watch={...v.server.watch,ignored:[...v.server.watch.ignored||[],...X,T]},e.verbose(`Fixed file watcher to use app root: ${A}`)}}}),b.push(At({debug:s,verbose:r})),b.push(Dt({debug:s})),b.push(Gs({fastRefresh:!0,jsxRuntime:"automatic"})),b.push(Bs({ignoreConfigErrors:!0})),a.https!==!1&&b.push(Ws()),b.push(It({...h,...i,debug:D})),b.push(Lt({...h,...l,debug:O})),b.push(...$t({...h,...u,debug:y})),b.push(wt({...h,...c,debug:k})),b.push(St({...h,mode:t,debug:s,verbose:r})),b.push(Mt({...p,debug:s,isDev:o})),g.enabled&&b.push(Ot({...g,debug:s})),b.push(Et({debug:s})),b}catch(t){throw F("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}L();B();function Vs(){let n=$.getInstance(),e=process.cwd(),t=n.resolvePath("/","/");for(;e!==t;){let s=n.resolvePath("node_modules/@donotdev",e);if(n.pathExists(s,!0))try{return n.readdirSync(s).filter(r=>!r.startsWith(".")).map(r=>`@donotdev/${r}`)}catch{return[]}e=n.resolvePath("..",e)}return[]}function Hs(n){if(!n)return{};let e={};return Array.isArray(n)?n.forEach(({find:t,replacement:s})=>{typeof t=="string"&&(e[t]=s)}):typeof n=="object"&&Object.assign(e,n),e}function Wt(n={}){let{alias:e,...t}=n,{conditions:s,...r}=t;return{alias:{"@":"/src",...Hs(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...s||[]],...r}}function Gt(n={}){let{include:e=[],exclude:t=[],esbuildOptions:s={},...r}=n,o=Vs(),a=[...e,...ye.optionalFeatures,...o],i=[...new Set(a)],l=[...new Set(t)];return{include:i,exclude:l,esbuildOptions:s,...r}}function Sr(n={}){return n==null&&(n={}),async(e={})=>{e==null&&(e={});try{let t=process.env.CI==="true";process.env.DNDEV_BUILD_ID||(process.env.DNDEV_BUILD_ID=t?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9));let s=e.command,r=e.mode,{appConfig:o,dndev:a,...i}=n;if(!o)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
1248
- Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof o!="object"||o===null)throw new Error(`appConfig must be an object, but got ${typeof o}. Make sure you are exporting appConfig from src/config/app.ts correctly.`);let l=o?.features?{debug:o.features.debug}:void 0,u=o?.seo&&typeof o.seo!="boolean"?{...o.seo,siteName:o.seo.siteName||o.app?.name}:o?.app?.name?{siteName:o.app.name}:void 0,{features:c,seo:p,...g}=i,d=o?.app?{name:o.app.name,shortName:o.app.shortName,description:o.app.description}:void 0,{pwa:h={},...D}=g,O={...h,app:h.app||d},y={...l?{features:l}:{},...u?{seo:u}:{},...Object.keys(O).length>0?{pwa:O}:{},...D,mode:r},k;try{k=ht(y)}catch(q){throw new Error(`mergeOptions failed: ${q?.message||q||"Unknown error"}`)}let R;try{R=vt(k)}catch(q){throw new Error(`normalizeOptions failed: ${q?.message||q||"Unknown error"}`)}if(!R)throw new Error("normalizeOptions returned undefined");let{mode:b,debug:S,verbose:v,isDev:A,isDebug:T,shouldAnalyze:X,serverOptions:P,previewOptions:x,buildOverrides:W,resolveOptions:Se,routeOptions:Q,themeOptions:ie,i18nOptions:_,assetOptions:N,featureOptions:C,seoOptions:I,pwaOptions:ee,serverShimOptions:G,chunkingOptions:pe,pluginFactoryOptions:de,base:ve,defineOptions:je,optimizeDepsOptions:Le,pluginsOptions:Pe,cssOptions:De,envDir:Ne,restOptions:Ae}=R,m=F("vite-config",S,v);m.debug(`Mode: ${b}, Dev: ${A}`);let w=process.env.DNDEV_BUILD_ID,z;s==="build"?z=`Building for ${b}`:s==="serve"?z=`Development server (${b})`:s==="preview"?z=`Preview server (serving ${b} build)`:z=`Running ${s} (${b})`,m.info(`
1249
- \u{1F3D7}\uFE0F DnDev Framework - ${z}${w?` [build:${w}]`:""}`),m.info(` Platform: Vite | Command: ${s} | Mode: ${b}
1250
- `);let le=Ut({mode:b,debug:S,verbose:v,isDev:A,routes:Q,themes:ie,i18n:_,assets:N,features:C,seo:I,pwa:ee,serverShim:G,chunkingOptions:pe,pluginFactory:de});if(!Array.isArray(le))throw new Error(`createVitePlugins returned ${typeof le}, expected array. Value: ${le}`);let ne=gt({mode:b,chunkingOptions:pe,debug:S,isDev:A,isDebug:T,shouldAnalyze:X}),Xt=dt(P.port||3e3,P,m),Qt=ft(x);if(a)try{let{createDndevPlugin:q}=await Promise.resolve().then(()=>(Zt(),Kt));Pe.push(q(typeof a=="object"?a:{}))}catch{}return{...ve&&{base:ve},plugins:[...le,...Pe],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...b==="production"&&{build:ne},...s==="serve"&&{server:Xt},...s==="preview"&&{preview:Qt},...Ne&&{envDir:Ne},customLogger:b==="production"&&!S?(()=>{let q={hasWarned:!1,_shouldSuppress(te){return te.includes("dist/")||te.includes("kB")||te.includes("\u2502")||te.includes("gzip:")||te.includes("\u2713 built in")||te.match(/built in \d+\.\d+s/)},info(te){q._shouldSuppress(te)},warn(te){q._shouldSuppress(te)},error(te){},warnOnce(te){q.hasWarned||(q.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return q})():void 0,css:{postcss:bt(De),...De},optimizeDeps:Gt(Le),resolve:Wt(Se),define:{...je,"process.env.NODE_ENV":JSON.stringify(r),__DEV__:JSON.stringify(A),__PROD__:JSON.stringify(!A)},...Ae}}catch(t){let s=t||new Error("Unknown error occurred"),r=s?.message||s?.toString()||String(s)||"Unknown error",o=s?.stack||"",a=new Error(`Failed to create Vite config: ${r}${o?`
1251
- ${o}`:""}`);throw a.stack=o||a.stack,a}}}export{Sr as defineViteConfig};
1262
+ `},generateManifest:n=>({themes:n.themes?.length||0,timestamp:Date.now(),hasCustomThemes:n.themes?.some(e=>!e.essential)||!1}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.themes||[],r=s.filter(a=>!a.essential).length,o=s.length;t&&(o===0?t.warn(`${e} No themes discovered - using framework essential themes fallback`):t.info(`${e} Themes: ${o} discovered${r>0?` (${r} custom)`:""}`))}};function os(n={}){let e=Date.now();return C("theme-plugin",n.debug,n.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),ce({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:j.themes,DiscoveryClass:Ce,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:rs,manifestFileName:ie.manifests.theme,configKey:"themes",createDiscovery:(r,o)=>{let a=new _e(r,{debug:o.debug,logger:C("css-extractor",o.debug,o.verbose)});return new Ce(a,r,o)}})(n)}L();function ns(n={}){let e=C("vite-plugins",n.debug,n.verbose);try{let{mode:t,debug:s,verbose:r,isDev:o,server:a={},routes:i={},themes:l={},i18n:c={},assets:u={},seo:p={},prerender:g={},pwa:f={},serverShim:m={},pluginFactory:d={}}=n,P=i.debug??s,w=l.debug??s,_=c.debug??s,T=u.debug??s,S=m.debug??s,D=[];D.push(es({...m,debug:S}));let N;try{N=E.getInstance()}catch(v){throw new Error(`Failed to initialize PathResolver: ${v.message||v}`)}return D.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(v){if(s){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let k={root:v.root,mode:v.mode,envDir:v.envDir,base:v.base,build:v.build?{outDir:v.build.outDir,minify:v.build.minify}:void 0,server:v.server?{port:v.server.port,host:v.server.host}:void 0,plugins:v.plugins?{count:v.plugins.length,names:v.plugins.map(O=>O?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(k,null,2))}N.setAppRoot(v.root);let b=N.getAppRoot();if(o&&v.server?.port){let k=v.server.https?"https":"http";process.env.VITE_APP_URL=`${k}://localhost:${v.server.port}`,(s||r)&&e.debug(`VITE_APP_URL set: ${process.env.VITE_APP_URL}`)}else o&&e.warn("VITE_APP_URL not set in dev mode. Server port not available.");try{let k=N.getRepoRoot();e.verbose(`Repo: ${k}`),e.verbose(`App: ${b}`)}catch(k){e.debug(`Could not log PathResolver values: ${k.message}`)}if(v.server){let k=R=>{let V=R.replace(/\\/g,"/"),z=b.replace(/\\/g,"/");return!V.startsWith(z)};v.server.watch||(v.server.watch={});let O=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];v.server.watch={...v.server.watch,ignored:[...v.server.watch.ignored||[],...O,k]},e.verbose(`Fixed file watcher to use app root: ${b}`)}}}),D.push(Wt({debug:s,verbose:r})),D.push(Lt({debug:s})),D.push(mr({fastRefresh:!0,jsxRuntime:"automatic"})),D.push(hr({ignoreConfigErrors:!0})),a.https===!0&&D.push(dr()),D.push(Kt({...d,...i,debug:P})),D.push(os({...d,...l,debug:w})),D.push(...jt({...d,...c,debug:_})),D.push(Ot({...d,...u,debug:T})),D.push(Ft({...d,mode:t,debug:s,verbose:r})),D.push(Qt({...p,debug:s,isDev:o})),f.enabled&&D.push(Jt({...f,debug:s})),D.push(It({debug:s})),D.push({name:"dndev-build-summary",enforce:"post",closeBundle(){let v=N,b=v.resolveAppPath("dist/assets");if(v.pathExists(b))try{let k=v.readdirSync(b),O=k.filter(z=>z.endsWith(".js")),R=k.filter(z=>z.endsWith(".css")),V=k.length-O.length-R.length;e.info(`
1263
+ Build output: ${O.length} JS, ${R.length} CSS, ${V} other \u2014 ${k.length} files total`)}catch{}}}),D.push(Ht({...g,debug:s,verbose:r})),D}catch(t){throw C("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}U();L();function vr(){let n=E.getInstance(),e=process.cwd(),t=n.resolvePath("/","/");for(;e!==t;){let s=n.resolvePath("node_modules/@donotdev",e);if(n.pathExists(s,!0))try{return n.readdirSync(s).filter(r=>!r.startsWith(".")).map(r=>`@donotdev/${r}`)}catch{return[]}e=n.resolvePath("..",e)}return[]}function yr(n){if(!n)return{};let e={};return Array.isArray(n)?n.forEach(({find:t,replacement:s})=>{typeof t=="string"&&(e[t]=s)}):typeof n=="object"&&Object.assign(e,n),e}function as(n={}){let{alias:e,...t}=n,{conditions:s,...r}=t;return{alias:{"@":"/src",...yr(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...s||[]],...r}}function is(n={}){let{include:e=[],exclude:t=[],esbuildOptions:s={},...r}=n,o=vr(),a=[...e,...xe.optionalFeatures,...o],i=[...new Set(a)],l=[...new Set(t)];return{include:i,exclude:l,esbuildOptions:s,...r}}function qr(n={}){return n==null&&(n={}),async(e={})=>{e==null&&(e={});try{let t=process.env.CI==="true";process.env.DNDEV_BUILD_ID||(process.env.DNDEV_BUILD_ID=t?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9));let s=e.command,r=e.mode,{appConfig:o,dndev:a,...i}=n;if(!o)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
1264
+ Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof o!="object"||o===null)throw new Error(`appConfig must be an object, but got ${typeof o}. Make sure you are exporting appConfig from src/config/app.ts correctly.`);let l=o?.features?{debug:o.features.debug}:void 0,c=o?.seo&&typeof o.seo!="boolean"?{...o.seo,siteName:o.seo.siteName||o.app?.name}:o?.app?.name?{siteName:o.app.name}:void 0,{features:u,seo:p,...g}=i,f=o?.app?{name:o.app.name,shortName:o.app.shortName,description:o.app.description}:void 0,{pwa:m={},...d}=g,P={...m,app:m.app||f},w={...l?{features:l}:{},...c?{seo:c}:{},...Object.keys(P).length>0?{pwa:P}:{},...d,mode:r},_;try{_=_t(w)}catch(q){throw new Error(`mergeOptions failed: ${q?.message||q||"Unknown error"}`)}let T;try{T=kt(_)}catch(q){throw new Error(`normalizeOptions failed: ${q?.message||q||"Unknown error"}`)}if(!T)throw new Error("normalizeOptions returned undefined");let{mode:S,debug:D,verbose:N,isDev:v,isDebug:b,shouldAnalyze:k,serverOptions:O,previewOptions:R,buildOverrides:V,resolveOptions:z,routeOptions:ae,themeOptions:de,i18nOptions:pe,assetOptions:ge,featureOptions:be,seoOptions:x,prerenderOptions:F,pwaOptions:M,serverShimOptions:I,chunkingOptions:X,pluginFactoryOptions:De,base:we,defineOptions:Pe,optimizeDepsOptions:y,pluginsOptions:$,cssOptions:B,envDir:Q,restOptions:oe}=T,Ie=C("vite-config",D,N);Ie.debug(`Mode: ${S}, Dev: ${v}`);let ct=process.env.DNDEV_BUILD_ID,Ae;s==="build"?Ae=`Building for ${S}`:s==="serve"?Ae=`Development server (${S})`:s==="preview"?Ae=`Preview server (serving ${S} build)`:Ae=`Running ${s} (${S})`,Ie.info(`
1265
+ \u{1F3D7}\uFE0F DnDev Framework - ${Ae}${ct?` [build:${ct}]`:""}`),Ie.info(` Platform: Vite | Command: ${s} | Mode: ${S}
1266
+ `);let Me=ns({mode:S,debug:D,verbose:N,isDev:v,routes:ae,themes:de,i18n:pe,assets:ge,features:be,seo:x,prerender:F,pwa:M,serverShim:I,chunkingOptions:X,pluginFactory:De});if(!Array.isArray(Me))throw new Error(`createVitePlugins returned ${typeof Me}, expected array. Value: ${Me}`);let hs=St({mode:S,chunkingOptions:X,debug:D,isDev:v,isDebug:b,shouldAnalyze:k}),vs=Pt(O.port||3e3,O,Ie),ys=Rt(R);if(a)try{let{createDndevPlugin:q}=await Promise.resolve().then(()=>(ms(),ds));$.push(q(typeof a=="object"?a:{}))}catch{}return{...we&&{base:we},plugins:[...Me,...$],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...S==="production"&&{build:hs},...s==="serve"&&{server:vs},...s==="preview"&&{preview:ys},...Q&&{envDir:Q},customLogger:S==="production"&&!D?(()=>{let q={hasWarned:!1,_shouldSuppress(ee){return ee.includes("dist/")||ee.includes("kB")||ee.includes("\u2502")||ee.includes("gzip:")||ee.includes("\u2713 built in")||ee.match(/built in \d+\.\d+s/)},info(ee){q._shouldSuppress(ee)},warn(ee){q._shouldSuppress(ee)},error(ee){},warnOnce(ee){q.hasWarned||(q.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return q})():void 0,css:{postcss:At(B),...B},optimizeDeps:is(y),resolve:as(z),define:{...Pe,"process.env.NODE_ENV":JSON.stringify(r),__DEV__:JSON.stringify(v),__PROD__:JSON.stringify(!v)},...oe}}catch(t){let s=t||new Error("Unknown error occurred"),r=s?.message||s?.toString()||String(s)||"Unknown error",o=s?.stack||"",a=new Error(`Failed to create Vite config: ${r}${o?`
1267
+ ${o}`:""}`);throw a.stack=o||a.stack,a}}}export{qr as defineViteConfig};