@donotdev/core 0.2.2 → 0.3.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 (60) hide show
  1. package/functions/index.js +13 -13
  2. package/i18n/locales/eager/dndev_ar.json +13 -0
  3. package/i18n/locales/eager/dndev_da.json +13 -0
  4. package/i18n/locales/eager/dndev_de.json +13 -0
  5. package/i18n/locales/eager/dndev_en.json +13 -0
  6. package/i18n/locales/eager/dndev_es.json +13 -0
  7. package/i18n/locales/eager/dndev_fr.json +13 -0
  8. package/i18n/locales/eager/dndev_it.json +13 -0
  9. package/i18n/locales/eager/dndev_ja.json +13 -0
  10. package/i18n/locales/eager/dndev_ko.json +13 -0
  11. package/i18n/locales/eager/dndev_nl.json +13 -0
  12. package/i18n/locales/eager/dndev_pl.json +645 -0
  13. package/i18n/locales/eager/dndev_pt.json +13 -0
  14. package/i18n/locales/eager/dndev_zh.json +13 -0
  15. package/i18n/locales/lazy/auth_ar.json +5 -2
  16. package/i18n/locales/lazy/auth_da.json +5 -2
  17. package/i18n/locales/lazy/auth_de.json +5 -2
  18. package/i18n/locales/lazy/auth_en.json +5 -2
  19. package/i18n/locales/lazy/auth_es.json +5 -2
  20. package/i18n/locales/lazy/auth_fr.json +5 -2
  21. package/i18n/locales/lazy/auth_it.json +5 -2
  22. package/i18n/locales/lazy/auth_ja.json +5 -2
  23. package/i18n/locales/lazy/auth_ko.json +5 -2
  24. package/i18n/locales/lazy/auth_nl.json +5 -2
  25. package/i18n/locales/lazy/auth_pl.json +195 -0
  26. package/i18n/locales/lazy/auth_pt.json +5 -2
  27. package/i18n/locales/lazy/auth_zh.json +5 -2
  28. package/i18n/locales/lazy/billing_pl.json +93 -0
  29. package/i18n/locales/lazy/blog_pl.json +9 -0
  30. package/i18n/locales/lazy/cookies_pl.json +35 -0
  31. package/i18n/locales/lazy/crud_ar.json +89 -3
  32. package/i18n/locales/lazy/crud_da.json +87 -4
  33. package/i18n/locales/lazy/crud_de.json +89 -3
  34. package/i18n/locales/lazy/crud_en.json +86 -4
  35. package/i18n/locales/lazy/crud_es.json +91 -4
  36. package/i18n/locales/lazy/crud_fr.json +90 -4
  37. package/i18n/locales/lazy/crud_it.json +91 -4
  38. package/i18n/locales/lazy/crud_ja.json +89 -3
  39. package/i18n/locales/lazy/crud_ko.json +89 -3
  40. package/i18n/locales/lazy/crud_nl.json +87 -4
  41. package/i18n/locales/lazy/crud_pl.json +632 -0
  42. package/i18n/locales/lazy/crud_pt.json +89 -5
  43. package/i18n/locales/lazy/crud_zh.json +87 -4
  44. package/i18n/locales/lazy/homeTemplate_pl.json +52 -0
  45. package/i18n/locales/lazy/legalNotice_de.json +55 -0
  46. package/i18n/locales/lazy/legalNotice_pl.json +55 -0
  47. package/i18n/locales/lazy/oauth_pl.json +11 -0
  48. package/i18n/locales/lazy/privacy_pl.json +178 -0
  49. package/i18n/locales/lazy/terms_pl.json +200 -0
  50. package/index.d.ts +5696 -2999
  51. package/index.js +6 -6
  52. package/next/index.d.ts +139 -4
  53. package/next/index.js +545 -163
  54. package/next/runtime.js +3 -0
  55. package/package.json +5 -3
  56. package/server.d.ts +5322 -2855
  57. package/server.js +1 -1
  58. package/symbol-index.json +1 -1
  59. package/vite/index.d.ts +10 -0
  60. package/vite/index.js +69 -68
package/vite/index.js CHANGED
@@ -1,13 +1,13 @@
1
- var ks=Object.defineProperty;var Xe=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(s){throw t=[s],s}};var Ds=(n,e)=>{for(var t in e)ks(n,t,{get:e[t],enumerable:!0})};function St(n,e=null){let t=oe[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function We(n){return bt[n]||bt.base}var et,L,Y,ge,ke,tt,Fe,Ue,oe,ve,wt,st,rt,Ce,xt,ot,bt,G=Xe(()=>{"use strict";et={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},L={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},Y={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},ge={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",blogContent:"src/content/blog/blog-content.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},ke="/og-image.png",tt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},Fe={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Ue={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"},oe={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:[`${Ue.SOURCE_EAGER}/*_*.json`],lazy:[`${Ue.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/**"]},ve={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","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"]},wt=["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"],st=["@donotdev/core/functions","@donotdev/core/server"],rt={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)/}},Ce={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]},xt={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:[]},ot=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],bt={base:{absolute:!0,onlyFiles:!0,ignore:oe.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...oe.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...oe.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:oe.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:oe.globalIgnore}}});import*as O from"node:fs";import"node:fs";import{createRequire as Is}from"node:module";import{resolve as Ie,join as be,dirname as we,relative as Pt,normalize as Ms,sep as Rt,extname as Ls}from"node:path";import{fileURLToPath as zs}from"node:url";import js from"fast-glob";function $t(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var De,V,Et,$,B=Xe(()=>{"use strict";G();De={getGlobOptionsFor:We||void 0,SCAN_PATTERNS:oe||void 0,getPatternsFor:St||void 0,I18N_PATHS:Ue||void 0},V={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};Et={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;_writtenPaths=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 Ms(e).split(Rt).join("/")}catch{return String(e).split(Rt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Pt(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(we(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Is(be(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=Ie(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Ie(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=Ie(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=O.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:Ls(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 O.promises.readFile(e);let a=await O.promises.readFile(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&V.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 O.readFileSync(e);let a=O.readFileSync(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&V.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(we(l)),u=this.pathExists(l);if(u&&!o)return i&&V.info(`Skipping existing file: ${l}`),!1;if(a)return V.info(`[DRY RUN] Would write file: ${l}`),!0;try{await O.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)}
2
- `:g=String(t);try{return await $t(async()=>(Buffer.isBuffer(g)?await O.promises.writeFile(l,g):await O.promises.writeFile(l,g,"utf8"),i&&V.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(we(l)),u=this.pathExists(l);if(u&&!o)return i&&V.info(`Skipping existing file: ${l}`),!1;if(a)return V.info(`[DRY RUN] Would write file: ${l}`),!0;try{O.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)}
3
- `:g=String(t);try{return Buffer.isBuffer(g)?O.writeFileSync(l,g):O.writeFileSync(l,g,"utf8"),this._writtenPaths?.add(l),i&&V.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&&V.info(`Skipping existing file: ${i}`),!1;if(o)return V.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(we(i));try{await O.promises.mkdir(c,{recursive:!0})}catch(u){if(u?.code!=="EEXIST")throw u}try{return await $t(async()=>(await O.promises.copyFile(e,i),a&&V.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&&V.info(`Skipping existing file: ${i}`),!1;if(o)return V.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(we(i));try{O.mkdirSync(c,{recursive:!0})}catch(u){if(u?.code!=="EEXIST")throw u}try{return O.copyFileSync(e,i),this._writtenPaths?.add(i),a&&V.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return O.existsSync(e)}catch(s){return t||V.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 O.existsSync(t)||O.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return O.readdirSync(e,t)}catch(s){return this.options.debug&&V.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return O.statSync(e)}catch(t){return this.options.debug&&V.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return O.realpathSync(e)}watch(e,t,s){return O.watch(e,t,s)}lstatSync(e){try{return O.lstatSync(e)}catch(t){return this.options.debug&&V.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await O.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{O.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await O.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){O.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return O.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}startWriteRecording(){this._writtenPaths=new Set}stopWriteRecording(){if(!this._writtenPaths)throw new Error("stopWriteRecording() called without startWriteRecording()");let e=this._writtenPaths;return this._writtenPaths=null,e}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=be(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Ie(e)),s=this.getAppRoot(),r=Pt(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(be(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:De.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=De.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(be(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await js(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=De.getGlobOptionsFor?De.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(!De.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=De.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=we(zs(import.meta.url));return this.normalizePath(Ie(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(be(t,Et.TOOLING)),a=this.normalizePath(be(t,Et.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=be(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(be(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(we(t))===t)return t;let c=this.normalizePath(we(t));if(c===t)break;t=c,s++}return this.normalizePath(e)}}});var Ss={};Ds(Ss,{createDndevPlugin:()=>Zr});import{execSync as me,execFileSync as Oe,spawn as Pr}from"node:child_process";function K(){return $.getInstance()}function te(){return K().getRepoRoot()}function ys(){return K().resolveRepoPath(".dndev")}function h(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function ye(n,e=Rr){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 $r(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function Er(){let n=K(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",o=me(r,{encoding:"utf8"}).trim().split(`
4
- `)[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 bs(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 _r(n){return n.includes("..")?!1:n.startsWith(".dndev/")||n.startsWith("docs/")||n.startsWith("guides/")}function ws(n){let e=K(),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 Dr(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(!bs(s))return h(e,{error:"Access denied"},403);let r=ws(s);if(!r)return h(e,{error:"Access denied"},403);let o=K();if(!o.pathExists(r))return h(e,{error:"File not found"},404);let a=$r(r);if(kr.has(a)){let i=o.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":xs[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 Ar(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("dir"),r=K(),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 Nr(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(!bs(s))return h(e,{error:"Access denied"},403);if(!_r(s))return h(e,{error:"Write not allowed to this path"},403);let r=ws(s);if(!r)return h(e,{error:"Access denied"},403);try{let o=await ye(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 K().write(r,i,{overwrite:!0}),h(e,{ok:!0})}catch{h(e,{error:"Failed to write file"},500)}}async function Or(n,e){try{let t=await ye(n),{line:s,checked:r}=JSON.parse(t);if(typeof s!="number")return h(e,{error:"line number required"},400);let o=K(),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(`
5
- `);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(`
6
- `),{overwrite:!0}),h(e,{ok:!0,line:l[s]})}catch{h(e,{error:"Failed to update progress"},500)}}async function Tr(n,e){try{let t=await ye(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=K(),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 Fr(n,e){try{let t=await ye(n),{action:s,phase:r}=JSON.parse(t);if(!s||typeof r!="number")return h(e,{error:"action and phase required"},400);let o=K(),a=ys();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 Cr(n,e){try{let t=te(),s=me("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=me("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 Ir(n,e){try{let t=await ye(n),s=JSON.parse(t);if(!s.id||!s.type||!s.result)return h(e,{error:"id, type, and result required"},400);let r=K(),o=ys();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 Mr(n,e){let t=K(),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 Lr(n,e){try{let t=te(),s=me("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),r=[],o={};for(let a of s.split(`
7
- `))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 zr(n,e){try{let t=await ye(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=te(),o=K(),a=o.resolvePath("..",r),i=o.getBasename(r),l=o.resolvePath(`${i}-${s.replace(/\//g,"-")}`,a);Oe("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 jr(n,e){try{let t=await ye(n),{path:s}=JSON.parse(t);if(!s||typeof s!="string")return h(e,{error:"path required"},400);let r=te();Oe("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 Ur(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=te(),o=Oe("git",["diff",`main...${s}`,"--stat"],{cwd:r,encoding:"utf-8",timeout:1e4}).trim(),a=Oe("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 Wr(n,e){try{let t=await ye(n),{branch:s,title:r,bodyText:o}=JSON.parse(t);if(!s)return h(e,{error:"branch required"},400);let a=te(),i=["pr","create","--head",s];r&&i.push("--title",r),o&&i.push("--body",o);let l=Oe("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 Gr(n,e){try{let t=te(),s=me("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 Br(n,e){try{let t=te(),s=me("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 Vr(n,e){try{let t=te(),s=me("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 Hr(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=te(),o=me(`gh pr diff ${s}`,{cwd:r,encoding:"utf-8",timeout:3e4});h(e,{diff:o})}catch(t){h(e,{error:t.message},500)}}function Jr(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=te(),o=me(`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 qr(n,e){try{let t=await ye(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=te(),l=["pr","review",String(s),`--${r}`];o&&l.push("--body",o),Oe("gh",l,{cwd:i,encoding:"utf-8",timeout:15e3}),h(e,{ok:!0})}catch(t){h(e,{error:t.message},500)}}function Yr(n){if(gt)return;let e=K(),t=e.normalizePath(n.config.root),s=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(s))return;try{let i=me(`fuser ${vs}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}gt=!0;let r=e.getRepoRoot(),o=Er(),a=Pr(o,[s],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(vs),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{gt=!1}),process.on("exit",()=>{a.kill()})}function Kr(n){let e=K(),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}`;ft.has(u)||(ft.set(u,!0),setTimeout(()=>ft.delete(u),300),n.hot.send("dndev:file-changed",{path:c,timestamp:Date.now()}))});n.httpServer?.on("close",()=>a.close())}}function Zr(n={}){return{name:"dndev",configureServer(e){let t=te();n.debug,e.middlewares.use((s,r,o)=>{let a=s.url;if(!a?.startsWith(hs))return o();let l=new URL(a,`http://${s.headers.host}`).pathname.slice(hs.length),c=s.method?.toUpperCase();if(c==="GET")return l==="/file"?void Dr(s,r):l==="/tree"?void Ar(s,r):l==="/git/head"?void Cr(s,r):l==="/apps"?void Mr(s,r):l==="/worktrees"?void Lr(s,r):l==="/worktrees/diff"?void Ur(s,r):l==="/git/platform"?void Gr(s,r):l==="/git/prs"?void Br(s,r):l==="/git/issues"?void Vr(s,r):l==="/git/pr/diff"?void Hr(s,r):l==="/git/pr/checks"?void Jr(s,r):h(r,{error:"Not found"},404);if(c==="POST")return l==="/file"?void Nr(s,r):l==="/progress/toggle"?void Or(s,r):l==="/bugs/screenshot"?void Tr(s,r):l==="/phase"?void Fr(s,r):l==="/actions/append"?void Ir(s,r):l==="/worktrees/add"?void zr(s,r):l==="/worktrees/remove"?void jr(s,r):l==="/worktrees/pr"?void Wr(s,r):l==="/git/pr/review"?void qr(s,r):h(r,{error:"Not found"},404);h(r,{error:"Method not allowed"},405)}),Yr(e),Kr(e)}}}var hs,Rr,xs,kr,vs,gt,ft,Ps=Xe(()=>{"use strict";B();hs="/api/dndev";Rr=5*1024*1024;xs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},kr=new Set(Object.keys(xs));vs=24681,gt=!1;ft=new Map});import Ws from"@rollup/plugin-strip";import{visualizer as Gs}from"rollup-plugin-visualizer";var Qe=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-day-picker/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],As={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function Ns(n){let e=n.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function ht(n){let e=n.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function vt(n,e=Qe){return e.some(t=>n.includes(t))}function Os(n){for(let[e,t]of Object.entries(As))if(t.some(s=>n.includes(s)))return e}function Ts(n){let e=Ns(n);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=ht(n);if(!t)return;if(vt(t))return"react-core";let s=Os(t);if(s)return s}function Fs(n=[]){let e=n.filter(s=>!Qe.includes(s)),t=[...Qe,...e];return function(s){let r=ht(s);if(r&&vt(r,t))return"react-core"}}var mt={development:{manualChunks:void 0},production:{manualChunks:Ts}};function yt(n,e={}){let t=mt[n]||mt.production,s=e.reactCore||[];return s.length>0?{manualChunks:Fs(s)}:t}B();import*as ee from"@clack/prompts";var ue={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 Us(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function fe(n,e){return Us()?`${e}${n}${ue.reset}`:n}function I(n,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,a=$.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()} ===
8
- `;a.writeSync(i,p)}let l=(u,p,g)=>{if(i){let f=new Date().toISOString(),m=g.length>0?" "+g.map(S=>typeof S=="object"?JSON.stringify(S,null,2):String(S)).join(" "):"",d=`${f} [${u}] ${p}${m}
9
- `;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):ee.log.message(fe(c(u,p),ue.gray)))},verbose:(u,...p)=>{t&&(o?l("VERBOSE",u,p):ee.log.message(c(u,p)))},info:(u,...p)=>{o?l("INFO",u,p):ee.log.info(fe(c(u,p),ue.brightCyan))},warn:(u,...p)=>{e&&o?l("WARN",u,p):ee.log.warn(fe(c(u,p),ue.brightYellow))},error:(u,...p)=>{e&&o?l("ERROR",u,p):ee.log.error(fe(c(u,p),ue.brightRed))},success:(u,...p)=>{e&&o?l("SUCCESS",u,p):ee.log.success(fe(c(u,p),ue.brightGreen))},when:(u,p="debug")=>(g,...f)=>{if(u){let m=c(g,f);switch(p){case"verbose":t&&(ee.log.message(m),l("VERBOSE",g,f));break;case"info":ee.log.info(fe(m,ue.brightCyan)),l("INFO",g,f);break;case"warn":ee.log.warn(fe(m,ue.brightYellow)),l("WARN",g,f);break;case"error":ee.log.error(fe(m,ue.brightRed)),l("ERROR",g,f);break;case"success":ee.log.success(fe(m,ue.brightGreen)),l("SUCCESS",g,f);break;default:e&&(ee.log.message(fe(m,ue.gray)),l("DEBUG",g,f))}}},getLogFilePath:()=>i}}B();function _t(n={}){let{mode:e="development",chunkingOptions:t={},debug:s,verbose:r=!0,isDev:o,isDebug:a,shouldAnalyze:i,build:l={}}=n,c=I("build",s,r),u=yt(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)
10
- `)),{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:Bs(),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?[]:[Ws({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let g=$.getInstance(),f=g.getAppRoot(),m="dist",d=g.resolveAppPath(`${m}/stats.html`),S=()=>{try{let k=g.resolveAppPath(m);g.pathExists(k)||g.mkdir(k)}catch{}},x=Gs({filename:d,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:o||a,projectRoot:f});if(x.buildStart){let k=x.buildStart.bind(x);x.buildStart=function(...T){S();let D=k.apply(this,T);return D&&typeof D.then=="function"?D.catch(A=>{}):D}}else x.buildStart=function(){S()};let R=["generateBundle","writeBundle","closeBundle"];for(let k of R)if(x[k]){let T=x[k];x[k]=function(...D){try{S();let A=T.apply(this,D);return A&&typeof A.then=="function"?A.catch(P=>{let b=P?.message||P?.toString()||String(P)||"Unknown error";c.warn(`Bundle visualizer warning in ${k}: ${b}`),k==="closeBundle"&&c.warn(`You can manually open ${d} to view the bundle analysis`)}):A}catch(A){let P=A?.message||A?.toString()||String(A)||"Unknown error";c.warn(`Bundle visualizer warning in ${k}: ${P}`),k==="closeBundle"&&c.warn(` You can manually open ${d} to view the bundle analysis`)}}}return x})()]:[]]}}}function Bs(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 Vs(){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 Hs(n,e){if(n!==void 0)return n;let{isDocker:t,isWSL2:s,isBun:r}=Vs();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 kt(n,e={},t){let s=$.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=Hs(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 Dt(n={}){let e=n.https===!0;return{...n,https:e}}G();var At={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 ne={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function xe(n,e,t,s={}){let{protectedKeys:r=[],onConflict:o}=s;if(e==null)return n;switch(t){case ne.CONCATENATE_DEDUPE:{if(!Array.isArray(n)||!Array.isArray(e))return e;let a=[...n,...e];return[...new Set(a)]}case ne.SHALLOW_MERGE:return typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e)?e:{...n,...e};case ne.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]=xe(a[i],e[i],ne.DEEP_MERGE,{protectedKeys:r,onConflict:o}):a[i]=e[i]}return a}case ne.REPLACE:default:return e}}function Nt(n,e,t=[],s){let r=[...n,...e||[]],o=[...new Set(r)];return[...new Set([...o,...t])]}var Ae={...At,reactCompiler:!1,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"},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:[...ve.mandatoryIncludes],exclude:[...ve.buildTools,...Object.values(L)],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 Ot(n={},e={}){let{onConflict:t}=e,s={...Ae},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(R=>!R.startsWith("@donotdev/")),m=g.filter(R=>f.includes(R));if(m.length>0)for(let R of m)o("optimizeDeps.exclude",R,"excluded",`Framework requires ${R} to be included. It will be included despite your exclusion.`);let d=Nt(c,p,f),S=xe(u,g,ne.CONCATENATE_DEDUPE),x=xe(l?.esbuildOptions||{},i.esbuildOptions||{},ne.DEEP_MERGE,{protectedKeys:["external"],onConflict:R=>o(`optimizeDeps.esbuildOptions.${R}`,l?.esbuildOptions?.[R],i.esbuildOptions?.[R],`Framework requires ${R} to remain as configured.`)});s[a]={...l,include:d,exclude:S,esbuildOptions:x,...Object.fromEntries(Object.entries(i).filter(([R])=>!["include","exclude","esbuildOptions"].includes(R)))};return}if(a==="css"&&typeof i=="object"&&i!==null){s[a]=xe(l||{},i,ne.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]=xe(l||{},i,ne.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]=xe(l,i,ne.CONCATENATE_DEDUPE):s[a]=i;return}if(typeof i=="object"&&i!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){s[a]=xe(l,i,ne.SHALLOW_MERGE);return}s[a]=i}),s}function Tt(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:S={},pluginFactory:x={},debug:R,verbose:k,base:T,define:D={},optimizeDeps:A={},plugins:P=[],css:b={},envDir:C,reactCompiler:y=!1,...w}=n,j=s==="development",F=R||j,U=s==="production"&&(r.analyze??Ae.build.analyze);return{mode:s,debug:R,verbose:k,isDev:j,isDebug:F,shouldAnalyze:U,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:S,pluginFactoryOptions:x,base:T,defineOptions:D,optimizeDepsOptions:A,pluginsOptions:P,cssOptions:b,envDir:C,reactCompiler:y,restOptions:w}}B();import Js from"autoprefixer";import qs from"postcss-import";import Ys from"postcss-nesting";function Ft({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 Ct(n={}){if(n.postcss)return n.postcss;let e=$.getInstance();return Ft({postcssImport:qs,postcssNesting:Ys,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 br from"@vitejs/plugin-basic-ssl";import wr from"@vitejs/plugin-react";import xr from"vite-tsconfig-paths";var Q=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 Gs=Object.defineProperty;var tt=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(s){throw t=[s],s}};var Bs=(n,e)=>{for(var t in e)Gs(n,t,{get:e[t],enumerable:!0})};function kt(n,e=null){let t=ne[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Ve(n){return Rt[n]||Rt.base}var rt,j,Y,fe,De,ot,Le,Be,ne,ye,Et,nt,at,$t,it,_t,lt,Rt,G=tt(()=>{"use strict";rt={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",blog:"@donotdev/blog-content"},Y={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},fe={next:{proxy:"src/proxy.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.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",blogContent:"src/content/blog/blog-content.generated.ts"},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"}},De="/og-image.png",ot={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},Le={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Be={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"},ne={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:[`${Be.SOURCE_EAGER}/*_*.json`],lazy:[`${Be.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","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","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"]},Et=["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"],nt=["@donotdev/core/functions","@donotdev/core/server"],at={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)/}},$t={Inter:"inter","Space Grotesk":"space-grotesk","Playfair Display":"playfair-display","Press Start 2P":"press-start-2p",Roboto:"roboto"},it={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]},_t={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin","latin-ext"],cs:["latin","latin-ext"],sk:["latin","latin-ext"],hr:["latin","latin-ext"],sl:["latin","latin-ext"],hu:["latin","latin-ext"],ro:["latin","latin-ext"],et:["latin","latin-ext"],lv:["latin","latin-ext"],lt:["latin","latin-ext"],mt:["latin","latin-ext"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin","latin-ext"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","latin-ext","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},lt=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Rt={base:{absolute:!0,onlyFiles:!0,ignore:ne.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...ne.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...ne.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:ne.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:ne.globalIgnore}}});import*as T from"node:fs";import"node:fs";import{createRequire as Zs}from"node:module";import{resolve as je,join as we,dirname as xe,relative as Dt,normalize as Xs,sep as At,extname as Qs}from"node:path";import{fileURLToPath as er}from"node:url";import tr from"fast-glob";function Ne(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="EEXIST"}function Nt(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Ae,V,Ot,_,B=tt(()=>{"use strict";G();Ae={getGlobOptionsFor:Ve||void 0,SCAN_PATTERNS:ne||void 0,getPatternsFor:kt||void 0,I18N_PATHS:Be||void 0},V={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};Ot={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;_writtenPaths=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 Xs(e).split(At).join("/")}catch{return String(e).split(At).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Dt(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(xe(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Zs(we(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=je(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=je(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=je(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=T.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:Qs(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 T.promises.readFile(e);let a=await T.promises.readFile(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&V.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 T.readFileSync(e);let a=T.readFileSync(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&V.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(xe(l)),c=this.pathExists(l);if(c&&!o)return i&&V.info(`Skipping existing file: ${l}`),!1;if(a)return V.info(`[DRY RUN] Would write file: ${l}`),!0;try{await T.promises.mkdir(u,{recursive:!0})}catch(g){if(!Ne(g))throw g}let p=this._detectFormat(e,r),f;Buffer.isBuffer(t)?f=t:p==="json"&&typeof t=="object"?f=`${JSON.stringify(t,null,2)}
2
+ `:f=String(t);try{return await Nt(async()=>(Buffer.isBuffer(f)?await T.promises.writeFile(l,f):await T.promises.writeFile(l,f,"utf8"),i&&V.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(xe(l)),c=this.pathExists(l);if(c&&!o)return i&&V.info(`Skipping existing file: ${l}`),!1;if(a)return V.info(`[DRY RUN] Would write file: ${l}`),!0;try{T.mkdirSync(u,{recursive:!0})}catch(g){if(!Ne(g))throw g}let p=this._detectFormat(e,r),f;Buffer.isBuffer(t)?f=t:p==="json"&&typeof t=="object"?f=`${JSON.stringify(t,null,2)}
3
+ `:f=String(t);try{return Buffer.isBuffer(f)?T.writeFileSync(l,f):T.writeFileSync(l,f,"utf8"),this._writtenPaths?.add(l),i&&V.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(g){throw new Error(`Failed to write file: ${l}: ${g instanceof Error?g.message:String(g)}`)}}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&&V.info(`Skipping existing file: ${i}`),!1;if(o)return V.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(xe(i));try{await T.promises.mkdir(u,{recursive:!0})}catch(c){if(!Ne(c))throw c}try{return await Nt(async()=>(await T.promises.copyFile(e,i),a&&V.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&&V.info(`Skipping existing file: ${i}`),!1;if(o)return V.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(xe(i));try{T.mkdirSync(u,{recursive:!0})}catch(c){if(!Ne(c))throw c}try{return T.copyFileSync(e,i),this._writtenPaths?.add(i),a&&V.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return T.existsSync(e)}catch(s){return t||V.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 T.existsSync(t)||T.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return T.readdirSync(e,t)}catch(s){return this.options.debug&&V.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return T.statSync(e)}catch(t){return this.options.debug&&V.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return T.realpathSync(e)}watch(e,t,s){return T.watch(e,t,s)}lstatSync(e){try{return T.lstatSync(e)}catch(t){return this.options.debug&&V.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await T.promises.mkdir(e,{recursive:!0})}catch(t){if(!Ne(t))throw t}}ensureDirSync(e){try{T.mkdirSync(e,{recursive:!0})}catch(t){if(!Ne(t))throw t}}async remove(e){await T.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){T.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return T.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}startWriteRecording(){this._writtenPaths=new Set}stopWriteRecording(){if(!this._writtenPaths)throw new Error("stopWriteRecording() called without startWriteRecording()");let e=this._writtenPaths;return this._writtenPaths=null,e}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=we(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(je(e)),s=this.getAppRoot(),r=Dt(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(we(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:Ae.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Ae.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(we(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await tr(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=Ae.getGlobOptionsFor?Ae.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(!Ae.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=Ae.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")}getEmptyFlagModulePath(){let e=xe(er(import.meta.url));return this.normalizePath(je(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(we(t,Ot.TOOLING)),a=this.normalizePath(we(t,Ot.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=we(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(we(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(xe(t))===t)return t;let u=this.normalizePath(xe(t));if(u===t)break;t=u,s++}return this.normalizePath(e)}}});var Ms={};Bs(Ms,{createDndevPlugin:()=>ko});import{execSync as he,execFileSync as Ie,spawn as Qr}from"node:child_process";function K(){return _.getInstance()}function re(){return K().getRepoRoot()}function Ts(){return K().resolveRepoPath(".dndev")}function h(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function be(n,e=eo){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 to(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function so(){let n=K(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",o=he(r,{encoding:"utf8"}).trim().split(`
4
+ `)[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 Fs(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 ro(n){return n.includes("..")?!1:n.startsWith(".dndev/")||n.startsWith("docs/")||n.startsWith("guides/")}function Cs(n){let e=K(),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 no(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(!Fs(s))return h(e,{error:"Access denied"},403);let r=Cs(s);if(!r)return h(e,{error:"Access denied"},403);let o=K();if(!o.pathExists(r))return h(e,{error:"File not found"},404);let a=to(r);if(oo.has(a)){let i=o.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":Is[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 ao(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("dir"),r=K(),o=r.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(c,p){try{let f=r.readdirSync(c,{withFileTypes:!0});for(let g of f){let d=p?`${p}/${g.name}`:g.name;g.isDirectory()&&i.has(g.name)||(g.isDirectory()?(a.push({path:d,name:g.name,isDirectory:!0}),l(r.resolvePath(g.name,c),d)):g.name.endsWith(".md")&&a.push({path:d,name:g.name,isDirectory:!1}))}}catch{}}let u=[".dndev","docs","guides"];if(s){if(s.includes("..")||s.includes("\0"))return h(e,{error:"Access denied"},403);if(!u.includes(s)&&!u.some(g=>s.startsWith(g+"/")))return h(e,{error:"Directory not allowed"},403);let c=r.resolvePath(s,o),p=r.normalizePath(o);if(!r.normalizePath(c).startsWith(p+"/"))return h(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{}}h(e,{entries:a})}async function io(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(!Fs(s))return h(e,{error:"Access denied"},403);if(!ro(s))return h(e,{error:"Write not allowed to this path"},403);let r=Cs(s);if(!r)return h(e,{error:"Access denied"},403);try{let o=await be(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 K().write(r,i,{overwrite:!0}),h(e,{ok:!0})}catch{h(e,{error:"Failed to write file"},500)}}async function lo(n,e){try{let t=await be(n),{line:s,checked:r}=JSON.parse(t);if(typeof s!="number")return h(e,{error:"line number required"},400);let o=K(),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(`
5
+ `);if(s<0||s>=l.length)return h(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(`
6
+ `),{overwrite:!0}),h(e,{ok:!0,line:l[s]})}catch{h(e,{error:"Failed to update progress"},500)}}async function co(n,e){try{let t=await be(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=K(),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 uo(n,e){try{let t=await be(n),{action:s,phase:r}=JSON.parse(t);if(!s||typeof r!="number")return h(e,{error:"action and phase required"},400);let o=K(),a=Ts();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}),h(e,{ok:!0,protocol:l})}catch{h(e,{error:"Failed to update phase"},500)}}function po(n,e){try{let t=re(),s=he("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=he("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 go(n,e){try{let t=await be(n),s=JSON.parse(t);if(!s.id||!s.type||!s.result)return h(e,{error:"id, type, and result required"},400);let r=K(),o=Ts();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}),h(e,{ok:!0})}catch{h(e,{error:"Failed to append action"},500)}}function fo(n,e){let t=K(),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 mo(n,e){try{let t=re(),s=he("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),r=[],o={};for(let a of s.split(`
7
+ `))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 ho(n,e){try{let t=await be(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=re(),o=K(),a=o.resolvePath("..",r),i=o.getBasename(r),l=o.resolvePath(`${i}-${s.replace(/\//g,"-")}`,a);Ie("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 vo(n,e){try{let t=await be(n),{path:s}=JSON.parse(t);if(!s||typeof s!="string")return h(e,{error:"path required"},400);let r=re();Ie("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 yo(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=re(),o=Ie("git",["diff",`main...${s}`,"--stat"],{cwd:r,encoding:"utf-8",timeout:1e4}).trim(),a=Ie("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 bo(n,e){try{let t=await be(n),{branch:s,title:r,bodyText:o}=JSON.parse(t);if(!s)return h(e,{error:"branch required"},400);let a=re(),i=["pr","create","--head",s];r&&i.push("--title",r),o&&i.push("--body",o);let l=Ie("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 wo(n,e){try{let t=re(),s=he("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 xo(n,e){try{let t=re(),s=he("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 So(n,e){try{let t=re(),s=he("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 Po(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=re(),o=he(`gh pr diff ${s}`,{cwd:r,encoding:"utf-8",timeout:3e4});h(e,{diff:o})}catch(t){h(e,{error:t.message},500)}}function Ro(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=re(),o=he(`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 Eo(n,e){try{let t=await be(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=re(),l=["pr","review",String(s),`--${r}`];o&&l.push("--body",o),Ie("gh",l,{cwd:i,encoding:"utf-8",timeout:15e3}),h(e,{ok:!0})}catch(t){h(e,{error:t.message},500)}}function $o(n){if(vt)return;let e=K(),t=e.normalizePath(n.config.root),s=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(s))return;try{let i=he(`fuser ${Os}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}vt=!0;let r=e.getRepoRoot(),o=so(),a=Qr(o,[s],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(Os),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{vt=!1}),process.on("exit",()=>{a.kill()})}function _o(n){let e=K(),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}`;yt.has(c)||(yt.set(c,!0),setTimeout(()=>yt.delete(c),300),n.hot.send("dndev:file-changed",{path:u,timestamp:Date.now()}))});n.httpServer?.on("close",()=>a.close())}}function ko(n={}){return{name:"dndev",configureServer(e){let t=re();n.debug,e.middlewares.use((s,r,o)=>{let a=s.url;if(!a?.startsWith(Ns))return o();let l=new URL(a,`http://${s.headers.host}`).pathname.slice(Ns.length),u=s.method?.toUpperCase();if(u==="GET")return l==="/file"?void no(s,r):l==="/tree"?void ao(s,r):l==="/git/head"?void po(s,r):l==="/apps"?void fo(s,r):l==="/worktrees"?void mo(s,r):l==="/worktrees/diff"?void yo(s,r):l==="/git/platform"?void wo(s,r):l==="/git/prs"?void xo(s,r):l==="/git/issues"?void So(s,r):l==="/git/pr/diff"?void Po(s,r):l==="/git/pr/checks"?void Ro(s,r):h(r,{error:"Not found"},404);if(u==="POST")return l==="/file"?void io(s,r):l==="/progress/toggle"?void lo(s,r):l==="/bugs/screenshot"?void co(s,r):l==="/phase"?void uo(s,r):l==="/actions/append"?void go(s,r):l==="/worktrees/add"?void ho(s,r):l==="/worktrees/remove"?void vo(s,r):l==="/worktrees/pr"?void bo(s,r):l==="/git/pr/review"?void Eo(s,r):h(r,{error:"Not found"},404);h(r,{error:"Method not allowed"},405)}),$o(e),_o(e)}}}var Ns,eo,Is,oo,Os,vt,yt,Ls=tt(()=>{"use strict";B();Ns="/api/dndev";eo=5*1024*1024;Is={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},oo=new Set(Object.keys(Is));Os=24681,vt=!1;yt=new Map});import rr from"@rollup/plugin-strip";import{visualizer as or}from"rollup-plugin-visualizer";var st=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-day-picker/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],Vs={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function Hs(n){let e=n.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function xt(n){let e=n.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function St(n,e=st){return e.some(t=>n.includes(t))}function Js(n){for(let[e,t]of Object.entries(Vs))if(t.some(s=>n.includes(s)))return e}function qs(n){let e=Hs(n);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=xt(n);if(!t)return;if(St(t))return"react-core";let s=Js(t);if(s)return s}function Ys(n=[]){let e=n.filter(s=>!st.includes(s)),t=[...st,...e];return function(s){let r=xt(s);if(r&&St(r,t))return"react-core"}}var wt={development:{manualChunks:void 0},production:{manualChunks:qs}};function Pt(n,e={}){let t=wt[n]||wt.production,s=e.reactCore||[];return s.length>0?{manualChunks:Ys(s)}:t}B();import*as te from"@clack/prompts";var pe={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 sr(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function de(n,e){return sr()?`${e}${n}${pe.reset}`:n}function C(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()} ===
8
+ `;a.writeSync(i,p)}let l=(c,p,f)=>{if(i){let g=new Date().toISOString(),d=f.length>0?" "+f.map(m=>typeof m=="object"?JSON.stringify(m,null,2):String(m)).join(" "):"",P=`${g} [${c}] ${p}${d}
9
+ `;a.appendFile(i,P)}},u=(c,p)=>{if(p.length===0)return c;let f=p.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${c} ${f}`};return{debug:(c,...p)=>{e&&(o?l("DEBUG",c,p):te.log.message(de(u(c,p),pe.gray)))},verbose:(c,...p)=>{t&&(o?l("VERBOSE",c,p):te.log.message(u(c,p)))},info:(c,...p)=>{o?l("INFO",c,p):te.log.info(de(u(c,p),pe.brightCyan))},warn:(c,...p)=>{e&&o?l("WARN",c,p):te.log.warn(de(u(c,p),pe.brightYellow))},error:(c,...p)=>{e&&o?l("ERROR",c,p):te.log.error(de(u(c,p),pe.brightRed))},success:(c,...p)=>{e&&o?l("SUCCESS",c,p):te.log.success(de(u(c,p),pe.brightGreen))},when:(c,p="debug")=>(f,...g)=>{if(c){let d=u(f,g);switch(p){case"verbose":t&&(te.log.message(d),l("VERBOSE",f,g));break;case"info":te.log.info(de(d,pe.brightCyan)),l("INFO",f,g);break;case"warn":te.log.warn(de(d,pe.brightYellow)),l("WARN",f,g);break;case"error":te.log.error(de(d,pe.brightRed)),l("ERROR",f,g);break;case"success":te.log.success(de(d,pe.brightGreen)),l("SUCCESS",f,g);break;default:e&&(te.log.message(de(d,pe.gray)),l("DEBUG",f,g))}}},getLogFilePath:()=>i}}B();function Tt(n={}){let{mode:e="development",chunkingOptions:t={},debug:s,verbose:r=!0,isDev:o,isDebug:a,shouldAnalyze:i,build:l={}}=n,u=C("build",s,r),c=Pt(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)
10
+ `)),{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:nr(),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(f,g){f.code!=="MODULE_LEVEL_DIRECTIVE"&&g(f)},plugins:[...a?[]:[rr({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let f=_.getInstance(),g=f.getAppRoot(),d="dist",P=f.resolveAppPath(`${d}/stats.html`),m=()=>{try{let v=f.resolveAppPath(d);f.pathExists(v)||f.mkdir(v)}catch{}},S=or({filename:P,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:o||a,projectRoot:g});if(S.buildStart){let v=S.buildStart.bind(S);S.buildStart=function(...A){m();let R=v.apply(this,A);return R&&typeof R.then=="function"?R.catch(N=>{}):R}}else S.buildStart=function(){m()};let E=["generateBundle","writeBundle","closeBundle"];for(let v of E)if(S[v]){let A=S[v];S[v]=function(...R){try{m();let N=A.apply(this,R);return N&&typeof N.then=="function"?N.catch($=>{let w=$?.message||$?.toString()||String($)||"Unknown error";u.warn(`Bundle visualizer warning in ${v}: ${w}`),v==="closeBundle"&&u.warn(`You can manually open ${P} to view the bundle analysis`)}):N}catch(N){let $=N?.message||N?.toString()||String(N)||"Unknown error";u.warn(`Bundle visualizer warning in ${v}: ${$}`),v==="closeBundle"&&u.warn(` You can manually open ${P} to view the bundle analysis`)}}}return S})()]:[]]}}}function nr(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 ar(){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 ir(n,e){if(n!==void 0)return n;let{isDocker:t,isWSL2:s,isBun:r}=ar();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 Ft(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},f=i!==void 0?i:!0,g=l.https===!0;return{port:n,host:f,open:e.open!==void 0?e.open:!0,https:g,fs:{allow:[r,s.resolveRepoPath("packages"),s.resolveRepoPath("node_modules")],strict:!1},watch:(()=>{let d=ir(e?.watch?.usePolling,t);return{usePolling:d,interval:e?.watch?.interval??2e3,...d&&{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 Ct(n={}){let e=n.https===!0;return{...n,https:e}}G();var It={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 ae={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function Se(n,e,t,s={}){let{protectedKeys:r=[],onConflict:o}=s;if(e==null)return n;switch(t){case ae.CONCATENATE_DEDUPE:{if(!Array.isArray(n)||!Array.isArray(e))return e;let a=[...n,...e];return[...new Set(a)]}case ae.SHALLOW_MERGE:return typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e)?e:{...n,...e};case ae.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]=Se(a[i],e[i],ae.DEEP_MERGE,{protectedKeys:r,onConflict:o}):a[i]=e[i]}return a}case ae.REPLACE:default:return e}}function Mt(n,e,t=[],s){let r=[...n,...e||[]],o=[...new Set(r)];return[...new Set([...o,...t])]}var Oe={...It,reactCompiler:!1,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"},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:[...ye.mandatoryIncludes],exclude:[...ye.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 Lt(n={},e={}){let{onConflict:t}=e,s={...Oe},r=[],o=(a,i,l,u)=>{r.push({key:a,frameworkValue:i,userValue:l,reason:u}),t&&t(a,i,l,u)};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 u=l?.include||[],c=l?.exclude||[],p=i.include||[],f=i.exclude||[],g=u.filter(E=>!E.startsWith("@donotdev/")),d=f.filter(E=>g.includes(E));if(d.length>0)for(let E of d)o("optimizeDeps.exclude",E,"excluded",`Framework requires ${E} to be included. It will be included despite your exclusion.`);let P=Mt(u,p,g),m=Se(c,f,ae.CONCATENATE_DEDUPE),S=Se(l?.esbuildOptions||{},i.esbuildOptions||{},ae.DEEP_MERGE,{protectedKeys:["external"],onConflict:E=>o(`optimizeDeps.esbuildOptions.${E}`,l?.esbuildOptions?.[E],i.esbuildOptions?.[E],`Framework requires ${E} to remain as configured.`)});s[a]={...l,include:P,exclude:m,esbuildOptions:S,...Object.fromEntries(Object.entries(i).filter(([E])=>!["include","exclude","esbuildOptions"].includes(E)))};return}if(a==="css"&&typeof i=="object"&&i!==null){s[a]=Se(l||{},i,ae.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]=Se(l||{},i,ae.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]=Se(l,i,ae.CONCATENATE_DEDUPE):s[a]=i;return}if(typeof i=="object"&&i!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){s[a]=Se(l,i,ae.SHALLOW_MERGE);return}s[a]=i}),s}function jt(n){let{server:e={},preview:t={},mode:s,build:r={},resolve:o={},routes:a={},themes:i={},i18n:l={},assets:u={},features:c={},seo:p={},prerender:f={},pwa:g={},serverShim:d={},chunking:P={},discovery:m={},pluginFactory:S={},debug:E,verbose:v,base:A,define:R={},optimizeDeps:N={},plugins:$=[],css:w={},envDir:L,reactCompiler:b=!1,...x}=n,M=s==="development",F=E||M,z=s==="production"&&(r.analyze??Oe.build.analyze);return{mode:s,debug:E,verbose:v,isDev:M,isDebug:F,shouldAnalyze:z,serverOptions:e,previewOptions:t,buildOverrides:r,resolveOptions:o,routeOptions:a,themeOptions:i,i18nOptions:l,assetOptions:u,featureOptions:c,seoOptions:p,prerenderOptions:f,pwaOptions:g,serverShimOptions:d,chunkingOptions:P,discoveryOptions:m,pluginFactoryOptions:S,base:A,defineOptions:R,optimizeDepsOptions:N,pluginsOptions:$,cssOptions:w,envDir:L,reactCompiler:b,restOptions:x}}B();import lr from"autoprefixer";import cr from"postcss-import";import ur from"postcss-nesting";function zt({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 Ut(n={}){if(n.postcss)return n.postcss;let e=_.getInstance();return zt({postcssImport:cr,postcssNesting:ur,autoprefixer:lr,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 Yr from"@vitejs/plugin-basic-ssl";import Kr from"@vitejs/plugin-react";import Zr from"vite-tsconfig-paths";var ee=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}
11
11
  // Generated by @donotdev/config discovery
12
12
  // Version: 1.0.0
13
13
 
@@ -43,14 +43,14 @@ var ks=Object.defineProperty;var Xe=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&
43
43
  `);return`// Helper functions for ${e}
44
44
  // Generated by @donotdev/config
45
45
 
46
- ${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"}}};B();B();function Ks(n){let e=n.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!e)return{};let t={};for(let s of e[1].split(`
47
- `)){let r=s.indexOf(":");if(r===-1)continue;let o=s.slice(0,r).trim(),a=s.slice(r+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[o]=a}return t}function Ge(n,e={}){let{blogPath:t="/blog"}=e,s=$.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=[{path:t,auth:!1,meta:{namespace:"blog"}}];for(let c of i){let u=c.replace(/_en\.md$/,""),p=s.resolvePath(c,a),g=s.readSync(p,{format:"text"}),f=g?Ks(g):{};l.push({path:`${t}/${u}`,auth:!1,meta:{namespace:"blog",seo:{title:f.title||u,description:f.description||null,image:f.image||null,type:"article"}}})}return l}catch{return[]}}function Se(n={}){let{logger:e}=n,t=$.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 It(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)}function de(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:S=s,hmrDebounceMs:x,hmrCacheTimeout:R,hmrSmartDetection:k,disableHmr:T,...D}=f;if(!Q.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let A={...Ae.discovery,...u,debug:m,verbose:d,...D},P=p||(()=>{let v=e.match(/dndev-vite-(\w+)-discovery/);return v?v[1]:null})(),b=I(e,m,d,{fileLogging:A.fileLogging,logDir:A.logDir}),C=$.getInstance(),y=()=>{let v=C.getAppRoot(),_=C.getRepoRoot();return v&&v!==_},w=Date.now(),j=c?c(C,A):new r(C,A),F="\0"+S,U="",se=!1,q=null,le=0,he=!1,W=null,Pe=!1,E=null,N=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(j.clearCache(),W=null,b.info("Discovery cache cleared manually"),"Cache cleared"));function M(v){let J=Q.generateVirtualModule(v,i,m,A,P).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!T&&se&&(J+=`
46
+ ${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();B();function pr(n){let e=n.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!e)return{};let t={};for(let s of e[1].split(`
47
+ `)){let r=s.indexOf(":");if(r===-1)continue;let o=s.slice(0,r).trim(),a=s.slice(r+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[o]=a}return t}function He(n,e={}){let{blogPath:t="/blog"}=e,s=_.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(u=>u.endsWith("_en.md"));if(i.length===0)return[];let l=[{path:t,auth:!1,meta:{namespace:"blog"}}];for(let u of i){let c=u.replace(/_en\.md$/,""),p=s.resolvePath(u,a),f=s.readSync(p,{format:"text"}),g=f?pr(f):{};l.push({path:`${t}/${c}`,auth:!1,meta:{namespace:"blog",seo:{title:g.title||c,description:g.description||null,image:g.image||null,type:"article"}}})}return l}catch{return[]}}function Te(n={}){let{logger:e}=n,t=_.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 Wt(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)}function me(n){let{pluginName:e,icon:t,virtualModuleId:s,DiscoveryClass:r,discoveryMethod:o,filePatterns:a,templates:i,manifestFileName:l,createDiscovery:u,discoveryOptions:c={},configKey:p}=n;return function(g={}){let{debug:d,verbose:P,virtualModuleId:m=s,hmrDebounceMs:S,hmrCacheTimeout:E,hmrSmartDetection:v,disableHmr:A,...R}=g;if(!ee.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let N={...Oe.discovery,...c,debug:d,verbose:P,...R},$=p||(()=>{let y=e.match(/dndev-vite-(\w+)-discovery/);return y?y[1]:null})(),w=C(e,d,P,{fileLogging:N.fileLogging,logDir:N.logDir}),L=_.getInstance(),b=()=>{let y=L.getAppRoot(),D=L.getRepoRoot();return y&&y!==D},x=Date.now(),M=u?u(L,N):new r(L,N),F="\0"+m,z="",Z=!1,q=null,ce=0,ve=!1,W=null,Pe=!1,k=null,O=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(M.clearCache(),W=null,w.info("Discovery cache cleared manually"),"Cache cleared"));function I(y){let J=ee.generateVirtualModule(y,i,d,N,$).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!A&&Z&&(J+=`
48
48
 
49
49
  // HMR boundary for ${e}
50
50
  if (import.meta.hot) {
51
51
  import.meta.hot.accept();
52
52
  }
53
- `),J}function z(v){let _=v.replace(/\\/g,"/");if(T||_.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 J=C.getRelativePath(_);if(J.startsWith("packages/"))return!1;let pe=J.startsWith("src/")&&/\.(ts|tsx)$/.test(J);return pe?Array.isArray(a)&&a.length>0?a.some(Z=>typeof Z=="function"?Z(_):typeof Z=="string"?Z.startsWith("**/")?_.endsWith(Z.slice(3)):_.endsWith(Z):!1):pe:!1}function ce(v){if(T)return b.debug("Virtual modules are static - HMR disabled"),[];let _=Date.now();return Pe?(b.debug("HMR already in progress, skipping update"),[]):_-le<x?(he||(he=!0,q=setTimeout(()=>{he=!1,le=Date.now(),Ee(v)},x)),[]):(le=_,Ee(v))}function Ee(v){let _=Date.now();if(E===v.file&&_-le<100)return b.debug(`Same file processed too recently: ${v.file}`),[];if(!z(v.file))return b.debug(`Skipping irrelevant file change: ${v.file}`),[];b.debug(`Relevant file changed: ${v.file}`),Pe=!0,E=v.file;try{let J=Date.now()-(W?.timestamp||0);if(J<R&&W){b.debug(`Using cached discovery data (age: ${J}ms)`);let Z=v.server.moduleGraph.getModuleById(F);return Z&&v.server.reloadModule(Z),[]}j.clearCache();let pe=v.server.moduleGraph.getModuleById(F);return pe&&v.server.reloadModule(pe),[]}finally{Pe=!1,setTimeout(()=>{E===v.file&&(E=null)},200)}}return{name:e,enforce:"pre",configResolved(v){U=v.root,se=v.command==="serve",m&&b.debug(`${t} ${e} initialized`),se&&b.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),i.logConfig&&i.logConfig(A)},config(v){return v.optimizeDeps||(v.optimizeDeps={}),v.optimizeDeps.exclude||(v.optimizeDeps.exclude=[]),v.optimizeDeps.exclude.includes(S)||v.optimizeDeps.exclude.push(S),v},resolveId(v){return v===S?(b.debug(`Resolving virtual module: ${v}`),{id:F,moduleSideEffects:!0}):null},async load(v){if(v!==F)return null;if(b.debug(`Loading virtual module: ${v}`),!y()){b.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let _=0;for(;!y()&&_<100;)await new Promise(J=>setTimeout(J,10)),_++;if(!y())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let _;return W?(b.debug("Using cached discovery data for virtual module"),_=W):(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 j[o](),W=_,b.debug("Discovery completed for virtual module")),M(_)}catch(_){return b.error(`${e} virtual module (${F}) failed to load: ${_.message}`),b.error(`Stack: ${_.stack||"No stack trace available"}`),i.generateEmpty({},m,A,P)}},async buildStart(){if(N=!1,!y()){b.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let v=0;for(;!y()&&v<100;)await new Promise(_=>setTimeout(_,10)),v++;if(!y())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let v=await j[o](!W);if(W=v,l&&p==="routes"&&v?.routes)try{let _=Ge(v.routes,{appRoot:C.getAppRoot()}),J=[...v.routes.map(_e=>({path:_e.path,auth:_e.auth,meta:_e.meta})),..._],pe={routes:J,source:v.source||"auto-discovery",totalRoutes:J.length,generatedAt:new Date().toISOString()},Z=C.resolveAppPath(`public/${l}`);await C.write(Z,JSON.stringify(pe,null,2)),b.debug(`Generated route manifest: public/${l}`)}catch(_){b.error(`Failed to write route manifest: ${_.message}`)}i.logStats&&i.logStats(v,t,b)}catch(v){b.error(`${e} discovery failed during file scanning: ${v.message}`),b.error(`Stack: ${v.stack||"No stack trace available"}`),W=Q.getEmptyResultWithError(j,v)}finally{N=!0}},configureServer(){N=!0},handleHotUpdate(v){return T?[]:N?ce(v):(b.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!W){b.warn("No cached discovery data for manifest generation - skipping");return}try{let v=Q.generateManifest(W,i.generateManifest);this.emitFile({type:"asset",fileName:l,source:JSON.stringify(v,null,2)}),d&&i.logManifest&&i.logManifest(W,e)}catch(v){b.error(`${e} manifest generation failed: ${v.message}`),b.error(`Stack: ${v.stack||"No stack trace available"}`)}},transform(v,_){return _===F?{code:v,map:null}:null}}}}var jo={generateGlobals:Q.generateGlobals,generateExports:Q.generateExports,generateDefaultExport:Q.generateDefaultExport,wrapVirtualModule:Q.wrapVirtualModule,generateInspectionHeader:Q.generateInspectionHeader,validateTemplates:Q.validateTemplates,createTemplateConfig:Q.createTemplateConfig};G();var ae=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=I(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}};G();var Re={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Be=class extends ae{constructor(e,t={}){super(e,{assets:oe.assets.fallback,assetPatterns:oe.assets.patterns,frameworkPackage:tt.package,assetsPath:tt.assetsPath,modernFormats:oe.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(Fe.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(`${Fe.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(`${Fe.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(Fe.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 _renderOgImage(e,t){let{width:s,height:r}=await e(t).metadata(),o=Math.min(Re.logoWidth/s,Re.logoHeight/r),a=await e(t,{density:Math.ceil(72*o)}).resize(Re.logoWidth,Re.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:Re.width,height:Re.height,channels:4,background:Re.background}}).composite([{input:a}]).png().toBuffer()}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 p of r){let g=`${s}/${p.name}`;if(this.pathResolver.pathExists(g)){i.push(p.name);continue}try{let f=c.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),m;p.format==="ico"?m=await f.toFormat("png").toBuffer():m=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(`public/${p.name}`,m),a.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),i.push(p.name)}}let u=ke.slice(1);if(this.pathResolver.pathExists(`${s}/${u}`))i.push(u);else try{let p=await this._renderOgImage(c.default,t);await this.pathResolver.write(`public/${u}`,p),a.push(u)}catch(p){this.logger.debug(`Failed to generate ${u}: ${p.message}`),i.push(u)}}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}}}};B();var Mt={data:null},Zs={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`// ${L.assets} - Generated asset manifest
53
+ `),J}function U(y){let D=y.replace(/\\/g,"/");if(A||D.includes("/node_modules/")||D.includes("/.git/")||D.includes("/dist/")||D.includes("/build/")||D.includes("/coverage/")||D.includes("/.vite/")||D.includes("/.turbo/")||D.endsWith(".d.ts")||D.endsWith(".tsbuildinfo")||D.endsWith(".map")||D.endsWith(".css.map")||D.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(D))return!1;let J=L.getRelativePath(D);if(J.startsWith("packages/"))return!1;let ge=J.startsWith("src/")&&/\.(ts|tsx)$/.test(J);return ge?Array.isArray(a)&&a.length>0?a.some(X=>typeof X=="function"?X(D):typeof X=="string"?X.startsWith("**/")?D.endsWith(X.slice(3)):D.endsWith(X):!1):ge:!1}function ue(y){if(A)return w.debug("Virtual modules are static - HMR disabled"),[];let D=Date.now();return Pe?(w.debug("HMR already in progress, skipping update"),[]):D-ce<S?(ve||(ve=!0,q=setTimeout(()=>{ve=!1,ce=Date.now(),_e(y)},S)),[]):(ce=D,_e(y))}function _e(y){let D=Date.now();if(k===y.file&&D-ce<100)return w.debug(`Same file processed too recently: ${y.file}`),[];if(!U(y.file))return w.debug(`Skipping irrelevant file change: ${y.file}`),[];w.debug(`Relevant file changed: ${y.file}`),Pe=!0,k=y.file;try{let J=Date.now()-(W?.timestamp||0);if(J<E&&W){w.debug(`Using cached discovery data (age: ${J}ms)`);let X=y.server.moduleGraph.getModuleById(F);return X&&y.server.reloadModule(X),[]}M.clearCache();let ge=y.server.moduleGraph.getModuleById(F);return ge&&y.server.reloadModule(ge),[]}finally{Pe=!1,setTimeout(()=>{k===y.file&&(k=null)},200)}}return{name:e,enforce:"pre",configResolved(y){z=y.root,Z=y.command==="serve",d&&w.debug(`${t} ${e} initialized`),Z&&w.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(m)||y.optimizeDeps.exclude.push(m),y},resolveId(y){return y===m?(w.debug(`Resolving virtual module: ${y}`),{id:F,moduleSideEffects:!0}):null},async load(y){if(y!==F)return null;if(w.debug(`Loading virtual module: ${y}`),!b()){w.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let D=0;for(;!b()&&D<100;)await new Promise(J=>setTimeout(J,10)),D++;if(!b())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let D;return W?(w.debug("Using cached discovery data for virtual module"),D=W):(w.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.`),D=await M[o](),W=D,w.debug("Discovery completed for virtual module")),I(D)}catch(D){return w.error(`${e} virtual module (${F}) failed to load: ${D.message}`),w.error(`Stack: ${D.stack||"No stack trace available"}`),i.generateEmpty({},d,N,$)}},async buildStart(){if(O=!1,!b()){w.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let y=0;for(;!b()&&y<100;)await new Promise(D=>setTimeout(D,10)),y++;if(!b())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let y=await M[o](!W);if(W=y,l&&p==="routes"&&y?.routes)try{let D=He(y.routes,{appRoot:L.getAppRoot()}),J=[...y.routes.map(ke=>({path:ke.path,auth:ke.auth,meta:ke.meta})),...D],ge={routes:J,source:y.source||"auto-discovery",totalRoutes:J.length,generatedAt:new Date().toISOString()},X=L.resolveAppPath(`public/${l}`);await L.write(X,JSON.stringify(ge,null,2)),w.debug(`Generated route manifest: public/${l}`)}catch(D){w.error(`Failed to write route manifest: ${D.message}`)}i.logStats&&i.logStats(y,t,w)}catch(y){w.error(`${e} discovery failed during file scanning: ${y.message}`),w.error(`Stack: ${y.stack||"No stack trace available"}`),W=ee.getEmptyResultWithError(M,y)}finally{O=!0}},configureServer(){O=!0},handleHotUpdate(y){return A?[]:O?ue(y):(w.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!W){w.warn("No cached discovery data for manifest generation - skipping");return}try{let y=ee.generateManifest(W,i.generateManifest);this.emitFile({type:"asset",fileName:l,source:JSON.stringify(y,null,2)}),P&&i.logManifest&&i.logManifest(W,e)}catch(y){w.error(`${e} manifest generation failed: ${y.message}`),w.error(`Stack: ${y.stack||"No stack trace available"}`)}},transform(y,D){return D===F?{code:y,map:null}:null}}}}var vn={generateGlobals:ee.generateGlobals,generateExports:ee.generateExports,generateDefaultExport:ee.generateDefaultExport,wrapVirtualModule:ee.wrapVirtualModule,generateInspectionHeader:ee.generateInspectionHeader,validateTemplates:ee.validateTemplates,createTemplateConfig:ee.createTemplateConfig};G();var ie=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}};G();var Re={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Je=class extends ie{constructor(e,t={}){super(e,{assets:ne.assets.fallback,assetPatterns:ne.assets.patterns,frameworkPackage:ot.package,assetsPath:ot.assetsPath,modernFormats:ne.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(Le.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(`${Le.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(`${Le.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(Le.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 _renderOgImage(e,t){let{width:s,height:r}=await e(t).metadata(),o=Math.min(Re.logoWidth/s,Re.logoHeight/r),a=await e(t,{density:Math.ceil(72*o)}).resize(Re.logoWidth,Re.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:Re.width,height:Re.height,channels:4,background:Re.background}}).composite([{input:a}]).png().toBuffer()}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(f){this.logger.debug(`Failed to copy ${c.name}: ${f.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 p of r){let f=`${s}/${p.name}`;if(this.pathResolver.pathExists(f)){i.push(p.name);continue}try{let g=u.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),d;p.format==="ico"?d=await g.toFormat("png").toBuffer():d=await g.toFormat(p.format).toBuffer(),await this.pathResolver.write(`public/${p.name}`,d),a.push(p.name)}catch(g){this.logger.debug(`Failed to generate ${p.name}: ${g.message}`),i.push(p.name)}}let c=De.slice(1);if(this.pathResolver.pathExists(`${s}/${c}`))i.push(c);else try{let p=await this._renderOgImage(u.default,t);await this.pathResolver.write(`public/${c}`,p),a.push(c)}catch(p){this.logger.debug(`Failed to generate ${c}: ${p.message}`),i.push(c)}}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 Gt={data:null},gr={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
54
54
  const assetManifest = ${JSON.stringify(s,null,2)};
55
55
  const assetStats = ${JSON.stringify(i,null,2)};
56
56
 
@@ -120,7 +120,7 @@ export default {
120
120
  getManifest,
121
121
  getAllAssets
122
122
  };
123
- `},generateEmpty:(n,e,t,s="assets")=>{let r={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${L.assets} - Empty asset manifest
123
+ `},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
124
124
  const assetManifest = {
125
125
  logo: { optimal: null, fallback: null },
126
126
  favicon: { optimal: null, fallback: null },
@@ -219,7 +219,7 @@ export default discoveredAssets;
219
219
  `:`/**
220
220
  * Generated Asset Discovery Results
221
221
  * Generated at: ${new Date().toISOString()}
222
- * Import from '${L.assets}'
222
+ * Import from '${j.assets}'
223
223
  */
224
224
 
225
225
  export const discoveredAssets = ${JSON.stringify(e,null,2)};
@@ -236,14 +236,14 @@ export const assetStats = {
236
236
  };
237
237
 
238
238
  export default discoveredAssets;
239
- `},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`))}},Xs=[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 Lt(n={}){let e=de({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:L.assets,DiscoveryClass:Be,discoveryMethod:"discoverAssets",filePatterns:Xs,templates:Zs,manifestFileName:ge.manifests.asset,configKey:"assets"})(n),t=$.getInstance(),s=I("asset-plugin",n.debug,n.verbose),r=e.buildStart;return e.buildStart=async function(...o){r&&await r.apply(this,o)},e}G();var jt=L.blog,zt="\0"+jt;function Ut(){return{name:"dndev-vite-blog",resolveId(n){if(n===jt)return zt},load(n){if(n===zt)return`
239
+ `},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`))}},fr=[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 Bt(n={}){let e=me({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:j.assets,DiscoveryClass:Je,discoveryMethod:"discoverAssets",filePatterns:fr,templates:gr,manifestFileName:fe.manifests.asset,configKey:"assets"})(n),t=_.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}G();var Ht=j.blog,Vt="\0"+Ht;function Jt(){return{name:"dndev-vite-blog",resolveId(n){if(n===Ht)return Vt},load(n){if(n===Vt)return`
240
240
  const files = import.meta.glob('/src/content/blog/*.md', {
241
241
  query: '?raw',
242
242
  import: 'default',
243
243
  eager: true,
244
244
  });
245
245
  export default files;
246
- `}}}import{loadEnv as Qs}from"vite";G();var Wt={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 Wt.generateEmpty(n,e,void 0,t);let o={totalVars:Object.keys(s).length,mode:r,source:n.source,generatedAt:new Date().toISOString()};return`// ${L.env} - Generated environment variables
246
+ `}}}import{loadEnv as dr}from"vite";G();var qt={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 qt.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
247
247
 
248
248
  const envData = ${JSON.stringify(s,null,2)};
249
249
  const envManifest = ${JSON.stringify(o,null,2)};
@@ -283,7 +283,7 @@ export const source = '${n.source}';
283
283
 
284
284
  // Default export
285
285
  export default envData;
286
- `},generateEmpty:(n,e,t,s="env")=>{let r={totalVars:0,mode:n.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${L.env} - Empty environment data
286
+ `},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
287
287
 
288
288
  const envData = {};
289
289
  const envManifest = ${JSON.stringify(r,null,2)};
@@ -322,20 +322,21 @@ export const source = 'empty';
322
322
 
323
323
  export default envData;
324
324
  `},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(`
325
- `)},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`)}},nt=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={...Qs(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 Gt(n={}){return de({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:L.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:Wt,manifestFileName:ge.manifests.env,configKey:"env",createDiscovery:(e,t)=>new nt(e,{...t,mode:n.mode||t.mode||"development"})})({...n,disableHmr:!0})}G();G();function at(n){let e=new Set(Object.keys(Ce)),t=new Set(["latin"]);for(let o of n||[]){let a=xt[o];if(a)for(let i of a)t.add(i)}let s=[],r=new Set;for(let o of e){let a=Ce[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 Bt(n){return n.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}G();B();G();function er(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[c,u]of Object.entries(l.peerDependenciesMeta))u?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function tr(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 sr(n){let e=ve.optionalFeatures||[],t=er(n),s=tr(n);return[...new Set([...e,...t,...s])]}function rr(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 or(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 Ve(n){let e=sr(n),t=[],s=[],r=$.getInstance(),o=rr(n);for(let a of e)a.startsWith("@donotdev/")?o.has(a)?s.push(a):t.push(a):o.has(a)&&or(a,n,r)?s.push(a):t.push(a);return{missing:t,installed:s}}var $e=class n extends ae{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:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[s,r]of Object.entries(e)){for(let o of Object.keys(r))t.includes(o)||delete r[o];Object.keys(r).length===0&&delete e[s]}}_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=We("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(E=>{let N=E.endsWith(".json")?E:`${E}/*_*.json`;return this.pathResolver.resolveAppPath(N)});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=(E,N)=>{let M=this.pathResolver.normalizePath(E),z=this.pathResolver.normalizePath(N);return M.startsWith(z)?M.slice(z.length+1):M},m=a.map(E=>f(E,t)),S=[...i,...l].map(E=>f(E,t)),x=c.map(E=>f(E,s)),R=u.map(E=>f(E,s)),k={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},T=await this.pathResolver._globWithNormalization(m,k),D=await this.pathResolver._globWithNormalization(S,k),A={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(E=>E!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(A.ignore)}`);let P=await this.pathResolver._globWithNormalization(x,A),b=await this.pathResolver._globWithNormalization(R,A);this.logger.debug(`Found ${T.length} eager, ${D.length} lazy, ${P.length} framework eager, ${b.length} framework lazy files`),P.length>0?this.logger.debug(`Framework eager files (first 3): ${P.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 C=[...new Set([...T,...D,...P,...b])],y=new Set([...T,...P]),w={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:j}=Ve(t),F=new Set(j.filter(E=>E.startsWith("@donotdev/")).map(E=>E.replace("@donotdev/","")));F.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...F].join(", ")}] (packages not installed)`);let U=new Map,se=[...P,...b];for(let E of se){let N=this._processTranslationFile(E,P.includes(E),t);if(N){if(F.has(N.namespace))continue;let M=`${N.namespace}_${N.language}`;U.set(M,N),w.allNamespaces.add(N.namespace),w.supportedLanguages.add(N.language),P.includes(E)&&w.eagerNamespaces.add(N.namespace)}}let q=new Set;for(let E of C){if(se.includes(E))continue;let N=this._processTranslationFile(E,y.has(E),t);if(N){let{namespace:M,language:z,importPath:ce,content:Ee}=N,v=`${N.namespace}_${N.language}`;if(U.has(v)){let _=U.get(v);N.content=this._mergeTranslations(_.content,Ee)}w.allNamespaces.add(M),w.supportedLanguages.add(z),q.add(z),y.has(E)&&w.eagerNamespaces.add(M),w.mapping[M]||(w.mapping[M]={}),w.mapping[M][z]=ce,N.content&&(w.content[M]||(w.content[M]={}),w.content[M][z]=N.content),w.files.push({path:E,relativePath:this.pathResolver.getRelativePath(E),namespace:M,language:z,eager:y.has(E),size:N.content?JSON.stringify(N.content).length:0})}}for(let[E,N]of U){let M=E.lastIndexOf("_"),z=E.slice(0,M),ce=E.slice(M+1);q.size>0&&!q.has(ce)||(!w.mapping[z]||!w.mapping[z][ce])&&(w.mapping[z]||(w.mapping[z]={}),w.mapping[z][ce]=N.importPath,w.content[z]||(w.content[z]={}),w.content[z][ce]=N.content,w.files.push({path:N.absolutePath,relativePath:this.pathResolver.getRelativePath(N.absolutePath),namespace:z,language:ce,eager:w.eagerNamespaces.has(z),size:N.content?JSON.stringify(N.content).length:0}))}let le=q.size>0?[...q].sort():[this.options.fallbackLanguage],he=this._getLanguageAllowlist(),W=le;if(he){let E=le.filter(M=>he.includes(M));W=E.length>0?E:[this.options.fallbackLanguage],this._restrictByLanguage(w.mapping,W),this._restrictByLanguage(w.content,W),w.files=w.files.filter(M=>W.includes(M.language));let N=new Set(Object.keys(w.mapping));w.allNamespaces=new Set([...w.allNamespaces].filter(M=>N.has(M))),w.eagerNamespaces=new Set([...w.eagerNamespaces].filter(M=>N.has(M))),this.logger.debug(`I18n restricted by i18n.only [${he.join(", ")}]: languages [${W.join(", ")}], namespaces ${N.size}`)}let Pe=[...new Set(W.map(E=>n.LANGUAGE_FLAG_OVERRIDES[E]||E))];return{mapping:w.mapping,content:w.content,eagerNamespaces:[...w.eagerNamespaces].sort(),allNamespaces:[...w.allNamespaces].sort(),supportedLanguages:W,fallbackLanguage:this.options.fallbackLanguage,flagCodes:Pe,files:w.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}};B();var nr=3,it="<!-- DNDEV_FONT_PRELOADS -->",lt=Object.keys(Ce);function Vt(n={}){let{debug:e=!1,i18nOptions:t={}}=n,s=I("font-preload",e,!1),r,o={},a=!1,i=new Set,l=[];return{name:"vite-font-preload-plugin",enforce:"post",configResolved(c){a=c.command==="build",o={root:c.root,base:c.base&&c.base!=="/"?c.base.replace(/\/$/,""):"",outDir:c.build?.outDir??"dist"};try{r=$.getInstance()}catch(u){s.debug(`Font preload: PathResolver not ready: ${u?.message}`)}},async buildStart(){if(!(!a||!r||!r.getAppRoot()))try{let u=[t.fallbackLanguage||"en"];try{let f=await new $e(r,{fallbackLanguage:t.fallbackLanguage||"en",only:t.only}).discoverTranslations();f?.supportedLanguages?.length&&(u=f.supportedLanguages)}catch(g){s.debug(`Font preload: i18n discovery failed, using 'en': ${g?.message}`)}let p=at(u);i=p.stems,s.debug(`Font filter: ${p.fontStems.size} font(s), ${p.subsets.size} subset(s), ${i.size} allowed stem(s)`)}catch(u){s.debug(`Font preload: discovery failed, using defaults: ${u?.message}`),i=at([t.fallbackLanguage||"en"]).stems}},generateBundle(c,u){if(i.size===0)return;let p=0,g=0;for(let d of Object.keys(u)){if(u[d].type!=="asset")continue;let x=d.toLowerCase();d.endsWith(".woff")?lt.some(R=>x.includes(R))&&(delete u[d],p++):d.endsWith(".woff2")&&lt.some(k=>x.includes(k))&&(Array.from(i).some(T=>x.includes(T))||(delete u[d],g++))}s.debug(`Font filter: deleted ${p} .woff + ${g} .woff2 from bundle`);for(let[d,S]of Object.entries(u)){if(S.type!=="asset"||!d.endsWith(".css")||typeof S.source!="string")continue;let x=S.source,R=x.replace(/@font-face\s*\{[\s\S]*?\}/g,k=>lt.some(A=>k.includes(A))?Array.from(i).some(A=>k.includes(A))?Bt(k):"":k);R!==x&&(S.source=R)}let f=o.base||"",m=[];for(let[d,S]of Object.entries(u)){if(S.type!=="asset"||!d.endsWith(".woff2"))continue;let x=d.toLowerCase();if(Array.from(i).some(R=>x.includes(R))){let R=f?`${f}/${d}`:`/${d}`;m.push(R)}}l=m.slice(0,nr)},writeBundle(){if(!a||!l.length)return;let c=r||$.getInstance(),u=o.root||process.cwd(),p=o.outDir||"dist",g=c.resolvePath(`${p}/index.html`,u);try{if(!c.pathExists(g)){s.debug(`Font preload: index.html not found at ${g}`);return}let f=c.readSync(g,{format:"text"}),m=l.map(d=>`<link rel="preload" as="font" href="${d}" type="font/woff2" crossorigin="anonymous" />`).join(`
326
- `);if(f.includes(it))f=f.replace(it,`${it}
327
- ${m}`);else{let d=f.indexOf("<!-- Fonts:"),S=d!==-1?f.indexOf("-->",d)+3:f.indexOf("</head>");S!==-1&&(f=f.slice(0,S)+`
328
- ${m}`+f.slice(S))}c.writeSync(g,f,{overwrite:!0}),s.debug(`Font preload: injected ${l.length} link(s)`)}catch(f){s.debug(`Font preload: write failed: ${f?.message}`)}}}}G();B();var Ht={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 x of p)c[x]&&(g[x]=c[x]);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[x,R]of Object.entries(r)){if(o.includes(x))continue;let k=[];for(let T of Object.keys(R))k.push(` '${T}': () => import('virtual:i18n-lazy-${x}-${T}')`);k.length>0&&d.push(` '${x}': {
329
- ${k.join(`,
325
+ `)},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`)}},ct=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={...dr(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 Yt(n={}){return me({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:j.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:qt,manifestFileName:fe.manifests.env,configKey:"env",createDiscovery:(e,t)=>new ct(e,{...t,mode:n.mode||t.mode||"development"})})({...n,disableHmr:!0})}G();var mr=["--font-family","--font-headline","--font-mono"],Fe=":root",hr=/\/\*[\s\S]*?\*\//g,vr=/([^{}]+)\{([^{}]*)\}/g,yr=/^(?::root|html|:where\(:root\))$/,br=/^(?::root|html)?\.([a-z][\w-]*)$/i,wr=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/;function Zt(n){let e=[],t=0,s="",r=0;for(let o=0;o<n.length;o++){let a=n[o];s?a===s&&(s=""):a==='"'||a==="'"?s=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(n.slice(r,o)),r=o+1)}return e.push(n.slice(r)),e.map(o=>o.trim())}function xr(n){if(yr.test(n))return Fe;let e=br.exec(n);return e?e[1]:null}function Kt(n){let e=new Map,t=n.replace(hr,"");for(let[,s,r]of t.matchAll(vr)){let o=s.split(";").pop(),a=Zt(o).map(xr).filter(i=>i!==null);if(a.length!==0)for(let i of r.split(";")){let l=i.indexOf(":");if(l===-1)continue;let u=i.slice(0,l).trim();if(!u.startsWith("--"))continue;let c=i.slice(l+1).replace(/!important\s*$/,"").trim();for(let p of a)e.has(p)||e.set(p,new Map),e.get(p).set(u,c)}}return e}function ut(n,e,t){let s=Zt(n)[0];if(!s)return null;let r=wr.exec(s);if(r){let[,o,a]=r;return e.has(o)&&!t.has(o)?ut(e.get(o),e,new Set([...t,o])):a===void 0?null:ut(a,e,t)}return s.replace(/^['"]|['"]$/g,"").trim()}function Xt({frameworkCss:n,appCss:e}){let t=Kt(n),s=Kt(e.join(`
326
+ `)),r=new Set([Fe,...t.keys(),...s.keys()]),o=new Set;for(let a of r){let i=new Map([...t.get(Fe)??[],...s.get(Fe)??[],...a===Fe?[]:t.get(a)??[],...a===Fe?[]:s.get(a)??[]]);for(let l of mr){if(!i.has(l))continue;let u=ut(i.get(l),i,new Set([l]));u&&o.add(u)}}return[...o]}var Sr=new Map(Object.entries($t).map(([n,e])=>[n.toLowerCase(),e]));function Qt({families:n,locales:e=[]}){if(!Array.isArray(n))throw new Error("resolveFontManifest: families is required (ThemeDiscovery fontFamilies)");let t=new Set;for(let o of n){let a=Sr.get(o.toLowerCase());a&&t.add(a)}let s=new Set(["latin"]);for(let o of e)for(let a of _t[o]??[])s.add(a);let r=new Set;for(let o of t)for(let a of s)for(let i of it[o])r.add(`${o}-${a}-${i}-normal`);return{fontStems:t,subsets:s,stems:r}}function pt(n){let e=n.split(/[/\\]/).pop().toLowerCase();for(let t of Object.keys(it)){if(!e.startsWith(`${t}-`))continue;let s=new RegExp(`^${t}-[a-z-]+?-\\d+-(?:normal|italic)`).exec(e);if(s)return s[0]}return null}function es(n){return n.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}G();B();G();function Pr(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 Rr(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 Er(n){let e=ye.optionalFeatures||[],t=Pr(n),s=Rr(n);return[...new Set([...e,...t,...s])]}function $r(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 _r(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 qe(n){let e=Er(n),t=[],s=[],r=_.getInstance(),o=$r(n);for(let a of e)a.startsWith("@donotdev/")?o.has(a)?s.push(a):t.push(a):o.has(a)&&_r(a,n,r)?s.push(a):t.push(a);return{missing:t,installed:s}}var Ee=class n extends ie{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:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[s,r]of Object.entries(e)){for(let o of Object.keys(r))t.includes(o)||delete r[o];Object.keys(r).length===0&&delete e[s]}}_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=Ve("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(k=>{let O=k.endsWith(".json")?k:`${k}/*_*.json`;return this.pathResolver.resolveAppPath(O)});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),f=this.pathResolver.normalizePath(s),g=(k,O)=>{let I=this.pathResolver.normalizePath(k),U=this.pathResolver.normalizePath(O);return I.startsWith(U)?I.slice(U.length+1):I},d=a.map(k=>g(k,t)),m=[...i,...l].map(k=>g(k,t)),S=u.map(k=>g(k,s)),E=c.map(k=>g(k,s)),v={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},A=await this.pathResolver._globWithNormalization(d,v),R=await this.pathResolver._globWithNormalization(m,v),N={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(k=>k!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(N.ignore)}`);let $=await this.pathResolver._globWithNormalization(S,N),w=await this.pathResolver._globWithNormalization(E,N);this.logger.debug(`Found ${A.length} eager, ${R.length} lazy, ${$.length} framework eager, ${w.length} framework lazy files`),$.length>0?this.logger.debug(`Framework eager files (first 3): ${$.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${u.join(", ")}`),w.length>0?this.logger.debug(`Framework lazy files (first 3): ${w.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let L=[...new Set([...A,...R,...$,...w])],b=new Set([...A,...$]),x={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:M}=qe(t),F=new Set(M.filter(k=>k.startsWith("@donotdev/")).map(k=>k.replace("@donotdev/","")));F.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...F].join(", ")}] (packages not installed)`);let z=new Map,Z=[...$,...w];for(let k of Z){let O=this._processTranslationFile(k,$.includes(k),t);if(O){if(F.has(O.namespace))continue;let I=`${O.namespace}_${O.language}`;z.set(I,O),x.allNamespaces.add(O.namespace),x.supportedLanguages.add(O.language),$.includes(k)&&x.eagerNamespaces.add(O.namespace)}}let q=new Set;for(let k of L){if(Z.includes(k))continue;let O=this._processTranslationFile(k,b.has(k),t);if(O){let{namespace:I,language:U,importPath:ue,content:_e}=O,y=`${O.namespace}_${O.language}`;if(z.has(y)){let D=z.get(y);O.content=this._mergeTranslations(D.content,_e)}x.allNamespaces.add(I),x.supportedLanguages.add(U),q.add(U),b.has(k)&&x.eagerNamespaces.add(I),x.mapping[I]||(x.mapping[I]={}),x.mapping[I][U]=ue,O.content&&(x.content[I]||(x.content[I]={}),x.content[I][U]=O.content),x.files.push({path:k,relativePath:this.pathResolver.getRelativePath(k),namespace:I,language:U,eager:b.has(k),size:O.content?JSON.stringify(O.content).length:0})}}for(let[k,O]of z){let I=k.lastIndexOf("_"),U=k.slice(0,I),ue=k.slice(I+1);q.size>0&&!q.has(ue)||(!x.mapping[U]||!x.mapping[U][ue])&&(x.mapping[U]||(x.mapping[U]={}),x.mapping[U][ue]=O.importPath,x.content[U]||(x.content[U]={}),x.content[U][ue]=O.content,x.files.push({path:O.absolutePath,relativePath:this.pathResolver.getRelativePath(O.absolutePath),namespace:U,language:ue,eager:x.eagerNamespaces.has(U),size:O.content?JSON.stringify(O.content).length:0}))}let ce=q.size>0?[...q].sort():[this.options.fallbackLanguage],ve=this._getLanguageAllowlist(),W=ce;if(ve){let k=ce.filter(I=>ve.includes(I));W=k.length>0?k:[this.options.fallbackLanguage],this._restrictByLanguage(x.mapping,W),this._restrictByLanguage(x.content,W),x.files=x.files.filter(I=>W.includes(I.language));let O=new Set(Object.keys(x.mapping));x.allNamespaces=new Set([...x.allNamespaces].filter(I=>O.has(I))),x.eagerNamespaces=new Set([...x.eagerNamespaces].filter(I=>O.has(I))),this.logger.debug(`I18n restricted by i18n.only [${ve.join(", ")}]: languages [${W.join(", ")}], namespaces ${O.size}`)}let Pe=[...new Set(W.map(k=>n.LANGUAGE_FLAG_OVERRIDES[k]||k))];return{mapping:x.mapping,content:x.content,eagerNamespaces:[...x.eagerNamespaces].sort(),allNamespaces:[...x.allNamespaces].sort(),supportedLanguages:W,fallbackLanguage:this.options.fallbackLanguage,flagCodes:Pe,files:x.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 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}};G();G();var Ce=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:{...at.selectors,...this.options.customPatterns?.selectors},themes:{...at.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 f=c.match(this.patterns.themes.themeIcon),g=c.match(this.patterns.themes.themeIsDark),d={name:u,displayName:p,isDark:g?g[1]==="1":!1,meta:{icon:f?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${u} (${p})`),r.push(d),s.themes.set(u,{name:u,displayName:p,isDark:d.isDark,file:a,variables:new Set,meta:d.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${a}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}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 ts="@donotdev/components/styles",kr=/@import\s+['"](\.[^'"]+)['"]\s*;/g,$e=class extends ie{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new Ce(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);let r=await this._processConsumerFiles(s),o=this._serializeThemes(),a=Xt({frameworkCss:this._readFrameworkTokenCss(),appCss:r});return this.logger.debug("Theme font families:",a),this.logger.debug(`Discovered ${o.length} themes:`,o.map(i=>i.name)),{themes:o,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(),fontFamilies:a}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return lt.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){let t=[];for(let s of e)try{let r=await this.pathResolver.read(s,{format:"text"});t.push(r);let o=this.pathResolver.normalizePath(s);this.cssExtractor.extractThemes(r,o,this.discovered),this.cssExtractor.extractVariables(r,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(o)}`)}catch(r){this.logger.debug(`Error scanning consumer file ${s}: ${r.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(ts,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw new Error(`Theme discovery: cannot resolve ${ts} (framework font defaults)`);let t=new Set,s=r=>{if(t.has(r))return"";t.add(r);let o=this.pathResolver.readSync(r,{format:"text"});if(typeof o!="string")throw new Error(`Theme discovery: cannot read ${r}`);let a=this.pathResolver.getDirname(r);return o.replace(kr,(i,l)=>s(this.pathResolver.resolvePath(l,a)))};return s(e)}_addEssentialThemes(){lt.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}))}};B();var Dr=3,gt="<!-- DNDEV_FONT_PRELOADS -->",Ar=/url\(\s*['"]?([^'")]+)['"]?\s*\)/g;function ss(n={}){let{debug:e=!1,i18nOptions:t={}}=n,s=C("font-preload",e,!1),r,o={},a=!1,i=null,l=[];return{name:"vite-font-preload-plugin",enforce:"post",configResolved(u){a=u.command==="build",o={root:u.root,base:u.base&&u.base!=="/"?u.base.replace(/\/$/,""):"",outDir:u.build?.outDir??"dist"};try{r=_.getInstance()}catch(c){s.debug(`Font preload: PathResolver not ready: ${c?.message}`)}},async buildStart(){if(!a||!r||!r.getAppRoot())return;let c=[t.fallbackLanguage||"en"];try{let P=await new Ee(r,{fallbackLanguage:t.fallbackLanguage||"en",only:t.only}).discoverTranslations();P?.supportedLanguages?.length&&(c=P.supportedLanguages)}catch(d){s.debug(`Font preload: i18n discovery failed, using 'en': ${d?.message}`)}let p=new $e(null,r,{debug:e}),{fontFamilies:f}=await p.discoverThemes(),g=Qt({families:f,locales:c});i=g.stems,s.debug(`Font filter: ${g.fontStems.size} font(s) [${[...g.fontStems].join(", ")}], ${g.subsets.size} subset(s), ${i.size} allowed stem(s)`)},generateBundle(u,c){if(!i)return;let p=S=>pt(S)!==null,f=S=>i.has(pt(S)),g=0,d=0;for(let S of Object.keys(c))c[S].type!=="asset"||!p(S)||(S.endsWith(".woff")?(delete c[S],g++):S.endsWith(".woff2")&&!f(S)&&(delete c[S],d++));s.debug(`Font filter: deleted ${g} .woff + ${d} .woff2 from bundle`);for(let[S,E]of Object.entries(c)){if(E.type!=="asset"||!S.endsWith(".css")||typeof E.source!="string")continue;let v=E.source,A=v.replace(/@font-face\s*\{[\s\S]*?\}/g,R=>{let N=[...R.matchAll(Ar)].map($=>$[1]);return N.some(p)?N.some(f)?es(R):"":R});A!==v&&(E.source=A)}let P=o.base||"",m=[];for(let[S,E]of Object.entries(c)){if(E.type!=="asset"||!S.endsWith(".woff2")||!f(S))continue;let v=P?`${P}/${S}`:`/${S}`;m.push(v)}l=m.slice(0,Dr)},writeBundle(){if(!a||!l.length)return;let u=r||_.getInstance(),c=o.root||process.cwd(),p=o.outDir||"dist",f=u.resolvePath(`${p}/index.html`,c);try{if(!u.pathExists(f)){s.debug(`Font preload: index.html not found at ${f}`);return}let g=u.readSync(f,{format:"text"}),d=l.map(P=>`<link rel="preload" as="font" href="${P}" type="font/woff2" crossorigin="anonymous" />`).join(`
327
+ `);if(g.includes(gt))g=g.replace(gt,`${gt}
328
+ ${d}`);else{let P=g.indexOf("<!-- Fonts:"),m=P!==-1?g.indexOf("-->",P)+3:g.indexOf("</head>");m!==-1&&(g=g.slice(0,m)+`
329
+ ${d}`+g.slice(m))}u.writeSync(f,g,{overwrite:!0}),s.debug(`Font preload: injected ${l.length} link(s)`)}catch(g){s.debug(`Font preload: write failed: ${g?.message}`)}}}}G();B();var rs={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,f={};for(let S of p)u[S]&&(f[S]=u[S]);let g=[...new Set([...o,...Object.keys(u)])],d={mapping:r,languages:a,eager:s?g:o,fallback:i,content:f,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},P=[];if(!s)for(let[S,E]of Object.entries(r)){if(o.includes(S))continue;let v=[];for(let A of Object.keys(E))v.push(` '${A}': () => import('virtual:i18n-lazy-${S}-${A}')`);v.length>0&&P.push(` '${S}': {
330
+ ${v.join(`,
330
331
  `)}
331
- }`)}let S=d.length>0?`{
332
- ${d.join(`,
332
+ }`)}let m=P.length>0?`{
333
+ ${P.join(`,
333
334
  `)}
334
- }`:"{}";return`// ${L.i18n} - Generated by @donotdev/config
335
+ }`:"{}";return`// ${j.i18n} - Generated by @donotdev/config
335
336
  // Generated at: ${new Date().toISOString()}
336
337
 
337
338
  // ===== STATIC EXPORTS =====
338
- export const I18N_CONFIG = ${JSON.stringify(m,null,2)};
339
+ export const I18N_CONFIG = ${JSON.stringify(d,null,2)};
339
340
  export const LANGUAGES = ${JSON.stringify(a,null,2)};
340
341
  export const FALLBACK_LANGUAGE = '${i}';
341
342
  export const EAGER_NAMESPACES = ${JSON.stringify(o,null,2)};
@@ -344,7 +345,7 @@ const i18nPluginConfig = I18N_CONFIG;
344
345
 
345
346
  // ===== LAZY LOADERS =====
346
347
  // Static import() calls \u2014 Vite bundles each JSON as a separate async chunk
347
- const _lazyLoaders = ${S};
348
+ const _lazyLoaders = ${m};
348
349
 
349
350
  // ============================================================================
350
351
  // INITIALIZE DnDev CONFIG FOUNDATION
@@ -456,7 +457,7 @@ export default {
456
457
  getInlineContent,
457
458
  };
458
459
 
459
- `},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`// ${L.i18n} - Empty i18n configuration
460
+ `},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
460
461
  // No translation files found - using fallback configuration
461
462
  // Generated at: ${new Date().toISOString()}
462
463
 
@@ -576,9 +577,9 @@ export default {
576
577
  files: translationFiles,
577
578
  manifest: i18nManifest,
578
579
  };
579
- `},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`)}},ar=[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=$.getInstance(),r={...Ae.discovery,fallbackLanguage:n.fallbackLanguage||"en",...n},o=new $e(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[S,x]of Object.entries(d))t.set(`virtual:i18n-lazy-${m}-${S}`,x)}let i={...Ht,generateModule:(p,g,f)=>(e||a(p),Ht.generateModule(p,g,f,e))};return[de({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:L.i18n,DiscoveryClass:$e,discoveryMethod:"discoverTranslations",filePatterns:ar,templates:i,manifestFileName:ge.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(){if(e)return;let p=()=>{let d=s.getAppRoot(),S=s.getRepoRoot();return d&&d!==S},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(e||!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;"}}]}B();function qt(n,e){return e.some(t=>n===t||n.startsWith(t+"/"))}function Yt(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=>qt(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=Ve(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 qt(r,e)?{id:t,syntheticNamedExports:!0}:null}}}function ct(n){return!n||typeof n!="string"?null:n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0]}function ir(n){return!n||typeof n!="string"?!1:!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("\\")&&!n.startsWith("\0")}function lr(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 cr(n,e){if(!n||!e)return null;let t=ct(n);if(!t)return null;let s=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(s)?e.resolveAppPath(`node_modules/${n}`):null}function Kt(n,e,t){return!ir(n)||!lr(e,t)?null:cr(n,t)}B();function Zt(n={}){let{debug:e=!1,verbose:t=!0}=n,s=I("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(Kt(r,o,this.pathResolver)){let i=ct(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}}}B();G();B();function ur(n){return n?String(n).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function ie(n){return n?String(n).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function pr(n,e,t){let s=$.getInstance(),r=new Map,o=`_${e}.json`,a=[s.resolvePath("src/pages/locales",n),s.resolvePath("src/locales",n)];for(let i of a){if(!s.pathExists(i,!0))continue;let l;try{l=s.readdirSync(i)}catch{continue}for(let c of l){if(!c.endsWith(o))continue;let u=c.slice(0,-o.length);if(!r.has(u))try{let p=s.resolvePath(c,i),g=s.readSync(p,{format:"json"});g&&r.set(u,g)}catch(p){t.debug(` Failed to parse locale ${c}: ${p.message}`)}}}return r}function He(n,e,t){let s=n.get(e);if(!s)return;let r=t.split("."),o=s;for(let a of r){if(o==null||typeof o!="object")return;o=o[a]}return o}var Je=class{constructor(e){this.routes=e.routes||[],this.outDir=e.outDir,this.base=e.base||"/",this.appRoot=e.appRoot,this.debug=e.debug||!1,this.logger=e.logger}async run(){let e=Se({appRoot:this.appRoot,logger:this.logger}),t=this.expandRoutes(e);if(t.length===0)return this.logger.warn("No routes to prerender after expansion."),[];let s=$.getInstance(),r=s.resolvePath("index.html",this.outDir),o=s.readSync(r);if(!o)return this.logger.warn("dist/index.html not found. Skipping prerender."),[];let a="en",i=pr(this.appRoot,a,this.logger);this.debug&&this.logger.debug(` Loaded ${i.size} locale namespace(s) for '${a}'`);let l=this.resolveSiteName(),c=new Map;for(let g of e.routes)g.path&&c.set(g.path,g);let u=process.env.VITE_APP_URL||"",p=[];for(let g of t)try{let f=c.get(g)||{},m=this.resolveRouteSeo(f,g,i,l),d=this.injectMetaTags(o,g,m,u,l);await this.writePrerenderedFile(g,d),this.debug&&this.logger.debug(` ${g} -> "${m.title||"(no title)"}"`),p.push({route:g,ok:!0})}catch(f){this.logger.warn(` Failed: ${g} - ${f.message}`),p.push({route:g,ok:!1,error:f.message})}return p}resolveRouteSeo(e,t,s,r){let o=e.meta||{},a=o.seo||{},i=o.namespace||t.split("/").filter(Boolean)[0]||"home",l=He(s,i,"meta")||{},c=He(s,i,"title"),u=He(s,i,"description"),p=He(s,i,"subtitle"),g;if(l.fullTitle)g=l.fullTitle;else if(a.fullTitle)g=a.fullTitle;else{let R=a.title!==void 0?a.title:c;g=R?`${R} | ${r}`:r}let f=a.description!==void 0?a.description:u||p||null,m=a.image||l.image||ke,d=a.type||l.type||"website",S=a.keywords||l.keywords||null,x=a.noindex||!1;return{title:g,description:f,image:m,type:d,keywords:S,noindex:x}}resolveSiteName(){let e=$.getInstance();try{let t=e.resolvePath("seo-manifest.json",this.outDir),s=e.readSync(t,{format:"json"});if(s?.siteName)return s.siteName}catch{}return process.env.VITE_APP_NAME?process.env.VITE_APP_NAME:""}injectMetaTags(e,t,s,r,o){let a=e,{title:i,description:l,image:c,type:u,keywords:p,noindex:g}=s;i&&(a=a.replace(/<title>[^<]*<\/title>/,`<title>${ur(i)}</title>`)),a=a.replace(/<meta\s+name="description"[^>]*\/?>\s*/gi,""),a=a.replace(/<meta\s+property="og:[^"]*"[^>]*\/?>\s*/gi,""),a=a.replace(/<meta\s+name="twitter:[^"]*"[^>]*\/?>\s*/gi,""),a=a.replace(/<link\s+rel="canonical"[^>]*\/?>\s*/gi,""),a=a.replace(/<meta\s+name="robots"[^>]*\/?>\s*/gi,""),a=a.replace(/<meta\s+name="keywords"[^>]*\/?>\s*/gi,"");let f=[],m=r?`${r.replace(/\/$/,"")}${t}`:"";if(l&&f.push(`<meta name="description" content="${ie(l)}" />`),m&&f.push(`<link rel="canonical" href="${ie(m)}" />`),i&&f.push(`<meta property="og:title" content="${ie(i)}" />`),l&&f.push(`<meta property="og:description" content="${ie(l)}" />`),m&&f.push(`<meta property="og:url" content="${ie(m)}" />`),c){let d=c.startsWith("http")?c:`${(r??"").replace(/\/$/,"")}${c}`;f.push(`<meta property="og:image" content="${ie(d)}" />`),f.push('<meta property="og:image:width" content="1200" />'),f.push('<meta property="og:image:height" content="630" />')}if(u&&f.push(`<meta property="og:type" content="${ie(u)}" />`),o&&f.push(`<meta property="og:site_name" content="${ie(o)}" />`),(i||l||c)&&(f.push('<meta name="twitter:card" content="summary_large_image" />'),i&&f.push(`<meta name="twitter:title" content="${ie(i)}" />`),l&&f.push(`<meta name="twitter:description" content="${ie(l)}" />`),c&&f.push(`<meta name="twitter:image" content="${ie(c)}" />`)),p){let d=Array.isArray(p)?p.join(", "):p;f.push(`<meta name="keywords" content="${ie(d)}" />`)}if(g&&f.push('<meta name="robots" content="noindex, nofollow" />'),f.length>0){let d=f.map(S=>` ${S}`).join(`
580
- `);a=a.replace("</head>",`${d}
581
- </head>`)}return a}expandRoutes(e){let{routes:t,errors:s}=e;if(t.length===0)return s.length>0&&this.logger.warn("Route manifest unavailable. Using explicit routes only."),this.routes.filter(o=>!o.includes("*"));let r=new Set;for(let o of this.routes)if(o.includes("*")){let a=o.replace(/\/?\*.*$/,"");for(let i of t){let l=i.path||i;l.startsWith(a)&&!this.isAuthProtected(i)&&r.add(l)}if(this.debug){let i=[...r].filter(l=>l.startsWith(a));this.logger.debug(` Pattern "${o}" matched ${i.length} route(s)`)}}else{let a=t.find(i=>(i.path||i)===o);a&&this.isAuthProtected(a)?this.logger.warn(` Skipping auth-protected route: ${o}`):a?r.add(o):(r.add(o),this.debug&&this.logger.debug(` Route "${o}" not in manifest, including anyway`))}return[...r]}isAuthProtected(e){return typeof e=="string"?!1:e.auth?.required===!0}async writePrerenderedFile(e,t){let s=$.getInstance(),r;if(e==="/")r=s.resolvePath("index.html",this.outDir);else{let i=e.replace(/^\//,"").replace(/\/$/,"");r=s.resolvePath(`${i}/index.html`,this.outDir)}let o=s.getDirname(r);if(s.ensureDirSync(o),!s.writeSync(r,t,{overwrite:!0}))throw new Error(`writeSync returned false for ${r}`)}};function Xt(n={}){let{routes:e="auto",debug:t,verbose:s,...r}=n;if(Array.isArray(e)&&e.length===0)return{name:"prerender-disabled"};let o=I("Prerender",t,s),a=$.getInstance(),i=null,l=!1;return{name:"dndev-prerender",enforce:"post",configResolved(c){l=c.command==="build",i={root:c.root,outDir:c.build?.outDir||"dist",base:c.base||"/"}},async closeBundle(){if(!i||!l)return;let c=a.getAppRoot(),u=a.resolveAppPath(i.outDir),p=e;if(e==="auto"){let g=Se({appRoot:c,logger:o}),f=It(g.routes),d=Ge(g.routes,{appRoot:c}).map(S=>S.path);if(p=[...new Set([...f,...d])],p.length===0){o.warn("No public static routes found for prerendering.");return}o.debug(`Auto-discovered ${p.length} route(s) to prerender`)}try{let f=await new Je({...r,routes:p,debug:t,outDir:u,base:i.base,appRoot:c,logger:o}).run(),m=f.filter(D=>D.ok).length,d=f.filter(D=>!D.ok),S=f.length,x=f.filter(D=>D.ok&&D.route.startsWith("/blog/")).length,R=m-x,k=[];R>0&&k.push(`${R} static`),x>0&&k.push(`${x} blog`);let T=k.length>0?` (${k.join(", ")})`:"";if(m>0&&o.info(`Prerendered: ${m}/${S} pages${T}`),d.length>0)for(let D of d)o.warn(` Failed: ${D.route} - ${D.error}`)}catch(g){o.warn(`Prerendering failed: ${g.message}`),o.warn("SPA will serve all routes via index.html fallback (no impact on functionality)."),t&&g.stack&&o.debug(g.stack)}}}}import{VitePWA as gr}from"vite-plugin-pwa";var qe=class extends ae{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
580
+ `},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`)}},Nr=[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 ft(n={}){return new Ee(_.getInstance(),os(n))}function os(n={}){return{...Oe.discovery,fallbackLanguage:n.fallbackLanguage||"en",...n}}function ns(n={}){let e=!1,t=new Map,s=_.getInstance(),r=ft(n);function o(c){t.clear();let{content:p,eagerNamespaces:f}=c;for(let[g,d]of Object.entries(p||{}))if(!f.includes(g))for(let[P,m]of Object.entries(d))t.set(`virtual:i18n-lazy-${g}-${P}`,m)}let a={...rs,generateModule:(c,p,f)=>(e||o(c),rs.generateModule(c,p,f,e))};return[me({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:j.i18n,DiscoveryClass:Ee,discoveryMethod:"discoverTranslations",filePatterns:Nr,templates:a,manifestFileName:fe.manifests.i18n,configKey:"i18n",discoveryOptions:os(n)})({...n,hmrSmartDetection:!1}),{name:"dndev-i18n-lazy-loader",enforce:"pre",configResolved(c){e=c.command==="serve"},async buildStart(){if(e)return;let c=()=>{let g=s.getAppRoot(),d=s.getRepoRoot();return g&&g!==d},p=0;for(;!c()&&p<100;)await new Promise(g=>setTimeout(g,10)),p++;if(!c())return;let f=await r.discoverTranslations();o(f)},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),f=t.get(p);return`export default ${JSON.stringify(f||{})};`}}},{name:"dndev-i18n-flag-filter",enforce:"pre",async buildStart(){if(e)return;let c=()=>{let d=s.getAppRoot(),P=s.getRepoRoot();return d&&d!==P},p=0;for(;!c()&&p<100;)await new Promise(d=>setTimeout(d,10)),p++;if(!c())return;let g=(await r.discoverTranslations()).flagCodes||[];this._allowedFlags=new Set(g.map(d=>d.toUpperCase()))},resolveId(c,p){if(e||!p||!c.includes("flag"))return;let f=c.match(/flag([A-Z][A-Z0-9_-]*)\.(tsx|js)$/i);if(!f)return;let g=f[1].toUpperCase();if(g!=="BASE"&&!this._allowedFlags?.has(g))return"\0empty-flag"},load(c){if(c==="\0empty-flag")return"export default () => null;"}}]}B();function as(n,e){return e.some(t=>n===t||n.startsWith(t+"/"))}function is(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=>as(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=qe(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 as(r,e)?{id:t,syntheticNamedExports:!0}:null}}}function dt(n){return!n||typeof n!="string"?null:n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0]}function Or(n){return!n||typeof n!="string"?!1:!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("\\")&&!n.startsWith("\0")}function Tr(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 Fr(n,e){if(!n||!e)return null;let t=dt(n);if(!t)return null;let s=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(s)?e.resolveAppPath(`node_modules/${n}`):null}function ls(n,e,t){return!Or(n)||!Tr(e,t)?null:Fr(n,t)}B();function cs(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=_.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(ls(r,o,this.pathResolver)){let i=dt(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}}}B();G();B();function Cr(n){return n?String(n).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function le(n){return n?String(n).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function Ir(n,e,t){let s=_.getInstance(),r=new Map,o=`_${e}.json`,a=[s.resolvePath("src/pages/locales",n),s.resolvePath("src/locales",n)];for(let i of a){if(!s.pathExists(i,!0))continue;let l;try{l=s.readdirSync(i)}catch{continue}for(let u of l){if(!u.endsWith(o))continue;let c=u.slice(0,-o.length);if(!r.has(c))try{let p=s.resolvePath(u,i),f=s.readSync(p,{format:"json"});f&&r.set(c,f)}catch(p){t.debug(` Failed to parse locale ${u}: ${p.message}`)}}}return r}function Ye(n,e,t){let s=n.get(e);if(!s)return;let r=t.split("."),o=s;for(let a of r){if(o==null||typeof o!="object")return;o=o[a]}return o}var Ke=class{constructor(e){this.routes=e.routes||[],this.outDir=e.outDir,this.base=e.base||"/",this.appRoot=e.appRoot,this.debug=e.debug||!1,this.logger=e.logger}async run(){let e=Te({appRoot:this.appRoot,logger:this.logger}),t=this.expandRoutes(e);if(t.length===0)return this.logger.warn("No routes to prerender after expansion."),[];let s=_.getInstance(),r=s.resolvePath("index.html",this.outDir),o=s.readSync(r);if(!o)return this.logger.warn("dist/index.html not found. Skipping prerender."),[];let a="en",i=Ir(this.appRoot,a,this.logger);this.debug&&this.logger.debug(` Loaded ${i.size} locale namespace(s) for '${a}'`);let l=this.resolveSiteName(),u=new Map;for(let f of e.routes)f.path&&u.set(f.path,f);let c=process.env.VITE_APP_URL||"",p=[];for(let f of t)try{let g=u.get(f)||{},d=this.resolveRouteSeo(g,f,i,l),P=this.injectMetaTags(o,f,d,c,l);await this.writePrerenderedFile(f,P),this.debug&&this.logger.debug(` ${f} -> "${d.title||"(no title)"}"`),p.push({route:f,ok:!0})}catch(g){this.logger.warn(` Failed: ${f} - ${g.message}`),p.push({route:f,ok:!1,error:g.message})}return p}resolveRouteSeo(e,t,s,r){let o=e.meta||{},a=o.seo||{},i=o.namespace||t.split("/").filter(Boolean)[0]||"home",l=Ye(s,i,"meta")||{},u=Ye(s,i,"title"),c=Ye(s,i,"description"),p=Ye(s,i,"subtitle"),f;if(l.fullTitle)f=l.fullTitle;else if(a.fullTitle)f=a.fullTitle;else{let E=a.title!==void 0?a.title:u;f=E?`${E} | ${r}`:r}let g=a.description!==void 0?a.description:c||p||null,d=a.image||l.image||De,P=a.type||l.type||"website",m=a.keywords||l.keywords||null,S=a.noindex||!1;return{title:f,description:g,image:d,type:P,keywords:m,noindex:S}}resolveSiteName(){let e=_.getInstance();try{let t=e.resolvePath("seo-manifest.json",this.outDir),s=e.readSync(t,{format:"json"});if(s?.siteName)return s.siteName}catch{}return process.env.VITE_APP_NAME?process.env.VITE_APP_NAME:""}injectMetaTags(e,t,s,r,o){let a=e,{title:i,description:l,image:u,type:c,keywords:p,noindex:f}=s;i&&(a=a.replace(/<title>[^<]*<\/title>/,`<title>${Cr(i)}</title>`)),a=a.replace(/<meta\s+name="description"[^>]*\/?>\s*/gi,""),a=a.replace(/<meta\s+property="og:[^"]*"[^>]*\/?>\s*/gi,""),a=a.replace(/<meta\s+name="twitter:[^"]*"[^>]*\/?>\s*/gi,""),a=a.replace(/<link\s+rel="canonical"[^>]*\/?>\s*/gi,""),a=a.replace(/<meta\s+name="robots"[^>]*\/?>\s*/gi,""),a=a.replace(/<meta\s+name="keywords"[^>]*\/?>\s*/gi,"");let g=[],d=r?`${r.replace(/\/$/,"")}${t}`:"";if(l&&g.push(`<meta name="description" content="${le(l)}" />`),d&&g.push(`<link rel="canonical" href="${le(d)}" />`),i&&g.push(`<meta property="og:title" content="${le(i)}" />`),l&&g.push(`<meta property="og:description" content="${le(l)}" />`),d&&g.push(`<meta property="og:url" content="${le(d)}" />`),u){let P=u.startsWith("http")?u:`${(r??"").replace(/\/$/,"")}${u}`;g.push(`<meta property="og:image" content="${le(P)}" />`),g.push('<meta property="og:image:width" content="1200" />'),g.push('<meta property="og:image:height" content="630" />')}if(c&&g.push(`<meta property="og:type" content="${le(c)}" />`),o&&g.push(`<meta property="og:site_name" content="${le(o)}" />`),(i||l||u)&&(g.push('<meta name="twitter:card" content="summary_large_image" />'),i&&g.push(`<meta name="twitter:title" content="${le(i)}" />`),l&&g.push(`<meta name="twitter:description" content="${le(l)}" />`),u&&g.push(`<meta name="twitter:image" content="${le(u)}" />`)),p){let P=Array.isArray(p)?p.join(", "):p;g.push(`<meta name="keywords" content="${le(P)}" />`)}if(f&&g.push('<meta name="robots" content="noindex, nofollow" />'),g.length>0){let P=g.map(m=>` ${m}`).join(`
581
+ `);a=a.replace("</head>",`${P}
582
+ </head>`)}return a}expandRoutes(e){let{routes:t,errors:s}=e;if(t.length===0)return s.length>0&&this.logger.warn("Route manifest unavailable. Using explicit routes only."),this.routes.filter(o=>!o.includes("*"));let r=new Set;for(let o of this.routes)if(o.includes("*")){let a=o.replace(/\/?\*.*$/,"");for(let i of t){let l=i.path||i;l.startsWith(a)&&!this.isAuthProtected(i)&&r.add(l)}if(this.debug){let i=[...r].filter(l=>l.startsWith(a));this.logger.debug(` Pattern "${o}" matched ${i.length} route(s)`)}}else{let a=t.find(i=>(i.path||i)===o);a&&this.isAuthProtected(a)?this.logger.warn(` Skipping auth-protected route: ${o}`):a?r.add(o):(r.add(o),this.debug&&this.logger.debug(` Route "${o}" not in manifest, including anyway`))}return[...r]}isAuthProtected(e){return typeof e=="string"?!1:e.auth?.required===!0}async writePrerenderedFile(e,t){let s=_.getInstance(),r;if(e==="/")r=s.resolvePath("index.html",this.outDir);else{let i=e.replace(/^\//,"").replace(/\/$/,"");r=s.resolvePath(`${i}/index.html`,this.outDir)}let o=s.getDirname(r);if(s.ensureDirSync(o),!s.writeSync(r,t,{overwrite:!0}))throw new Error(`writeSync returned false for ${r}`)}};function us(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=_.getInstance(),i=null,l=!1;return{name:"dndev-prerender",enforce:"post",configResolved(u){l=u.command==="build",i={root:u.root,outDir:u.build?.outDir||"dist",base:u.base||"/"}},async closeBundle(){if(!i||!l)return;let u=a.getAppRoot(),c=a.resolveAppPath(i.outDir),p=e;if(e==="auto"){let f=Te({appRoot:u,logger:o}),g=Wt(f.routes),P=He(f.routes,{appRoot:u}).map(m=>m.path);if(p=[...new Set([...g,...P])],p.length===0){o.warn("No public static routes found for prerendering.");return}o.debug(`Auto-discovered ${p.length} route(s) to prerender`)}try{let g=await new Ke({...r,routes:p,debug:t,outDir:c,base:i.base,appRoot:u,logger:o}).run(),d=g.filter(R=>R.ok).length,P=g.filter(R=>!R.ok),m=g.length,S=g.filter(R=>R.ok&&R.route.startsWith("/blog/")).length,E=d-S,v=[];E>0&&v.push(`${E} static`),S>0&&v.push(`${S} blog`);let A=v.length>0?` (${v.join(", ")})`:"";if(d>0&&o.info(`Prerendered: ${d}/${m} pages${A}`),P.length>0)for(let R of P)o.warn(` Failed: ${R.route} - ${R.error}`)}catch(f){o.warn(`Prerendering failed: ${f.message}`),o.warn("SPA will serve all routes via index.html fallback (no impact on functionality)."),t&&f.stack&&o.debug(f.stack)}}}}import{VitePWA as Mr}from"vite-plugin-pwa";var Ze=class extends ie{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(f=>f.type==="manifest"||f.type==="service-worker");o.push(...i);let l=a.filter(f=>f.type==="icon"),u=new Set(o.filter(f=>f.type==="icon").map(f=>f.path)),c=l.filter(f=>!u.has(f.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==="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(r=>r.type==="icon"),s=this._getDefaultManifest();return t.length>0&&(s.icons=t.map(r=>this.toManifestIcon(r))),s}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},s=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:s==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[s]||`image/${s}`,purpose:e.purpose==="maskable"?"maskable":"any"}}_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
582
583
  // Generated at ${new Date().toISOString()}
583
584
 
584
585
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
@@ -612,22 +613,22 @@ self.addEventListener('message', (event) => {
612
613
  self.addEventListener('activate', (event) => {
613
614
  event.waitUntil(self.clients.claim());
614
615
  });
615
- `}_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({
616
+ `}_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({
616
617
  maxEntries: ${i.expiration.maxEntries||50},
617
618
  maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
618
- })`),i.cacheableResponse&&u.push(`new CacheableResponsePlugin({
619
+ })`),i.cacheableResponse&&c.push(`new CacheableResponsePlugin({
619
620
  statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
620
- })`),i.backgroundSync&&u.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
621
+ })`),i.backgroundSync&&c.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
621
622
  maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
622
623
  })`);let p="";return i.cacheName&&(p+=`
623
- cacheName: '${i.cacheName}',`),u.length>0&&(p+=`
624
+ cacheName: '${i.cacheName}',`),c.length>0&&(p+=`
624
625
  plugins: [
625
- ${u.join(`,
626
+ ${c.join(`,
626
627
  `)}
627
628
  ],`),i.networkTimeoutSeconds&&(p+=`
628
629
  networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${i.cacheName||"cache-"+r}
629
630
  registerRoute(
630
- ${c},
631
+ ${u},
631
632
  new ${l}({${p}
632
633
  })
633
634
  );`}).join(`
@@ -646,7 +647,7 @@ registerRoute(
646
647
  }),
647
648
  'POST'
648
649
  );
649
- `}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()}};B();function Qt(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=I("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=$.getInstance(),r=Mt.data,o=new qe(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 gr(c)}G();G();function es(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 Me=null,ts=null;function fr(n){let t=(n.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var Ye=class extends ae{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(Me&&ts===s)return this.logger.debug("Using cached route discovery results"),this.routes=Me.routes,this.errors=Me.errors,this.source=Me.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/"),Me={routes:this.routes,errors:this.errors,source:this.source},ts=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=fr(o),c=i===et.HOMEPAGE_COMPONENT?et.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=es(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 dr={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=>` {
650
+ `}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 ps(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=C("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=Gt.data,o=new Ze(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||{},f=(await o.discoverPWAAssets()).assets.filter(g=>g.type==="icon").map(g=>o.toManifestIcon(g));return{name:c.name,short_name:c.shortName,description:c.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:f.length>0?f:[]}},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(f=>f.url==="/index.html"||f.url==="index.html");return p&&!c.find(f=>f.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 Mr(u)}G();G();function gs(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 ze=null,fs=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)}function jr(n){let e=n.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw new Error(`PageMeta signedInRedirect in ${n.file} must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`);if(e.split(/[?#]/)[0]===n.path)throw new Error(`PageMeta signedInRedirect in ${n.file} points at the page itself (${e}): signed-in visitors would loop. Use another page.`)}}var Xe=class extends ie{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(ze&&fs===s)return this.logger.debug("Using cached route discovery results"),this.routes=ze.routes,this.errors=ze.errors,this.source=ze.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/"),ze={routes:this.routes,errors:this.errors,source:this.source},fs=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),jr(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=Lr(o),u=i===rt.HOMEPAGE_COMPONENT?rt.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:p,action:f,...g}=a||{};return{path:u,component:i,importPath:o,auth:a?.auth||!1,meta:{...c,...g,entity:c.entity,action:c.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=gs(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 zr={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=>` {
650
651
  path: '${o.path}',
651
652
  component: () => import('${o.importPath}'),
652
653
  auth: ${JSON.stringify(o.auth,null,2).replace(/\n/g,`
@@ -655,7 +656,7 @@ registerRoute(
655
656
  `)}
656
657
  }`).join(`,
657
658
  `);return`
658
- // ${L.routes} - Generated route data
659
+ // ${j.routes} - Generated route data
659
660
  import { lazy } from 'react';
660
661
 
661
662
  const routeData = [
@@ -695,7 +696,7 @@ export const source = '${n.source}';
695
696
 
696
697
  export default { routes: routeData, manifest: routeManifest, source: '${n.source}' };
697
698
  `},generateEmpty:(n,e,t,s="routes")=>{let r={totalRoutes:0,authRequired:0,publicRoutes:0,source:"empty",generatedAt:new Date().toISOString()};return`
698
- // ${L.routes} - Empty route data
699
+ // ${j.routes} - Empty route data
699
700
 
700
701
  const routeData = [];
701
702
  const routeManifest = ${JSON.stringify(r,null,2)};
@@ -759,7 +760,7 @@ export default discoveredRoutes;
759
760
  * Generated Route Discovery Results
760
761
  * Source: ${n.source}
761
762
  * Generated at: ${new Date().toISOString()}
762
- * Import from '${L.routes}'
763
+ * Import from '${j.routes}'
763
764
  */
764
765
 
765
766
  export const discoveredRoutes = [
@@ -773,23 +774,30 @@ export const routeManifest = {
773
774
  };
774
775
 
775
776
  export default discoveredRoutes;
776
- `},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`:""}`)}},mr=[n=>n.endsWith("Page.tsx")];function ss(n={}){return de({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:L.routes,DiscoveryClass:Ye,discoveryMethod:"discoverRoutes",filePatterns:mr,templates:dr,manifestFileName:ge.manifests.route,configKey:"routes"})({...n,disableHmr:n?.hmr===!1,hmrSmartDetection:!1})}import{loadEnv as yr}from"vite";B();G();B();function H(n){return n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function rs(n){return n?n.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Ke=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:ke,twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...u},this.appRoot=u.appRoot||null,this.logger=I("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(...hr(l))),i.join(`
777
- `)}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>${H(this.options.baseUrl)}${H(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>
777
+ `},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 ds(n={}){return me({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:j.routes,DiscoveryClass:Xe,discoveryMethod:"discoverRoutes",filePatterns:Ur,templates:zr,manifestFileName:fe.manifests.route,configKey:"routes"})({...n,disableHmr:n?.hmr===!1,hmrSmartDetection:!1})}import{loadEnv as qr}from"vite";B();function Ue(n){return n.replace(/\s+/g," ").trim()}function ms(n){let e=[`# ${Ue(n.name)}`,""];n.summary&&e.push(`> ${Ue(n.summary)}`,"");for(let t of n.sections)if(t.links.length!==0){e.push(`## ${Ue(t.heading)}`,"");for(let s of t.links){let r=`- [${Ue(s.title)}](${s.url})`;e.push(s.description?`${r}: ${Ue(s.description)}`:r)}e.push("")}return e.join(`
778
+ `)}B();var Wr="dndev",Gr="crud",Br="entity-";function hs(n,e,t){return e?n?.[e]?.[t]:void 0}function se(n){return typeof n=="string"&&n.trim()!==""?n.trim():void 0}function Vr(n,e,t){let s=n.metaExport||n.meta||{},r=s.seo||{},o=hs(e,s.namespace,t),a=se(o?.title)??se(r.title)??se(o?.meta?.fullTitle)??se(r.fullTitle),i=r.description===null?void 0:se(r.description)??se(o?.description);return{...a&&{title:a},...i&&{description:i}}}function vs(n){let{siteName:e,description:t,baseUrl:s,sitemapRoutes:r,routes:o,blogPosts:a=[],blogPath:i="/blog",translations:l,language:u}=n,c=hs(l,Wr,u)?.seo,p=se(c?.llmsPages),f=se(c?.llmsBlog);if(!p||!f)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${u}".`);let g=new Map(o.map(v=>[v.path,v])),d=new Map(a.map(v=>[`${i}/${v.slug}`,v])),P=r.map(({path:v,collection:A})=>{let R=d.get(v);if(R)return{path:v,title:R.title,...se(R.description)&&{description:se(R.description)},section:f};if(A)return{path:v,collection:A};let N=m(v);if(v===i&&!N.title)return{path:v,...N,title:f};if(!N.title){let $=g.get(v),w=($?.metaExport||$?.meta)?.namespace;throw new Error(`[dndev] llms.txt: page "${v}" has no title in "${u}". Add "title" to `+(w?`${w}_${u}.json`:"its translations")+" or `seo: { title }` to its PageMeta.")}return{path:v,...N}});function m(v){let A=g.get(v);return A?Vr(A,l,u):{}}let S={},E={};for(let[v,A]of Object.entries(l||{})){if(v===Gr&&A?.[u]&&(E[v]=A[u]),!v.startsWith(Br))continue;A?.[u]&&(E[v]=A[u]);let R=se(A?.[u]?.namePlural);R&&(S[v]=R)}return{name:e,...se(t)&&{summary:se(t)},baseUrl:s,pagesHeading:p,routes:P,entityHeadings:S,language:u,translations:E}}function ys(n){let e=new Map([[n.pagesHeading,[]]]);for(let t of n.routes){if(t.collection||t.path.includes(":"))continue;let s=t.section??n.pagesHeading;e.has(s)||e.set(s,[]),e.get(s).push({title:t.title,url:`${n.baseUrl}${t.path}`,...t.description&&{description:t.description}})}return ms({name:n.name,...n.summary&&{summary:n.summary},sections:[...e].map(([t,s])=>({heading:t,links:s}))})}function bs(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=_.getInstance(),l=o?i.resolvePath("src/content/blog",o):null;if(!l||!i.pathExists(l))return null;let u=[`# ${e}
779
+ `];n.description&&u.push(`> ${n.description}
780
+ `);for(let c of s){let p=i.resolvePath(`${c.slug}_en.md`,l);try{let f=i.readSync(p,{format:"text"});if(!f)continue;let g=f.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),d=`${t}${r}/${c.slug}`;u.push(`## ${c.title}
781
+ `),u.push(`Source: ${d}
782
+ `),c.date&&u.push(`Date: ${c.date}
783
+ `),u.push(g.trim()),u.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${c.slug}`)}}return u.join(`
784
+ `)}G();B();function H(n){return n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function ws(n){return n?n.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Hr=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function Ss(n,e){let t;try{let s=new URL(n);if(s.protocol!=="https:"&&s.protocol!=="http:")throw new Error;t=s.hostname}catch{throw new Error(`[dndev] SEO: base URL "${n}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(Hr.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: production build with base URL "${n}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}function xs(n){return n.auth&&n.auth!==!1?!1:n.meta?.seo?.noindex!==!0}var Qe=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:a,crawlDelay:i=1,aiCrawlers:l="recommended",routes:u={},...c}=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:u,defaultImage:De,twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...c},this.appRoot=c.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");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=>!(!xs(i)||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}}getSitemapRoutes(e,t=[]){let{blogPath:s}=this.options,r=[];for(let o of e||[]){if(!xs(o)||typeof o.path!="string")continue;let a=o.path===s||o.path.startsWith(`${s}/`);if(!(t.length>0&&a))if(o.path.includes(":")){if(a)continue;r.push({path:o.path,...o.meta?.entity&&{collection:o.meta.entity}})}else r.push({path:o.path})}if(t.length>0){r.push({path:s,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let o of t)r.push({path:`${s}/${o.slug}`,priority:.6,changeFrequency:"monthly",...o.date&&{lastModified:o.date}})}return r}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=u=>u?u==="*"?"*":u.startsWith("/")?u:`/${u}`:"/",i=["User-agent: *",...s.map(u=>`Disallow: ${a(u)}`),...t.map(u=>`Allow: ${a(u)}`)];o&&i.push(`Crawl-delay: ${o}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Jr(l))),i.join(`
785
+ `)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:o,changefreq:a,priority:i,image:l})=>{let u=[` <loc>${H(this.options.baseUrl)}${H(r)}</loc>`];return o&&u.push(` <lastmod>${o}</lastmod>`),a&&u.push(` <changefreq>${a}</changefreq>`),i&&u.push(` <priority>${i}</priority>`),l&&u.push(` <image:image>
778
786
  <image:loc>${H(this.options.baseUrl)}${H(l)}</image:loc>
779
787
  </image:image>`),` <url>
780
- ${c.join(`
788
+ ${u.join(`
781
789
  `)}
782
790
  </url>`}).join(`
783
791
  `);return`<?xml version="1.0" encoding="UTF-8"?>
784
792
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
785
793
  xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
786
794
  ${s}
787
- </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=$.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.resolvePath(o,t),i=e.readSync(a,{format:"text"}),l=o.replace(/_en\.md$/,""),c=i.match(/^---\r?\n([\s\S]*?)\r?\n---/),u={};if(c)for(let g of c[1].split(`
788
- `)){let f=g.indexOf(":");f!==-1&&(u[g.slice(0,f).trim()]=g.slice(f+1).trim())}let p=u.date;if(!p)try{p=e.statSync(a).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no date and file stat failed, using today`)}r.push({slug:l,title:u.title||l,description:u.description||"",date:p,tags:u.tags?u.tags.split(",").map(g=>g.trim()):[],image:u.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>
789
- <title><![CDATA[${rs(o.title)}]]></title>
795
+ </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=_.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.resolvePath(o,t),i=e.readSync(a,{format:"text"}),l=o.replace(/_en\.md$/,""),u=i.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(u)for(let f of u[1].split(`
796
+ `)){let g=f.indexOf(":");g!==-1&&(c[f.slice(0,g).trim()]=f.slice(g+1).trim())}let p=c.date;if(!p)try{p=e.statSync(a).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no date and file stat failed, using today`)}r.push({slug:l,title:c.title||l,description:c.description||"",date:p,tags:c.tags?c.tags.split(",").map(f=>f.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>
797
+ <title><![CDATA[${ws(o.title)}]]></title>
790
798
  <link>${H(this.options.baseUrl)}${H(this.options.blogPath)}/${H(o.slug)}</link>
791
799
  <guid>${H(this.options.baseUrl)}${H(this.options.blogPath)}/${H(o.slug)}</guid>
792
- <description><![CDATA[${rs(o.description)}]]></description>
800
+ <description><![CDATA[${ws(o.description)}]]></description>
793
801
  <pubDate>${o.date?new Date(o.date).toUTCString():""}</pubDate>${o.tags.length?`
794
802
  <category>${H(o.tags.join(", "))}</category>`:""}${o.image?`
795
803
  <enclosure url="${H(this.options.baseUrl)}${H(o.image)}" type="image/png" length="0"/>`:""}
@@ -804,17 +812,10 @@ ${c.join(`
804
812
  <atom:link href="${H(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
805
813
  ${s}
806
814
  </channel>
807
- </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()}}},ut=["GPTBot","Google-Extended","CCBot","ClaudeBot"],pt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function hr(n){let e=["# AI Crawler Management"];if(n==="block-all"){for(let t of[...ut,...pt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(n==="allow-all"){for(let t of[...ut,...pt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of ut)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of pt)e.push(`User-agent: ${t}`,"Allow: /","");return e}B();function os(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=Se({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||vr(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(`
808
- `)}function ns(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=$.getInstance(),l=o?i.resolvePath("src/content/blog",o):null;if(!l||!i.pathExists(l))return null;let c=[`# ${e}
809
- `];n.description&&c.push(`> ${n.description}
810
- `);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}
811
- `),c.push(`Source: ${m}
812
- `),u.date&&c.push(`Date: ${u.date}
813
- `),c.push(f.trim()),c.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${u.slug}`)}}return c.join(`
814
- `)}function vr(n){return n==="/"||n===""?"Home":(n.split("/").filter(Boolean).pop()||"Home").split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function as(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=I("SEO Plugin",t,!0),S=$.getInstance(),x=null,R=null,k=!1;return{name:"vite-seo-plugin",enforce:"pre",configResolved(T){let D=S.getAppRoot(),A=T.mode||"production",b=yr(A,D,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;b&&t&&d.debug(`Using app URL from VITE_APP_URL: ${b}`),x=i||null;let C=a||b||null;R=C?C.trim().replace(/\/+$/,""):null,d.verbose(`Name: ${x||"Not found"}`),d.verbose(`URL: ${R||"Not found"}
815
- `),x&&d.debug(` - Site name from appConfig: "${x}"`);let y=[];if(R||y.push("baseUrl (VITE_APP_URL in .env)"),x||y.push("siteName (APP_NAME in src/config/app.ts)"),y.length>0){k=!0,d.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),y.forEach(w=>d.warn(` - ${w}`)),d.warn(""),d.warn(" To fix:"),R||d.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),x||(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(!k)try{let T=new Ke({debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:R,siteName:x,crawlDelay:c,aiCrawlers:u,routes:o,appRoot:S.getAppRoot(),...m}),D=Se({appRoot:S.getAppRoot(),logger:d}),A=async(b,C)=>{this.emitFile({type:"asset",fileName:b,source:C})},P=await T.generateSEOFiles(D,A);if(P.robotsTxt&&!P.robotsTxt.skipped&&d.info(`\u{1F916} robots.txt: ${P.robotsTxt.disallowedPaths||0} disallowed paths`),P.sitemap&&!P.sitemap.skipped&&d.info(`\u{1F5FA}\uFE0F sitemap.xml: ${P.sitemap.publicRoutes||0} routes`),P.rss&&!P.rss.skipped&&d.info(`\u{1F4E1} rss.xml: ${P.rss.postCount||0} blog posts`),P.manifest&&!P.manifest.skipped&&d.info("\u{1F4C4} seo-manifest.json"),p){let b=S.getAppRoot(),C=T.discoverBlogPosts(),y=os({siteName:x,baseUrl:R,description:l,appRoot:b,blogPosts:C,logger:d});if(y&&(await A("llms.txt",y),d.info("\u{1F4C4} llms.txt")),C.length>0){let w=ns({siteName:x,baseUrl:R,description:l,appRoot:b,blogPosts:C,logger:d});w&&(await A("llms-full.txt",w),d.info("\u{1F4C4} llms-full.txt"))}}if(g?.length>0){let b=new Set,C=[];for(let{from:y,to:w,permanent:j}of g){let F=y.replace(/\/+$/,"")||"/",U=w.replace(/\/+$/,"")||"/";if(F===U){d.warn(`Redirect loop detected: ${y} \u2192 ${w} (skipped)`);continue}if(!y.startsWith("/")){d.warn(`Redirect source must start with /: "${y}" (skipped)`);continue}if(b.has(F)){d.warn(`Duplicate redirect source: "${y}" (skipped)`);continue}b.add(F),C.push(`${y} ${w} ${j===!1?302:301}`)}C.length>0&&(await A("_redirects",C.join(`
815
+ </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()}}},mt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],ht=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Jr(n){let e=["# AI Crawler Management"];if(n==="block-all"){for(let t of[...mt,...ht])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(n==="allow-all"){for(let t of[...mt,...ht])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of mt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of ht)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Ps(n={}){let{disabled:e=!1,debug:t,generateRobotsTxt:s,generateSitemap:r,routes:o={},baseUrl:a,siteName:i,siteDescription:l,crawlDelay:u,aiCrawlers:c,llmsTxt:p=!0,redirects:f,isDev:g,i18n:d={},...P}=n;if(e)return{name:"seo-disabled"};let m=C("SEO Plugin",t,!0),S=_.getInstance(),E=null,v=null,A=!1;return{name:"vite-seo-plugin",enforce:"pre",configResolved(R){let N=S.getAppRoot(),$=R.mode||"production",L=qr($,N,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;L&&t&&m.debug(`Using app URL from VITE_APP_URL: ${L}`),E=i||null;let b=a||L||null;v=b?b.trim().replace(/\/+$/,""):null,m.verbose(`Name: ${E||"Not found"}`),m.verbose(`URL: ${v||"Not found"}
816
+ `),E&&m.debug(` - Site name from appConfig: "${E}"`);let x=[];if(v||x.push("baseUrl (VITE_APP_URL in .env)"),E||x.push("siteName (APP_NAME in src/config/app.ts)"),x.length>0){A=!0,m.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),x.forEach(M=>m.warn(` - ${M}`)),m.warn(""),m.warn(" To fix:"),v||m.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),E||(m.warn(" 2. Add APP_NAME export to src/config/app.ts:"),m.warn(' export const APP_NAME = "Your App Name";')),m.warn(""),m.warn(" robots.txt and sitemap.xml will NOT be generated."),m.warn("");return}m.debug(`Generate robots.txt: ${s}`),m.debug(`Generate sitemap: ${r}`)},async generateBundle(){if(!A){g||Ss(v,"VITE_APP_URL");try{let R=new Qe({debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:v,siteName:E,crawlDelay:u,aiCrawlers:c,routes:o,appRoot:S.getAppRoot(),...P}),N=Te({appRoot:S.getAppRoot(),logger:m}),$=async(L,b)=>{this.emitFile({type:"asset",fileName:L,source:b})},w=await R.generateSEOFiles(N,$);if(w.robotsTxt&&!w.robotsTxt.skipped&&m.info(`\u{1F916} robots.txt: ${w.robotsTxt.disallowedPaths||0} disallowed paths`),w.sitemap&&!w.sitemap.skipped&&m.info(`\u{1F5FA}\uFE0F sitemap.xml: ${w.sitemap.publicRoutes||0} routes`),w.rss&&!w.rss.skipped&&m.info(`\u{1F4E1} rss.xml: ${w.rss.postCount||0} blog posts`),w.manifest&&!w.manifest.skipped&&m.info("\u{1F4C4} seo-manifest.json"),p){let L=S.getAppRoot(),b=R.discoverBlogPosts(),x=await ft(d).discoverTranslations(),M=vs({siteName:E,description:l,baseUrl:v,sitemapRoutes:R.getSitemapRoutes(N.routes||[],b),routes:N.routes||[],blogPosts:b,blogPath:R.options.blogPath,translations:x.content,language:x.fallbackLanguage});if(await $("llms.txt",ys(M)),m.info("\u{1F4C4} llms.txt"),b.length>0){let F=bs({siteName:E,baseUrl:v,description:l,appRoot:L,blogPosts:b,logger:m});F&&(await $("llms-full.txt",F),m.info("\u{1F4C4} llms-full.txt"))}}if(f?.length>0){let L=new Set,b=[];for(let{from:x,to:M,permanent:F}of f){let z=x.replace(/\/+$/,"")||"/",Z=M.replace(/\/+$/,"")||"/";if(z===Z){m.warn(`Redirect loop detected: ${x} \u2192 ${M} (skipped)`);continue}if(!x.startsWith("/")){m.warn(`Redirect source must start with /: "${x}" (skipped)`);continue}if(L.has(z)){m.warn(`Duplicate redirect source: "${x}" (skipped)`);continue}L.add(z),b.push(`${x} ${M} ${F===!1?302:301}`)}b.length>0&&(await $("_redirects",b.join(`
816
817
  `)+`
817
- `),d.info(`\u{1F4CE} _redirects: ${C.length} redirect${C.length>1?"s":""}`))}}catch(T){d.error(`SEO plugin failed to generate files (robots.txt/sitemap.xml): ${T.message}`),d.error(`Stack: ${T.stack||"No stack trace available"}`)}}}}G();function is(n={}){let{debug:e}=n;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,s){return t.startsWith("node:")?(I("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):st.includes(t)||st.some(r=>t.startsWith(`${r}/`))?(I("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):wt.includes(t)?(I("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"?`
818
+ `),m.info(`\u{1F4CE} _redirects: ${b.length} redirect${b.length>1?"s":""}`))}}catch(R){m.error(`SEO plugin failed to generate files (robots.txt/sitemap.xml): ${R.message}`),m.error(`Stack: ${R.stack||"No stack trace available"}`)}}}}}G();function Rs(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"):nt.includes(t)||nt.some(r=>t.startsWith(`${r}/`))?(C("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):Et.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"?`
818
819
  // Node.js built-in modules shims for browser compatibility
819
820
  export const URL = globalThis.URL;
820
821
  export const URLSearchParams = globalThis.URLSearchParams;
@@ -1093,7 +1094,7 @@ ${s}
1093
1094
  // Google Logging Utils shims
1094
1095
  export const LoggingWinston = class LoggingWinston {};
1095
1096
  export const LoggingBunyan = class LoggingBunyan {};
1096
- `:null}}}G();G();G();var ls=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,cs=/['"]([^'"]+)['"]/g,Ne=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:{...rt.selectors,...this.options.customPatterns?.selectors},themes:{...rt.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(ls.lastIndex=0;(r=ls.exec(t))!==null;){let o=r[1],a;for(cs.lastIndex=0;(a=cs.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 Le=class extends ae{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new Ne(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 ot.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(){ot.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 us={isEmpty:n=>!n.themes||n.themes.length===0,generateModule:(n,e,t="themes")=>{let{themes:s}=n;if(!s||s.length===0)return us.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: ${L.themes}
1097
+ `:null}}}G();var Es={isEmpty:n=>!n.themes||n.themes.length===0,generateModule:(n,e,t="themes")=>{let{themes:s}=n;if(!s||s.length===0)return Es.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}
1097
1098
  // \u{1F680} STATIC INJECTION PATTERN - Zero Runtime Loading
1098
1099
  // Generated by @donotdev/config at ${new Date().toISOString()}
1099
1100
 
@@ -1168,7 +1169,7 @@ export default {
1168
1169
  getAllThemes,
1169
1170
  getThemeNames
1170
1171
  };
1171
- `},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`// ${L.themes} - Using framework essential themes (fallback)
1172
+ `},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)
1172
1173
  // Generated by @donotdev/config at ${new Date().toISOString()}
1173
1174
 
1174
1175
  export const THEMES = ${JSON.stringify(r,null,2)};
@@ -1254,7 +1255,7 @@ export default discoveredThemes;
1254
1255
  `;let s=t.find(r=>r.essential&&r.name==="light")||t[0];return`/**
1255
1256
  * Generated Theme Discovery Results
1256
1257
  * Generated at: ${new Date().toISOString()}
1257
- * Import from '${L.themes}'
1258
+ * Import from '${j.themes}'
1258
1259
  */
1259
1260
 
1260
1261
  export const discoveredThemes = ${JSON.stringify(t,null,2)};
@@ -1269,9 +1270,9 @@ export const themeManifest = {
1269
1270
  };
1270
1271
 
1271
1272
  export default discoveredThemes;
1272
- `},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 ps(n={}){let e=Date.now();return I("theme-plugin",n.debug,n.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),de({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:L.themes,DiscoveryClass:Le,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:us,manifestFileName:ge.manifests.theme,configKey:"themes",createDiscovery:(r,o)=>{let a=new Ne(r,{debug:o.debug,logger:I("css-extractor",o.debug,o.verbose)});return new Le(a,r,o)}})(n)}G();B();var Ze=new Set(["@donotdev/functions"]);function gs(){try{let n=$.getInstance(),e=n.resolveAppPath("package.json"),t=n.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(r=>r.startsWith("@donotdev/")).filter(r=>!ve.buildTimePackages.includes(r)).filter(r=>!Ze.has(r)).sort()}catch{return[]}}B();function fs(n={}){let e=I("vite-plugins",n.debug,n.verbose);try{let{mode:t,debug:s,verbose:r,isDev:o,isPreview:a=!1,server:i={},routes:l={},themes:c={},i18n:u={},assets:p={},seo:g={},prerender:f={},pwa:m={},serverShim:d={},pluginFactory:S={},reactCompiler:x=!1}=n,R=l.debug??s,k=c.debug??s,T=u.debug??s,D=p.debug??s,A=d.debug??s,P=[];P.push(is({...d,debug:A}));let b;try{b=$.getInstance()}catch(y){throw new Error(`Failed to initialize PathResolver: ${y.message||y}`)}P.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(y){if(s){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let F={root:y.root,mode:y.mode,envDir:y.envDir,base:y.base,build:y.build?{outDir:y.build.outDir,minify:y.build.minify}:void 0,server:y.server?{port:y.server.port,host:y.server.host}:void 0,plugins:y.plugins?{count:y.plugins.length,names:y.plugins.map(U=>U?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(F,null,2))}b.setAppRoot(y.root);let w=b.getAppRoot(),j=gs();if(j.length>0){let F=y.optimizeDeps?.include||[];y.optimizeDeps.include=[...new Set([...F,...j])],e.verbose(`optimizeDeps: added ${j.length} @donotdev packages`)}if(Ze.size>0){let F=y.optimizeDeps?.exclude||[],U=[...Ze];y.optimizeDeps.exclude=[...new Set([...F,...U])],e.verbose(`optimizeDeps: excluded ${U.length} server-only packages`)}if(o&&y.server?.port){let F=y.server.https?"https":"http";process.env.VITE_APP_URL=`${F}://localhost:${y.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 F=b.getRepoRoot();e.verbose(`Repo: ${F}`),e.verbose(`App: ${w}`)}catch(F){e.debug(`Could not log PathResolver values: ${F.message}`)}if(y.server&&!a){let F=se=>{let q=se.replace(/\\/g,"/"),le=w.replace(/\\/g,"/");return!q.startsWith(le)};y.server.watch||(y.server.watch={});let U=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];y.server.watch={...y.server.watch,ignored:[...y.server.watch.ignored||[],...U,F]},e.verbose(`Fixed file watcher to use app root: ${w}`)}}}),P.push(Zt({debug:s,verbose:r})),P.push(Yt({debug:s})),P.push(wr({fastRefresh:!0,jsxRuntime:"automatic",...x?{babel:{plugins:[["babel-plugin-react-compiler",{target:"19"}]]}}:{}})),P.push(xr({ignoreConfigErrors:!0})),i.https===!0&&P.push(br()),P.push(ss({...S,...l,debug:R})),P.push(ps({...S,...c,debug:k})),P.push(...Jt({...S,...u,debug:T})),P.push(Lt({...S,...p,debug:D})),P.push(Gt({...S,mode:t,debug:s,verbose:r})),P.push(as({...g,debug:s,isDev:o})),m.enabled&&P.push(Qt({...m,debug:s})),P.push(Vt({debug:s,i18nOptions:u})),P.push(Ut());let C=!1;return P.push({name:"dndev-build-summary",enforce:"post",configResolved(y){C=y.command==="build"},closeBundle(){if(!C)return;let y=b,w=y.resolveAppPath("dist/assets");if(y.pathExists(w))try{let j=y.readdirSync(w),F=j.filter(q=>q.endsWith(".js")),U=j.filter(q=>q.endsWith(".css")),se=j.length-F.length-U.length;e.info(`
1273
- Build output: ${F.length} JS, ${U.length} CSS, ${se} other \u2014 ${j.length} files total`)}catch{}}}),P.push(Xt({...f,debug:s,verbose:r})),P}catch(t){throw I("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}G();function Sr(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 ds(n={}){let{alias:e,...t}=n,{conditions:s,...r}=t;return{alias:{"@":"/src",...Sr(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...s||[]],...r}}function ms(n={}){let{include:e=[],exclude:t=[],esbuildOptions:s={},...r}=n,o=[...e,...ve.optionalFeatures],a=[...new Set(o)],i=[...new Set(t)];return{include:a,exclude:i,esbuildOptions:s,...r}}function Xr(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,o=e.isPreview??!1,{appConfig:a,dndev:i,...l}=n;if(!a)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
1274
- Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof a!="object"||a===null)throw new Error(`appConfig must be an object, but got ${typeof a}. Make sure you are exporting appConfig from src/config/app.ts correctly.`);let c=a?.features?{debug:a.features.debug}:void 0,u=a?.seo&&typeof a.seo!="boolean"?{...a.seo,siteName:a.seo.siteName||a.app?.name}:a?.app?.name?{siteName:a.app.name}:void 0,{features:p,seo:g,...f}=l,m=a?.app?{name:a.app.name,shortName:a.app.shortName,description:a.app.description}:void 0,{pwa:d={},...S}=f,x={...d,app:d.app||m},R={...c?{features:c}:{},...u?{seo:u}:{},...Object.keys(x).length>0?{pwa:x}:{},...S,mode:r},k;try{k=Ot(R)}catch(X){throw new Error(`mergeOptions failed: ${X?.message||X||"Unknown error"}`)}let T;try{T=Tt(k)}catch(X){throw new Error(`normalizeOptions failed: ${X?.message||X||"Unknown error"}`)}if(!T)throw new Error("normalizeOptions returned undefined");let{mode:D,debug:A,verbose:P,isDev:b,isDebug:C,shouldAnalyze:y,serverOptions:w,previewOptions:j,buildOverrides:F,resolveOptions:U,routeOptions:se,themeOptions:q,i18nOptions:le,assetOptions:he,featureOptions:W,seoOptions:Pe,prerenderOptions:E,pwaOptions:N,serverShimOptions:M,chunkingOptions:z,pluginFactoryOptions:ce,reactCompiler:Ee,base:v,defineOptions:_,optimizeDepsOptions:J,pluginsOptions:pe,cssOptions:Z,envDir:_e,restOptions:Rs}=T,ze=I("vite-config",A,P);ze.debug(`Mode: ${D}, Dev: ${b}`);let dt=process.env.DNDEV_BUILD_ID,Te;s==="build"?Te=`Building for ${D}`:o?Te=`Preview server (serving ${D} build)`:s==="serve"?Te=`Development server (${D})`:Te=`Running ${s} (${D})`,ze.info(`
1275
- \u{1F3D7}\uFE0F DnDev Framework - ${Te}${dt?` [build:${dt}]`:""}`),ze.info(` Platform: Vite | Command: ${s} | Mode: ${D}
1276
- `);let je=fs({mode:D,debug:A,verbose:P,isDev:b,isPreview:o,routes:se,themes:q,i18n:le,assets:he,features:W,seo:Pe,prerender:E,pwa:N,serverShim:M,chunkingOptions:z,pluginFactory:ce,reactCompiler:Ee});if(!Array.isArray(je))throw new Error(`createVitePlugins returned ${typeof je}, expected array. Value: ${je}`);let $s=_t({mode:D,chunkingOptions:z,debug:A,isDev:b,isDebug:C,shouldAnalyze:y}),Es=o?void 0:kt(w.port||3e3,w,ze),_s=o?Dt(j):void 0;if(i)try{let{createDndevPlugin:X}=await Promise.resolve().then(()=>(Ps(),Ss));pe.push(X(typeof i=="object"?i:{}))}catch{}return{...v&&{base:v},plugins:[...je,...pe],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...D==="production"&&{build:$s},...s==="serve"&&!o&&{server:Es},...o&&{preview:_s},..._e&&{envDir:_e},customLogger:D==="production"&&!A?(()=>{let X={hasWarned:!1,_shouldSuppress(re){return re.includes("dist/")||re.includes("kB")||re.includes("\u2502")||re.includes("gzip:")||re.includes("\u2713 built in")||re.match(/built in \d+\.\d+s/)},info(re){X._shouldSuppress(re)},warn(re){X._shouldSuppress(re)},error(re){},warnOnce(re){X.hasWarned||(X.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return X})():void 0,css:{postcss:Ct(Z),...Z},optimizeDeps:ms(J),resolve:ds(U),define:{..._,"process.env.NODE_ENV":JSON.stringify(r),__DEV__:JSON.stringify(b),__PROD__:JSON.stringify(!b)},...Rs}}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?`
1277
- ${o}`:""}`);throw a.stack=o||a.stack,a}}}export{Xr as defineViteConfig};
1273
+ `},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 $s(n={}){let e=Date.now();return C("theme-plugin",n.debug,n.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),me({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:j.themes,DiscoveryClass:$e,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:Es,manifestFileName:fe.manifests.theme,configKey:"themes",createDiscovery:(r,o)=>{let a=new Ce(r,{debug:o.debug,logger:C("css-extractor",o.debug,o.verbose)});return new $e(a,r,o)}})(n)}G();B();var et=new Set(["@donotdev/functions"]);function _s(){try{let n=_.getInstance(),e=n.resolveAppPath("package.json"),t=n.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(r=>r.startsWith("@donotdev/")).filter(r=>!ye.buildTimePackages.includes(r)).filter(r=>!et.has(r)).sort()}catch{return[]}}B();function ks(n={}){let e=C("vite-plugins",n.debug,n.verbose);try{let{mode:t,debug:s,verbose:r,isDev:o,isPreview:a=!1,server:i={},routes:l={},themes:u={},i18n:c={},assets:p={},seo:f={},prerender:g={},pwa:d={},serverShim:P={},pluginFactory:m={},reactCompiler:S=!1}=n,E=l.debug??s,v=u.debug??s,A=c.debug??s,R=p.debug??s,N=P.debug??s,$=[];$.push(Rs({...P,debug:N}));let w;try{w=_.getInstance()}catch(b){throw new Error(`Failed to initialize PathResolver: ${b.message||b}`)}$.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(b){if(s){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let F={root:b.root,mode:b.mode,envDir:b.envDir,base:b.base,build:b.build?{outDir:b.build.outDir,minify:b.build.minify}:void 0,server:b.server?{port:b.server.port,host:b.server.host}:void 0,plugins:b.plugins?{count:b.plugins.length,names:b.plugins.map(z=>z?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(F,null,2))}w.setAppRoot(b.root);let x=w.getAppRoot(),M=_s();if(M.length>0){let F=b.optimizeDeps?.include||[];b.optimizeDeps.include=[...new Set([...F,...M])],e.verbose(`optimizeDeps: added ${M.length} @donotdev packages`)}if(et.size>0){let F=b.optimizeDeps?.exclude||[],z=[...et];b.optimizeDeps.exclude=[...new Set([...F,...z])],e.verbose(`optimizeDeps: excluded ${z.length} server-only packages`)}if(o&&b.server?.port){let F=b.server.https?"https":"http";process.env.VITE_APP_URL=`${F}://localhost:${b.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 F=w.getRepoRoot();e.verbose(`Repo: ${F}`),e.verbose(`App: ${x}`)}catch(F){e.debug(`Could not log PathResolver values: ${F.message}`)}if(b.server&&!a){let F=Z=>{let q=Z.replace(/\\/g,"/"),ce=x.replace(/\\/g,"/");return!q.startsWith(ce)};b.server.watch||(b.server.watch={});let z=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];b.server.watch={...b.server.watch,ignored:[...b.server.watch.ignored||[],...z,F]},e.verbose(`Fixed file watcher to use app root: ${x}`)}}}),$.push(cs({debug:s,verbose:r})),$.push(is({debug:s})),$.push(Kr({fastRefresh:!0,jsxRuntime:"automatic",...S?{babel:{plugins:[["babel-plugin-react-compiler",{target:"19"}]]}}:{}})),$.push(Zr({ignoreConfigErrors:!0})),i.https===!0&&$.push(Yr()),$.push(ds({...m,...l,debug:E})),$.push($s({...m,...u,debug:v})),$.push(...ns({...m,...c,debug:A})),$.push(Bt({...m,...p,debug:R})),$.push(Yt({...m,mode:t,debug:s,verbose:r})),$.push(Ps({...f,debug:s,isDev:o,i18n:{...m,...c,debug:A}})),d.enabled&&$.push(ps({...d,debug:s})),$.push(ss({debug:s,i18nOptions:c})),$.push(Jt());let L=!1;return $.push({name:"dndev-build-summary",enforce:"post",configResolved(b){L=b.command==="build"},closeBundle(){if(!L)return;let b=w,x=b.resolveAppPath("dist/assets");if(b.pathExists(x))try{let M=b.readdirSync(x),F=M.filter(q=>q.endsWith(".js")),z=M.filter(q=>q.endsWith(".css")),Z=M.length-F.length-z.length;e.info(`
1274
+ Build output: ${F.length} JS, ${z.length} CSS, ${Z} other \u2014 ${M.length} files total`)}catch{}}}),$.push(us({...g,debug:s,verbose:r})),$}catch(t){throw C("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}G();function Xr(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 Ds(n={}){let{alias:e,...t}=n,{conditions:s,...r}=t;return{alias:{"@":"/src",...Xr(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...s||[]],...r}}function As(n={}){let{include:e=[],exclude:t=[],esbuildOptions:s={},...r}=n,o=[...e,...ye.optionalFeatures],a=[...new Set(o)],i=[...new Set(t)];return{include:a,exclude:i,esbuildOptions:s,...r}}function Do(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,o=e.isPreview??!1,{appConfig:a,dndev:i,...l}=n;if(!a)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
1275
+ Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof a!="object"||a===null)throw new Error(`appConfig must be an object, but got ${typeof a}. Make sure you are exporting appConfig from src/config/app.ts correctly.`);let u=a?.features?{debug:a.features.debug}:void 0,c=a?.seo===!1?{disabled:!0}:a?.seo&&typeof a.seo!="boolean"?{...a.seo,siteName:a.seo.siteName||a.app?.name,siteDescription:a.app?.description}:a?.app?.name?{siteName:a.app.name,siteDescription:a.app.description}:void 0,{features:p,seo:f,...g}=l,d=a?.app?{name:a.app.name,shortName:a.app.shortName,description:a.app.description}:void 0,{pwa:P={},...m}=g,S={...P,app:P.app||d},E={...u?{features:u}:{},...c?{seo:c}:{},...Object.keys(S).length>0?{pwa:S}:{},...m,mode:r},v;try{v=Lt(E)}catch(Q){throw new Error(`mergeOptions failed: ${Q?.message||Q||"Unknown error"}`)}let A;try{A=jt(v)}catch(Q){throw new Error(`normalizeOptions failed: ${Q?.message||Q||"Unknown error"}`)}if(!A)throw new Error("normalizeOptions returned undefined");let{mode:R,debug:N,verbose:$,isDev:w,isDebug:L,shouldAnalyze:b,serverOptions:x,previewOptions:M,buildOverrides:F,resolveOptions:z,routeOptions:Z,themeOptions:q,i18nOptions:ce,assetOptions:ve,featureOptions:W,seoOptions:Pe,prerenderOptions:k,pwaOptions:O,serverShimOptions:I,chunkingOptions:U,pluginFactoryOptions:ue,reactCompiler:_e,base:y,defineOptions:D,optimizeDepsOptions:J,pluginsOptions:ge,cssOptions:X,envDir:ke,restOptions:js}=A,We=C("vite-config",N,$);We.debug(`Mode: ${R}, Dev: ${w}`);let bt=process.env.DNDEV_BUILD_ID,Me;s==="build"?Me=`Building for ${R}`:o?Me=`Preview server (serving ${R} build)`:s==="serve"?Me=`Development server (${R})`:Me=`Running ${s} (${R})`,We.info(`
1276
+ \u{1F3D7}\uFE0F DnDev Framework - ${Me}${bt?` [build:${bt}]`:""}`),We.info(` Platform: Vite | Command: ${s} | Mode: ${R}
1277
+ `);let Ge=ks({mode:R,debug:N,verbose:$,isDev:w,isPreview:o,routes:Z,themes:q,i18n:ce,assets:ve,features:W,seo:Pe,prerender:k,pwa:O,serverShim:I,chunkingOptions:U,pluginFactory:ue,reactCompiler:_e});if(!Array.isArray(Ge))throw new Error(`createVitePlugins returned ${typeof Ge}, expected array. Value: ${Ge}`);let zs=Tt({mode:R,chunkingOptions:U,debug:N,isDev:w,isDebug:L,shouldAnalyze:b}),Us=o?void 0:Ft(x.port||3e3,x,We),Ws=o?Ct(M):void 0;if(i)try{let{createDndevPlugin:Q}=await Promise.resolve().then(()=>(Ls(),Ms));ge.push(Q(typeof i=="object"?i:{}))}catch{}return{...y&&{base:y},plugins:[...Ge,...ge],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...R==="production"&&{build:zs},...s==="serve"&&!o&&{server:Us},...o&&{preview:Ws},...ke&&{envDir:ke},customLogger:R==="production"&&!N?(()=>{let Q={hasWarned:!1,_shouldSuppress(oe){return oe.includes("dist/")||oe.includes("kB")||oe.includes("\u2502")||oe.includes("gzip:")||oe.includes("\u2713 built in")||oe.match(/built in \d+\.\d+s/)},info(oe){Q._shouldSuppress(oe)},warn(oe){Q._shouldSuppress(oe)},error(oe){},warnOnce(oe){Q.hasWarned||(Q.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return Q})():void 0,css:{postcss:Ut(X),...X},optimizeDeps:As(J),resolve:Ds(z),define:{...D,"process.env.NODE_ENV":JSON.stringify(r),__DEV__:JSON.stringify(w),__PROD__:JSON.stringify(!w)},...js}}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?`
1278
+ ${o}`:""}`);throw a.stack=o||a.stack,a}}}export{Do as defineViteConfig};