@donotdev/core 0.3.1 → 0.3.3

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 (279) hide show
  1. package/functions/index.d.ts +99 -10
  2. package/functions/index.js +20 -18
  3. package/i18n/flags/af.svg +1 -0
  4. package/i18n/flags/al.svg +1 -0
  5. package/i18n/flags/am.svg +1 -0
  6. package/i18n/flags/ar.svg +1 -0
  7. package/i18n/flags/at.svg +1 -0
  8. package/i18n/flags/au.svg +1 -0
  9. package/i18n/flags/az.svg +1 -0
  10. package/i18n/flags/ba.svg +1 -0
  11. package/i18n/flags/bd.svg +1 -0
  12. package/i18n/flags/be.svg +1 -0
  13. package/i18n/flags/bg.svg +1 -0
  14. package/i18n/flags/bn.svg +1 -0
  15. package/i18n/flags/br.svg +1 -0
  16. package/i18n/flags/bs.svg +1 -0
  17. package/i18n/flags/by.svg +1 -0
  18. package/i18n/flags/bzh.svg +1 -0
  19. package/i18n/flags/ca.svg +1 -0
  20. package/i18n/flags/ch.svg +1 -0
  21. package/i18n/flags/co.svg +1 -0
  22. package/i18n/flags/cs.svg +1 -0
  23. package/i18n/flags/cy.svg +1 -0
  24. package/i18n/flags/da.svg +1 -0
  25. package/i18n/flags/de.svg +1 -0
  26. package/i18n/flags/dz.svg +1 -0
  27. package/i18n/flags/ee.svg +1 -0
  28. package/i18n/flags/el.svg +1 -0
  29. package/i18n/flags/en.svg +1 -0
  30. package/i18n/flags/es.svg +1 -0
  31. package/i18n/flags/et.svg +1 -0
  32. package/i18n/flags/eu.svg +1 -0
  33. package/i18n/flags/fa.svg +1 -0
  34. package/i18n/flags/fi.svg +1 -0
  35. package/i18n/flags/fr-cor.svg +1 -0
  36. package/i18n/flags/fr.svg +1 -0
  37. package/i18n/flags/ga.svg +1 -0
  38. package/i18n/flags/gb-sct.svg +1 -0
  39. package/i18n/flags/gb.svg +1 -0
  40. package/i18n/flags/gd.svg +1 -0
  41. package/i18n/flags/ge.svg +1 -0
  42. package/i18n/flags/gl.svg +1 -0
  43. package/i18n/flags/gu.svg +1 -0
  44. package/i18n/flags/he.svg +1 -0
  45. package/i18n/flags/hi.svg +1 -0
  46. package/i18n/flags/hr.svg +1 -0
  47. package/i18n/flags/hu.svg +1 -0
  48. package/i18n/flags/hy.svg +1 -0
  49. package/i18n/flags/id.svg +1 -0
  50. package/i18n/flags/ie.svg +1 -0
  51. package/i18n/flags/in.svg +1 -0
  52. package/i18n/flags/ir.svg +1 -0
  53. package/i18n/flags/is.svg +1 -0
  54. package/i18n/flags/it.svg +1 -0
  55. package/i18n/flags/ja.svg +1 -0
  56. package/i18n/flags/ke.svg +1 -0
  57. package/i18n/flags/kg.svg +1 -0
  58. package/i18n/flags/kh.svg +1 -0
  59. package/i18n/flags/kk.svg +1 -0
  60. package/i18n/flags/km.svg +1 -0
  61. package/i18n/flags/kn.svg +1 -0
  62. package/i18n/flags/ko.svg +1 -0
  63. package/i18n/flags/kz.svg +1 -0
  64. package/i18n/flags/la.svg +1 -0
  65. package/i18n/flags/lb.svg +1 -0
  66. package/i18n/flags/lk.svg +1 -0
  67. package/i18n/flags/lt.svg +1 -0
  68. package/i18n/flags/lv.svg +1 -0
  69. package/i18n/flags/ly.svg +1 -0
  70. package/i18n/flags/ma.svg +1 -0
  71. package/i18n/flags/md.svg +1 -0
  72. package/i18n/flags/mk.svg +1 -0
  73. package/i18n/flags/ml.svg +1 -0
  74. package/i18n/flags/mm.svg +1 -0
  75. package/i18n/flags/mn.svg +1 -0
  76. package/i18n/flags/mr.svg +1 -0
  77. package/i18n/flags/ms.svg +1 -0
  78. package/i18n/flags/mt.svg +1 -0
  79. package/i18n/flags/mx.svg +1 -0
  80. package/i18n/flags/my.svg +1 -0
  81. package/i18n/flags/ne.svg +1 -0
  82. package/i18n/flags/nl.svg +1 -0
  83. package/i18n/flags/no.svg +1 -0
  84. package/i18n/flags/np.svg +1 -0
  85. package/i18n/flags/oc.svg +1 -0
  86. package/i18n/flags/pa.svg +1 -0
  87. package/i18n/flags/pk.svg +1 -0
  88. package/i18n/flags/pl.svg +1 -0
  89. package/i18n/flags/ps.svg +1 -0
  90. package/i18n/flags/pt.svg +1 -0
  91. package/i18n/flags/rm.svg +1 -0
  92. package/i18n/flags/ro.svg +1 -0
  93. package/i18n/flags/ru.svg +1 -0
  94. package/i18n/flags/sa.svg +1 -0
  95. package/i18n/flags/si.svg +1 -0
  96. package/i18n/flags/sk.svg +1 -0
  97. package/i18n/flags/sl.svg +1 -0
  98. package/i18n/flags/sr.svg +1 -0
  99. package/i18n/flags/sv.svg +1 -0
  100. package/i18n/flags/sw.svg +1 -0
  101. package/i18n/flags/ta.svg +1 -0
  102. package/i18n/flags/te.svg +1 -0
  103. package/i18n/flags/th.svg +1 -0
  104. package/i18n/flags/tj.svg +1 -0
  105. package/i18n/flags/tl.svg +1 -0
  106. package/i18n/flags/tn.svg +1 -0
  107. package/i18n/flags/tr.svg +1 -0
  108. package/i18n/flags/ua.svg +1 -0
  109. package/i18n/flags/ur.svg +1 -0
  110. package/i18n/flags/us.svg +1 -0
  111. package/i18n/flags/uz.svg +1 -0
  112. package/i18n/flags/vi.svg +1 -0
  113. package/i18n/flags/za.svg +1 -0
  114. package/i18n/flags/zh.svg +1 -0
  115. package/i18n/locales/eager/dndev_ar.json +2 -1
  116. package/i18n/locales/eager/dndev_da.json +2 -1
  117. package/i18n/locales/eager/dndev_de.json +2 -1
  118. package/i18n/locales/eager/dndev_en.json +2 -1
  119. package/i18n/locales/eager/dndev_es.json +2 -1
  120. package/i18n/locales/eager/dndev_fr.json +2 -1
  121. package/i18n/locales/eager/dndev_it.json +2 -1
  122. package/i18n/locales/eager/dndev_ja.json +2 -1
  123. package/i18n/locales/eager/dndev_ko.json +2 -1
  124. package/i18n/locales/eager/dndev_nl.json +2 -1
  125. package/i18n/locales/eager/dndev_pl.json +2 -1
  126. package/i18n/locales/eager/dndev_pt.json +2 -1
  127. package/i18n/locales/eager/dndev_zh.json +2 -1
  128. package/i18n/locales/lazy/auth_ar.json +19 -2
  129. package/i18n/locales/lazy/auth_da.json +22 -2
  130. package/i18n/locales/lazy/auth_de.json +19 -2
  131. package/i18n/locales/lazy/auth_en.json +19 -2
  132. package/i18n/locales/lazy/auth_es.json +19 -2
  133. package/i18n/locales/lazy/auth_fr.json +19 -2
  134. package/i18n/locales/lazy/auth_it.json +19 -2
  135. package/i18n/locales/lazy/auth_ja.json +19 -2
  136. package/i18n/locales/lazy/auth_ko.json +19 -2
  137. package/i18n/locales/lazy/auth_nl.json +22 -2
  138. package/i18n/locales/lazy/auth_pl.json +19 -2
  139. package/i18n/locales/lazy/auth_pt.json +19 -2
  140. package/i18n/locales/lazy/auth_zh.json +19 -2
  141. package/i18n/locales/lazy/crud_ar.json +3 -1
  142. package/i18n/locales/lazy/crud_da.json +3 -1
  143. package/i18n/locales/lazy/crud_de.json +3 -1
  144. package/i18n/locales/lazy/crud_en.json +3 -1
  145. package/i18n/locales/lazy/crud_es.json +3 -1
  146. package/i18n/locales/lazy/crud_fr.json +3 -1
  147. package/i18n/locales/lazy/crud_it.json +3 -1
  148. package/i18n/locales/lazy/crud_ja.json +3 -1
  149. package/i18n/locales/lazy/crud_ko.json +3 -1
  150. package/i18n/locales/lazy/crud_nl.json +3 -1
  151. package/i18n/locales/lazy/crud_pl.json +3 -1
  152. package/i18n/locales/lazy/crud_pt.json +3 -1
  153. package/i18n/locales/lazy/crud_zh.json +3 -1
  154. package/index.d.ts +6927 -6153
  155. package/index.js +3 -3
  156. package/next/index.d.ts +250 -23
  157. package/next/index.js +556 -594
  158. package/next/runtime.js +3 -3
  159. package/package.json +4 -3
  160. package/server.d.ts +6950 -6153
  161. package/shared.js +2 -1
  162. package/symbol-index.json +1 -1
  163. package/vite/index.d.ts +85 -10
  164. package/vite/index.js +152 -152
  165. package/chunks/FlagBase-IQILJTOA.js +0 -1
  166. package/chunks/chunk-I6HT4XNS.js +0 -1
  167. package/chunks/chunk-PX544BGJ.js +0 -1
  168. package/chunks/flagAF-JHV34XMS.js +0 -1
  169. package/chunks/flagAL-UH6NKHXO.js +0 -1
  170. package/chunks/flagAM-7XYXA6G6.js +0 -1
  171. package/chunks/flagAR-LO3YLUZF.js +0 -1
  172. package/chunks/flagAT-6SWWBNVY.js +0 -1
  173. package/chunks/flagAU-FIJG7J4T.js +0 -1
  174. package/chunks/flagAZ-6AIO4DNL.js +0 -1
  175. package/chunks/flagBA-PIQRWY42.js +0 -1
  176. package/chunks/flagBD-7PXOE6GM.js +0 -1
  177. package/chunks/flagBE-2ZP6HCIM.js +0 -1
  178. package/chunks/flagBG-4XSHCVYH.js +0 -1
  179. package/chunks/flagBN-OF5XRA5N.js +0 -1
  180. package/chunks/flagBR-Y2266PSZ.js +0 -1
  181. package/chunks/flagBS-UV5PVKWJ.js +0 -1
  182. package/chunks/flagBY-MNAFXBA6.js +0 -1
  183. package/chunks/flagBZH-AOCZVEVI.js +0 -1
  184. package/chunks/flagCA-VR6MSBTS.js +0 -1
  185. package/chunks/flagCH-Q7MV5SPV.js +0 -1
  186. package/chunks/flagCO-C2YBOMO2.js +0 -1
  187. package/chunks/flagCS-5BC7NJX6.js +0 -1
  188. package/chunks/flagCY-PPAUTJGB.js +0 -1
  189. package/chunks/flagDA-LPI2JRTO.js +0 -1
  190. package/chunks/flagDE-MQDJAEWL.js +0 -1
  191. package/chunks/flagDZ-M6NVCF3D.js +0 -1
  192. package/chunks/flagEE-LY2JJ44X.js +0 -1
  193. package/chunks/flagEL-PP2HZIV7.js +0 -1
  194. package/chunks/flagEN-TGFHJYK7.js +0 -1
  195. package/chunks/flagES-C3H6SSSI.js +0 -1
  196. package/chunks/flagET-GEZLWRTF.js +0 -1
  197. package/chunks/flagEU-YJF5577W.js +0 -1
  198. package/chunks/flagFA-QCQKNEUZ.js +0 -1
  199. package/chunks/flagFI-LN5ICHNF.js +0 -1
  200. package/chunks/flagFR-5JPZSUVS.js +0 -1
  201. package/chunks/flagFR-COR-KPRNU2U6.js +0 -1
  202. package/chunks/flagGA-PUAQ7VY3.js +0 -1
  203. package/chunks/flagGB-SCT-RJGHRDJP.js +0 -1
  204. package/chunks/flagGB-XD2JB7EC.js +0 -1
  205. package/chunks/flagGD-ABOZBNKE.js +0 -1
  206. package/chunks/flagGE-N7C2KHVA.js +0 -1
  207. package/chunks/flagGL-AO2LC4XU.js +0 -1
  208. package/chunks/flagGU-RNGQ3TIY.js +0 -1
  209. package/chunks/flagHE-QUAWLF43.js +0 -1
  210. package/chunks/flagHI-JOOJFNKB.js +0 -1
  211. package/chunks/flagHR-2U7YEA7P.js +0 -1
  212. package/chunks/flagHU-6SPEV3OO.js +0 -1
  213. package/chunks/flagHY-L62LW6BP.js +0 -1
  214. package/chunks/flagID-LV75M4R3.js +0 -1
  215. package/chunks/flagIE-LBTC7LCK.js +0 -1
  216. package/chunks/flagIN-3UWOJ2S3.js +0 -1
  217. package/chunks/flagIR-44N33GFX.js +0 -1
  218. package/chunks/flagIS-VCPTXPLZ.js +0 -1
  219. package/chunks/flagIT-KB4NWTBO.js +0 -1
  220. package/chunks/flagJA-KLHM6VYH.js +0 -1
  221. package/chunks/flagKE-MZONPGAJ.js +0 -1
  222. package/chunks/flagKG-VF3T4E3E.js +0 -1
  223. package/chunks/flagKH-K5ZXX3DS.js +0 -1
  224. package/chunks/flagKK-ZZTJKPMR.js +0 -1
  225. package/chunks/flagKM-Y3XA6HXW.js +0 -1
  226. package/chunks/flagKN-OMVHGIUS.js +0 -1
  227. package/chunks/flagKO-UBLOXGRF.js +0 -1
  228. package/chunks/flagKZ-PYOALOB6.js +0 -1
  229. package/chunks/flagLA-4ONTEYIB.js +0 -1
  230. package/chunks/flagLB-FGOBUCL4.js +0 -1
  231. package/chunks/flagLK-BEVYO56P.js +0 -1
  232. package/chunks/flagLT-TYWQGIIQ.js +0 -1
  233. package/chunks/flagLV-S34SVWJJ.js +0 -1
  234. package/chunks/flagLY-AVR5B6N3.js +0 -1
  235. package/chunks/flagMA-KHTPMDTL.js +0 -1
  236. package/chunks/flagMD-TQMYMRQI.js +0 -1
  237. package/chunks/flagMK-C4CIIAUH.js +0 -1
  238. package/chunks/flagML-JEE5UGDD.js +0 -1
  239. package/chunks/flagMM-M72A7CHZ.js +0 -1
  240. package/chunks/flagMN-34CH7Q43.js +0 -1
  241. package/chunks/flagMR-KIJ2BPCC.js +0 -1
  242. package/chunks/flagMS-6COZCDLY.js +0 -1
  243. package/chunks/flagMT-HDBP7BED.js +0 -1
  244. package/chunks/flagMX-3XBPZTP5.js +0 -1
  245. package/chunks/flagMY-Y7C3QGRG.js +0 -1
  246. package/chunks/flagNE-LCWCYEQW.js +0 -1
  247. package/chunks/flagNL-3RFQSLLH.js +0 -1
  248. package/chunks/flagNO-RNDXHKBT.js +0 -1
  249. package/chunks/flagNP-IKVTRWFR.js +0 -1
  250. package/chunks/flagOC-JWCST6MI.js +0 -1
  251. package/chunks/flagPA-5SGZJRNZ.js +0 -1
  252. package/chunks/flagPK-KQ674PEZ.js +0 -1
  253. package/chunks/flagPL-V2ITOKFK.js +0 -1
  254. package/chunks/flagPS-WBOKI4MV.js +0 -1
  255. package/chunks/flagPT-PFIUVBWR.js +0 -1
  256. package/chunks/flagRM-MEV6U4AJ.js +0 -1
  257. package/chunks/flagRO-JPMXEGLK.js +0 -1
  258. package/chunks/flagRU-3BBKEK34.js +0 -1
  259. package/chunks/flagSA-N7OI2M6Y.js +0 -1
  260. package/chunks/flagSI-UTODFLQZ.js +0 -1
  261. package/chunks/flagSK-EV5JZ2DI.js +0 -1
  262. package/chunks/flagSL-Y4LHIV2J.js +0 -1
  263. package/chunks/flagSR-MTRWQPJ5.js +0 -1
  264. package/chunks/flagSV-LYVDSSJ4.js +0 -1
  265. package/chunks/flagSW-GJO5P4HE.js +0 -1
  266. package/chunks/flagTA-CDT3KYEB.js +0 -1
  267. package/chunks/flagTE-5EXMXH6E.js +0 -1
  268. package/chunks/flagTH-ODJA4CWB.js +0 -1
  269. package/chunks/flagTJ-CE5SV6V4.js +0 -1
  270. package/chunks/flagTL-TRVUF3XO.js +0 -1
  271. package/chunks/flagTN-G6ERYSZ3.js +0 -1
  272. package/chunks/flagTR-33VFGL2S.js +0 -1
  273. package/chunks/flagUA-HESNDKQJ.js +0 -1
  274. package/chunks/flagUR-ECIZZCDG.js +0 -1
  275. package/chunks/flagUS-M7R4WRRU.js +0 -1
  276. package/chunks/flagUZ-YW54WCES.js +0 -1
  277. package/chunks/flagVI-K3DF2THA.js +0 -1
  278. package/chunks/flagZA-5UIOKDJH.js +0 -1
  279. package/chunks/flagZH-5IE3RZVQ.js +0 -1
package/vite/index.js CHANGED
@@ -1,29 +1,29 @@
1
- var gr=Object.defineProperty;var st=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(s){throw t=[s],s}};var dr=(o,e)=>{for(var t in e)gr(o,t,{get:e[t],enumerable:!0})};function Ft(o,e=null){let t=ae[o];if(!t)throw new Error(`Unknown pattern type: ${o}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Ve(o){return Ot[o]||Ot.base}var ot,z,K,de,De,nt,Le,Be,ae,ye,Nt,at,it,Tt,lt,Ct,ct,Ot,B=st(()=>{"use strict";ot={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},z={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},K={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},de={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.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",nt={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"},ae={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"]},Nt=["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"],at=["@donotdev/core/functions","@donotdev/core/server"],it={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)/}},Tt={Inter:"inter","Space Grotesk":"space-grotesk","Playfair Display":"playfair-display","Press Start 2P":"press-start-2p",Roboto:"roboto"},lt={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]},Ct={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:[]},ct=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ot={base:{absolute:!0,onlyFiles:!0,ignore:ae.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...ae.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...ae.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:ae.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:ae.globalIgnore}}});import*as O from"node:fs";import"node:fs";import{createRequire as xr}from"node:module";import{resolve as je,join as we,dirname as xe,relative as It,normalize as Sr,sep as Mt,extname as Rr}from"node:path";import{fileURLToPath as Pr}from"node:url";import Er from"fast-glob";function Oe(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EEXIST"}function Lt(o,e){return o().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Ae,H,jt,E,G=st(()=>{"use strict";B();Ae={getGlobOptionsFor:Ve||void 0,SCAN_PATTERNS:ae||void 0,getPatternsFor:Ft||void 0,I18N_PATHS:Be||void 0},H={error:(o,e)=>{},warn:(o,e)=>{},info:o=>{}};jt={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},E=class o{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return o._instance||(o._instance=new o(e)),o._instance}static _reset(){o._instance=null}constructor(e={}){if(o._instance)return o._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,o._instance=this}normalizePath(e){if(!e)return"";try{return Sr(e).split(Mt).join("/")}catch{return String(e).split(Mt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=It(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(),n=xr(we(s,"package.json")).resolve(e);return this.normalizePath(n)}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 n=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(n)?n: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),n=je(s,r);return this.normalizePath(n)}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:Rr(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return await O.promises.readFile(e);let a=await O.promises.readFile(e,r),i=this.stripBom(a);return n==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&H.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return O.readFileSync(e);let a=O.readFileSync(e,r),i=this.stripBom(a);return n==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&H.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(xe(l)),c=this.pathExists(l);if(c&&!n)return i&&H.info(`Skipping existing file: ${l}`),!1;if(a)return H.info(`[DRY RUN] Would write file: ${l}`),!0;try{await O.promises.mkdir(u,{recursive:!0})}catch(f){if(!Oe(f))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 Lt(async()=>(Buffer.isBuffer(g)?await O.promises.writeFile(l,g):await O.promises.writeFile(l,g,"utf8"),i&&H.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(xe(l)),c=this.pathExists(l);if(c&&!n)return i&&H.info(`Skipping existing file: ${l}`),!1;if(a)return H.info(`[DRY RUN] Would write file: ${l}`),!0;try{O.mkdirSync(u,{recursive:!0})}catch(f){if(!Oe(f))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&&H.info(`${c?"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:n=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&H.info(`Skipping existing file: ${i}`),!1;if(n)return H.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(xe(i));try{await O.promises.mkdir(u,{recursive:!0})}catch(c){if(!Oe(c))throw c}try{return await Lt(async()=>(await O.promises.copyFile(e,i),a&&H.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:n=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&H.info(`Skipping existing file: ${i}`),!1;if(n)return H.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(xe(i));try{O.mkdirSync(u,{recursive:!0})}catch(c){if(!Oe(c))throw c}try{return O.copyFileSync(e,i),this._writtenPaths?.add(i),a&&H.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return O.existsSync(e)}catch(s){return t||H.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&&H.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&&H.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&&H.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await O.promises.mkdir(e,{recursive:!0})}catch(t){if(!Oe(t))throw t}}ensureDirSync(e){try{O.mkdirSync(e,{recursive:!0})}catch(t){if(!Oe(t))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=we(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(je(e)),s=this.getAppRoot(),r=It(s,t),n=this.normalizePath(r);return!n.startsWith("../")&&!n.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(we(e,t)),n=this.getAppRoot(),a=this.normalizePath(n),i=r.startsWith(a)?r.slice(a.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,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 n=this.normalizePath(we(r,t.PUBLISHED_ROOT,s)),a=n.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),n}async _globWithNormalization(e,t){return(await Er(e,t)).map(r=>{let n=typeof r=="string"?r:r.path;return this.normalizePath(n)})}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(),n=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={...n,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),n=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:n?(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:n?(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:n?(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(Pr(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 n=this.normalizePath(we(t,jt.TOOLING)),a=this.normalizePath(we(t,jt.CORE));if(this.pathExists(n)&&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 ir={};dr(ir,{createDndevPlugin:()=>wn});import{execSync as ve,execFileSync as Ie,spawn as Vo}from"node:child_process";function Z(){return E.getInstance()}function oe(){return Z().getRepoRoot()}function rr(){return Z().resolveRepoPath(".dndev")}function y(o,e,t=200){o.writeHead(t,{"Content-Type":"application/json"}),o.end(JSON.stringify(e))}function be(o,e=Ho){return new Promise((t,s)=>{let r="",n=0;o.on("data",a=>{if(n+=a.length,n>e){o.destroy(),s(new Error("Request body too large"));return}r+=a.toString()}),o.on("end",()=>t(r)),o.on("error",s)})}function Jo(o){let e=o.lastIndexOf(".");return e===-1?"":o.slice(e).toLowerCase()}function qo(){let o=Z(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",n=ve(r,{encoding:"utf8"}).trim().split(`
4
- `)[0];e.push(n)}catch{}let s=[process.env.NVM_DIR,o.resolvePath(".nvm",t)].filter(Boolean);for(let r of s)try{let n=o.resolvePath("versions/node",r),a=o.readdirSync(n).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(o.resolvePath(`${i}/bin/node`,n))}catch{}if(process.env.NVM_BIN&&e.push(o.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 n=o.resolvePath("nvm",r),a=o.readdirSync(n).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(o.resolvePath(`${i}/node.exe`,n))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let r of e)try{let n=o.realpathSync(r);if(n.includes("bun")||!o.pathExists(n))continue;return r}catch{continue}return"node"}function or(o){if(!o||typeof o!="string"||o.includes("\0"))return!1;let e=o.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 Yo(o){return o.includes("..")?!1:o.startsWith(".dndev/")||o.startsWith("docs/")||o.startsWith("guides/")}function nr(o){let e=Z(),t=e.getRepoRoot(),s=e.resolvePath(o,t),r=e.normalizePath(t),n=e.normalizePath(s);return!n.startsWith(r+"/")&&n!==r?null:s}async function Zo(o,e){let s=new URL(o.url,`http://${o.headers.host}`).searchParams.get("path");if(!s)return y(e,{error:"path parameter required"},400);if(!or(s))return y(e,{error:"Access denied"},403);let r=nr(s);if(!r)return y(e,{error:"Access denied"},403);let n=Z();if(!n.pathExists(r))return y(e,{error:"File not found"},404);let a=Jo(r);if(Ko.has(a)){let i=n.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":ar[a]||"application/octet-stream","Content-Length":i.byteLength}),void e.end(Buffer.from(i))):y(e,{error:"Failed to read file"},500)}if(a===".json")try{let i=await n.read(r);return i===null?y(e,{error:"Failed to read file"},500):y(e,{path:s,content:i})}catch{return y(e,{error:"Invalid JSON"},500)}try{let i=await n.read(r,{format:"text"});if(i===null)return y(e,{error:"Failed to read file"},500);y(e,{path:s,content:i})}catch{y(e,{error:"Failed to read file"},500)}}function Xo(o,e){let s=new URL(o.url,`http://${o.headers.host}`).searchParams.get("dir"),r=Z(),n=r.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(c,p){try{let g=r.readdirSync(c,{withFileTypes:!0});for(let 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,c),m)):f.name.endsWith(".md")&&a.push({path:m,name:f.name,isDirectory:!1}))}}catch{}}let u=[".dndev","docs","guides"];if(s){if(s.includes("..")||s.includes("\0"))return y(e,{error:"Access denied"},403);if(!u.includes(s)&&!u.some(f=>s.startsWith(f+"/")))return y(e,{error:"Directory not allowed"},403);let c=r.resolvePath(s,n),p=r.normalizePath(n);if(!r.normalizePath(c).startsWith(p+"/"))return y(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(n,{withFileTypes:!0});for(let p of c)!p.isDirectory()&&p.name.endsWith(".md")&&a.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}y(e,{entries:a})}async function Qo(o,e){let s=new URL(o.url,`http://${o.headers.host}`).searchParams.get("path");if(!s)return y(e,{error:"path parameter required"},400);if(!or(s))return y(e,{error:"Access denied"},403);if(!Yo(s))return y(e,{error:"Write not allowed to this path"},403);let r=nr(s);if(!r)return y(e,{error:"Access denied"},403);try{let n=await be(o),{content:a}=JSON.parse(n);if(a===void 0)return y(e,{error:"content field required"},400);let i=typeof a=="string"?a:JSON.stringify(a,null,2);await Z().write(r,i,{overwrite:!0}),y(e,{ok:!0})}catch{y(e,{error:"Failed to write file"},500)}}async function en(o,e){try{let t=await be(o),{line:s,checked:r}=JSON.parse(t);if(typeof s!="number")return y(e,{error:"line number required"},400);let n=Z(),a=n.resolveRepoPath(".dndev/implementation.md");if(!n.pathExists(a))return y(e,{error:"implementation.md not found"},404);let i=await n.read(a,{format:"text"});if(i===null)return y(e,{error:"Failed to read file"},500);let l=i.split(`
5
- `);if(s<0||s>=l.length)return y(e,{error:"Line out of range"},400);let u=l[s];l[s]=r?u.replace("- [ ]","- [x]"):u.replace("- [x]","- [ ]"),await n.write(a,l.join(`
6
- `),{overwrite:!0}),y(e,{ok:!0,line:l[s]})}catch{y(e,{error:"Failed to update progress"},500)}}async function tn(o,e){try{let t=await be(o),{id:s,data:r}=JSON.parse(t);if(!s||!r)return y(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(s))return y(e,{error:"Invalid screenshot ID"},400);let n=Z(),a=n.resolveRepoPath(".dndev/bugs");n.ensureDirSync(a);let i=Buffer.from(r,"base64"),l=n.resolvePath(`${s}.png`,a);await n.write(l,i,{overwrite:!0}),y(e,{ok:!0,path:`.dndev/bugs/${s}.png`})}catch{y(e,{error:"Failed to save screenshot"},500)}}async function sn(o,e){try{let t=await be(o),{action:s,phase:r}=JSON.parse(t);if(!s||typeof r!="number")return y(e,{error:"action and phase required"},400);let n=Z(),a=rr();n.ensureDirSync(a);let i=n.resolvePath("protocol.json",a),l={currentPhase:0,phases:{}};if(n.pathExists(i))try{let u=await n.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 n.write(i,l,{overwrite:!0}),y(e,{ok:!0,protocol:l})}catch{y(e,{error:"Failed to update phase"},500)}}function rn(o,e){try{let t=oe(),s=ve("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=ve("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();y(e,{commit:s,branch:r})}catch{y(e,{commit:"unknown",branch:"unknown"})}}async function on(o,e){try{let t=await be(o),s=JSON.parse(t);if(!s.id||!s.type||!s.result)return y(e,{error:"id, type, and result required"},400);let r=Z(),n=rr();r.ensureDirSync(n);let a=r.resolvePath("health.json",n),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}),y(e,{ok:!0})}catch{y(e,{error:"Failed to append action"},500)}}function nn(o,e){let t=Z(),s=t.resolveRepoPath("apps");try{let n=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}}});y(e,{apps:n})}catch{y(e,{apps:[]})}}function an(o,e){try{let t=oe(),s=ve("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),r=[],n={};for(let a of s.split(`
7
- `))a.startsWith("worktree ")?(n.path&&r.push(n),n={path:a.slice(9)}):a.startsWith("HEAD ")?n.head=a.slice(5):a.startsWith("branch ")?(n.branch=a.slice(7),n.shortBranch=n.branch.replace("refs/heads/","")):a==="detached"&&(n.detached=!0);n.path&&r.push(n),y(e,{worktrees:r})}catch(t){y(e,{error:t.message},500)}}async function ln(o,e){try{let t=await be(o),{branch:s}=JSON.parse(t);if(!s||typeof s!="string")return y(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(s))return y(e,{error:"Invalid branch name"},400);let r=oe(),n=Z(),a=n.resolvePath("..",r),i=n.getBasename(r),l=n.resolvePath(`${i}-${s.replace(/\//g,"-")}`,a);Ie("git",["worktree","add",l,"-b",s],{cwd:r,encoding:"utf-8",timeout:3e4}),y(e,{ok:!0,path:l,branch:s})}catch(t){y(e,{error:t.message},500)}}async function cn(o,e){try{let t=await be(o),{path:s}=JSON.parse(t);if(!s||typeof s!="string")return y(e,{error:"path required"},400);let r=oe();Ie("git",["worktree","remove",s,"--force"],{cwd:r,encoding:"utf-8",timeout:1e4}),y(e,{ok:!0})}catch(t){y(e,{error:t.message},500)}}function un(o,e){try{let s=new URL(o.url,`http://${o.headers.host}`).searchParams.get("branch");if(!s)return y(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(s))return y(e,{error:"Invalid branch name"},400);let r=oe(),n=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});y(e,{stat:n,diff:a})}catch(t){y(e,{error:t.message},500)}}async function pn(o,e){try{let t=await be(o),{branch:s,title:r,bodyText:n}=JSON.parse(t);if(!s)return y(e,{error:"branch required"},400);let a=oe(),i=["pr","create","--head",s];r&&i.push("--title",r),n&&i.push("--body",n);let l=Ie("gh",i,{cwd:a,encoding:"utf-8",timeout:3e4}).trim();y(e,{ok:!0,url:l})}catch(t){y(e,{error:t.message},500)}}function fn(o,e){try{let t=oe(),s=ve("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"),y(e,{platform:r,remoteUrl:s})}catch{y(e,{platform:null,remoteUrl:null})}}function gn(o,e){try{let t=oe(),s=ve("gh pr list --json number,title,state,author,headRefName,url,isDraft,reviewDecision,statusCheckRollup --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});y(e,{prs:JSON.parse(s)})}catch(t){y(e,{prs:[],error:t.message})}}function dn(o,e){try{let t=oe(),s=ve("gh issue list --json number,title,state,labels,assignees --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});y(e,{issues:JSON.parse(s)})}catch(t){y(e,{issues:[],error:t.message})}}function mn(o,e){try{let s=new URL(o.url,`http://${o.headers.host}`).searchParams.get("number");if(!s||!/^\d+$/.test(s))return y(e,{error:"PR number required"},400);let r=oe(),n=ve(`gh pr diff ${s}`,{cwd:r,encoding:"utf-8",timeout:3e4});y(e,{diff:n})}catch(t){y(e,{error:t.message},500)}}function hn(o,e){try{let s=new URL(o.url,`http://${o.headers.host}`).searchParams.get("number");if(!s||!/^\d+$/.test(s))return y(e,{error:"PR number required"},400);let r=oe(),n=ve(`gh pr checks ${s} --json name,state,status`,{cwd:r,encoding:"utf-8",timeout:15e3});y(e,{checks:JSON.parse(n)})}catch(t){y(e,{checks:[],error:t.message})}}async function vn(o,e){try{let t=await be(o),{number:s,action:r,comment:n}=JSON.parse(t);if(!s||!r)return y(e,{error:"number and action required"},400);let a=["approve","request-changes","comment"];if(!a.includes(r))return y(e,{error:`Invalid action. Use: ${a.join(", ")}`},400);let i=oe(),l=["pr","review",String(s),`--${r}`];n&&l.push("--body",n),Ie("gh",l,{cwd:i,encoding:"utf-8",timeout:15e3}),y(e,{ok:!0})}catch(t){y(e,{error:t.message},500)}}function yn(o){if(Pt)return;let e=Z(),t=e.normalizePath(o.config.root),s=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(s))return;try{let i=ve(`fuser ${sr}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}Pt=!0;let r=e.getRepoRoot(),n=qo(),a=Vo(n,[s],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(sr),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{Pt=!1}),process.on("exit",()=>{a.kill()})}function bn(o){let e=Z(),t=e.getRepoRoot(),s=[".dndev","docs","guides"];for(let r of s){let n=e.resolveRepoPath(r);if(!e.pathExists(n))continue;let a=e.watch(n,{recursive:!0},(i,l)=>{if(!l||l==="dashboard.json")return;let u=`${r}/${l}`,c=`change:${u}`;Et.has(c)||(Et.set(c,!0),setTimeout(()=>Et.delete(c),300),o.hot.send("dndev:file-changed",{path:u,timestamp:Date.now()}))});o.httpServer?.on("close",()=>a.close())}}function wn(o={}){return{name:"dndev",configureServer(e){let t=oe();o.debug,e.middlewares.use((s,r,n)=>{let a=s.url;if(!a?.startsWith(tr))return n();let l=new URL(a,`http://${s.headers.host}`).pathname.slice(tr.length),u=s.method?.toUpperCase();if(u==="GET")return l==="/file"?void Zo(s,r):l==="/tree"?void Xo(s,r):l==="/git/head"?void rn(s,r):l==="/apps"?void nn(s,r):l==="/worktrees"?void an(s,r):l==="/worktrees/diff"?void un(s,r):l==="/git/platform"?void fn(s,r):l==="/git/prs"?void gn(s,r):l==="/git/issues"?void dn(s,r):l==="/git/pr/diff"?void mn(s,r):l==="/git/pr/checks"?void hn(s,r):y(r,{error:"Not found"},404);if(u==="POST")return l==="/file"?void Qo(s,r):l==="/progress/toggle"?void en(s,r):l==="/bugs/screenshot"?void tn(s,r):l==="/phase"?void sn(s,r):l==="/actions/append"?void on(s,r):l==="/worktrees/add"?void ln(s,r):l==="/worktrees/remove"?void cn(s,r):l==="/worktrees/pr"?void pn(s,r):l==="/git/pr/review"?void vn(s,r):y(r,{error:"Not found"},404);y(r,{error:"Method not allowed"},405)}),yn(e),bn(e)}}}var tr,Ho,ar,Ko,sr,Pt,Et,lr=st(()=>{"use strict";G();tr="/api/dndev";Ho=5*1024*1024;ar={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},Ko=new Set(Object.keys(ar));sr=24681,Pt=!1;Et=new Map});import _r from"@rollup/plugin-strip";import{visualizer as kr}from"rollup-plugin-visualizer";var rt=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],mr={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 hr(o){let e=o.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function kt(o){let e=o.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function Dt(o,e=rt){return e.some(t=>o.includes(t))}function vr(o){for(let[e,t]of Object.entries(mr))if(t.some(s=>o.includes(s)))return e}function yr(o){let e=hr(o);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=kt(o);if(!t)return;if(Dt(t))return"react-core";let s=vr(t);if(s)return s}function br(o=[]){let e=o.filter(s=>!rt.includes(s)),t=[...rt,...e];return function(s){let r=kt(s);if(r&&Dt(r,t))return"react-core"}}var _t={development:{manualChunks:void 0},production:{manualChunks:yr}};function At(o,e={}){let t=_t[o]||_t.production,s=e.reactCore||[];return s.length>0?{manualChunks:br(s)}:t}G();import*as se from"@clack/prompts";var fe={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 $r(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function me(o,e){return $r()?`${e}${o}${fe.reset}`:o}function T(o,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:n=!1}=s,a=E.getInstance(),i=null;if(n){let c=a.resolveAppPath(r);a.pathExists(c)||a.mkdir(c),i=a.resolveAppPath(`${r}/${o.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${o} Log Started at ${new Date().toISOString()} ===
8
- `;a.writeSync(i,p)}let l=(c,p,g)=>{if(i){let f=new Date().toISOString(),m=g.length>0?" "+g.map(v=>typeof v=="object"?JSON.stringify(v,null,2):String(v)).join(" "):"",R=`${f} [${c}] ${p}${m}
9
- `;a.appendFile(i,R)}},u=(c,p)=>{if(p.length===0)return c;let g=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${c} ${g}`};return{debug:(c,...p)=>{e&&(n?l("DEBUG",c,p):se.log.message(me(u(c,p),fe.gray)))},verbose:(c,...p)=>{t&&(n?l("VERBOSE",c,p):se.log.message(u(c,p)))},info:(c,...p)=>{n?l("INFO",c,p):se.log.info(me(u(c,p),fe.brightCyan))},warn:(c,...p)=>{e&&n?l("WARN",c,p):se.log.warn(me(u(c,p),fe.brightYellow))},error:(c,...p)=>{e&&n?l("ERROR",c,p):se.log.error(me(u(c,p),fe.brightRed))},success:(c,...p)=>{e&&n?l("SUCCESS",c,p):se.log.success(me(u(c,p),fe.brightGreen))},when:(c,p="debug")=>(g,...f)=>{if(c){let m=u(g,f);switch(p){case"verbose":t&&(se.log.message(m),l("VERBOSE",g,f));break;case"info":se.log.info(me(m,fe.brightCyan)),l("INFO",g,f);break;case"warn":se.log.warn(me(m,fe.brightYellow)),l("WARN",g,f);break;case"error":se.log.error(me(m,fe.brightRed)),l("ERROR",g,f);break;case"success":se.log.success(me(m,fe.brightGreen)),l("SUCCESS",g,f);break;default:e&&(se.log.message(me(m,fe.gray)),l("DEBUG",g,f))}}},getLogFilePath:()=>i}}G();function zt(o={}){let{mode:e="development",chunkingOptions:t={},debug:s,verbose:r=!0,isDev:n,isDebug:a,shouldAnalyze:i,build:l={}}=o,u=T("build",s,r),c=At(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:n||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:Dr(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...c.manualChunks&&{manualChunks:c.manualChunks},compact:!0},onwarn(g,f){g.code!=="MODULE_LEVEL_DIRECTIVE"&&f(g)},plugins:[...a?[]:[_r({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let g=E.getInstance(),f=g.getAppRoot(),m="dist",R=g.resolveAppPath(`${m}/stats.html`),v=()=>{try{let b=g.resolveAppPath(m);g.pathExists(b)||g.mkdir(b)}catch{}},x=kr({filename:R,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:n||a,projectRoot:f});if(x.buildStart){let b=x.buildStart.bind(x);x.buildStart=function(...D){v();let S=b.apply(this,D);return S&&typeof S.then=="function"?S.catch(k=>{}):S}}else x.buildStart=function(){v()};let P=["generateBundle","writeBundle","closeBundle"];for(let b of P)if(x[b]){let D=x[b];x[b]=function(...S){try{v();let k=D.apply(this,S);return k&&typeof k.then=="function"?k.catch(N=>{let h=N?.message||N?.toString()||String(N)||"Unknown error";u.warn(`Bundle visualizer warning in ${b}: ${h}`),b==="closeBundle"&&u.warn(`You can manually open ${R} to view the bundle analysis`)}):k}catch(k){let N=k?.message||k?.toString()||String(k)||"Unknown error";u.warn(`Bundle visualizer warning in ${b}: ${N}`),b==="closeBundle"&&u.warn(` You can manually open ${R} to view the bundle analysis`)}}}return x})()]:[]]}}}function Dr(o){return o?["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 o=!1,e=E.getInstance();if((e.pathExists("/.dockerenv")||e.pathExists("/run/.containerenv"))&&(o=!0),!o&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(o=!0),!o&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(o=!0),!o&&process.platform==="linux"&&e.pathExists("/proc/self/cgroup"))try{let r=e.readSync("/proc/self/cgroup");r&&(r.includes("docker")||r.includes("containerd"))&&(o=!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:o,isWSL2:t,isBun:s}}function Or(o,e){if(o!==void 0)return o;let{isDocker:t,isWSL2:s,isBun:r}=Ar();if(t||s||r){let n=t?"Docker":s?"WSL2":"Bun";return e.info(`Detected ${n} environment - enabling polling mode for file watching`),!0}}function Ut(o,e={},t){let s=E.getInstance(),r=s.getRepoRoot(),{watch:n,hmr:a,host:i,...l}=e||{},u=a||{},c=i===!0?"localhost":i||"localhost",p={...u.port&&{port:u.port},...u.clientPort&&{clientPort:u.clientPort},host:u.host??c,...u.protocol&&{protocol:u.protocol},overlay:u.overlay??!0,timeout:u.timeout??5e3},g=i!==void 0?i:!0,f=l.https===!0;return{port:o,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=Or(e?.watch?.usePolling,t);return{usePolling:m,interval:e?.watch?.interval??2e3,...m&&{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 Wt(o={}){let e=o.https===!0;return{...o,https:e}}B();var Gt={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 ie={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function Se(o,e,t,s={}){let{protectedKeys:r=[],onConflict:n}=s;if(e==null)return o;switch(t){case ie.CONCATENATE_DEDUPE:{if(!Array.isArray(o)||!Array.isArray(e))return e;let a=[...o,...e];return[...new Set(a)]}case ie.SHALLOW_MERGE:return typeof o!="object"||typeof e!="object"||o===null||e===null||Array.isArray(o)||Array.isArray(e)?e:{...o,...e};case ie.DEEP_MERGE:{if(typeof o!="object"||typeof e!="object"||o===null||e===null||Array.isArray(o)||Array.isArray(e))return e;let a={...o};for(let i in e){if(r.includes(i)){n&&n(i,o[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],ie.DEEP_MERGE,{protectedKeys:r,onConflict:n}):a[i]=e[i]}return a}case ie.REPLACE:default:return e}}function Bt(o,e,t=[],s){let r=[...o,...e||[]],n=[...new Set(r)];return[...new Set([...n,...t])]}var Ne={...Gt,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(z)],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 Vt(o={},e={}){let{onConflict:t}=e,s={...Ne},r=[],n=(a,i,l,u)=>{r.push({key:a,frameworkValue:i,userValue:l,reason:u}),t&&t(a,i,l,u)};if("prerender"in o){let a=o.prerender;a===!1?o.prerender={routes:[]}:a===!0?o.prerender={routes:"auto"}:Array.isArray(a)&&(o.prerender={routes:a})}return Object.keys(o).forEach(a=>{let i=o[a],l=s[a];if(a==="optimizeDeps"&&typeof i=="object"&&i!==null){let u=l?.include||[],c=l?.exclude||[],p=i.include||[],g=i.exclude||[],f=u.filter(P=>!P.startsWith("@donotdev/")),m=g.filter(P=>f.includes(P));if(m.length>0)for(let P of m)n("optimizeDeps.exclude",P,"excluded",`Framework requires ${P} to be included. It will be included despite your exclusion.`);let R=Bt(u,p,f),v=Se(c,g,ie.CONCATENATE_DEDUPE),x=Se(l?.esbuildOptions||{},i.esbuildOptions||{},ie.DEEP_MERGE,{protectedKeys:["external"],onConflict:P=>n(`optimizeDeps.esbuildOptions.${P}`,l?.esbuildOptions?.[P],i.esbuildOptions?.[P],`Framework requires ${P} to remain as configured.`)});s[a]={...l,include:R,exclude:v,esbuildOptions:x,...Object.fromEntries(Object.entries(i).filter(([P])=>!["include","exclude","esbuildOptions"].includes(P)))};return}if(a==="css"&&typeof i=="object"&&i!==null){s[a]=Se(l||{},i,ie.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>n("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,ie.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:u=>n(`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,ie.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,ie.SHALLOW_MERGE);return}s[a]=i}),s}function Ht(o){let{server:e={},preview:t={},mode:s,build:r={},resolve:n={},routes:a={},themes:i={},i18n:l={},assets:u={},features:c={},seo:p={},prerender:g={},pwa:f={},serverShim:m={},chunking:R={},discovery:v={},pluginFactory:x={},debug:P,verbose:b,base:D,define:S={},optimizeDeps:k={},plugins:N=[],css:h={},envDir:F,reactCompiler:C=!1,...d}=o,L=s==="development",j=P||L,I=s==="production"&&(r.analyze??Ne.build.analyze);return{mode:s,debug:P,verbose:b,isDev:L,isDebug:j,shouldAnalyze:I,serverOptions:e,previewOptions:t,buildOverrides:r,resolveOptions:n,routeOptions:a,themeOptions:i,i18nOptions:l,assetOptions:u,featureOptions:c,seoOptions:p,prerenderOptions:g,pwaOptions:f,serverShimOptions:m,chunkingOptions:R,discoveryOptions:v,pluginFactoryOptions:x,base:D,defineOptions:S,optimizeDepsOptions:k,pluginsOptions:N,cssOptions:h,envDir:F,reactCompiler:C,restOptions:d}}G();import Nr from"autoprefixer";import Tr from"postcss-import";import Cr from"postcss-nesting";function Jt({postcssImport:o,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?o({resolve:s}):o,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function qt(o={}){if(o.postcss)return o.postcss;let e=E.getInstance();return Jt({postcssImport:Tr,postcssNesting:Cr,autoprefixer:Nr,resolve:(s,r)=>{let n=e.resolvePackage(s,r);if(n)return n;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 Uo from"@vitejs/plugin-basic-ssl";import Wo from"@vitejs/plugin-react";import Go from"vite-tsconfig-paths";var ee=class{static generateVirtualModule(e,t,s=!1,r=void 0,n=void 0){return t.isEmpty(e)?t.generateEmpty(e,s,r,n):t.generateModule(e,s,n)}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 ss=Object.defineProperty;var _t=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(n){throw t=[n],n}};var as=(o,e)=>{for(var t in e)ss(o,t,{get:e[t],enumerable:!0})};function bn(o,e=null){let t=pe[o];if(!t)throw new Error(`Unknown pattern type: ${o}`);return e&&t.framework?{...t,framework:t.framework.map(n=>`${e}/${n}`)}:t}function st(o){return mn[o]||mn.base}var Nt,V,oe,ve,qe,rt,kt,$e,Fe,pe,Pe,hn,Dt,Tt,vn,yn,Ot,mn,q=_t(()=>{"use strict";Nt={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},V={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},oe={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},ve={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.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",fonts:"src/app/fonts.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"}},qe="/og-image.png",rt="_shell.html",kt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},$e={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Fe={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",PUBLISHED_FLAGS:"i18n/flags"},pe={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:[`${Fe.SOURCE_EAGER}/*_*.json`],lazy:[`${Fe.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","icon-*x*.png",qe.slice(1)],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/**"]},Pe={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"]},hn=["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"],Dt=["@donotdev/core/functions","@donotdev/core/server"],Tt={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)/}},vn=["-apple-system","BlinkMacSystemFont","SF Pro","SF Pro Text","SF Pro Display","SF Mono","Helvetica Neue","Helvetica","Menlo","Monaco","Apple SD Gothic Neo","Hiragino Sans","Hiragino Kaku Gothic ProN","PingFang SC","PingFang TC","Apple Color Emoji","Segoe UI","Segoe UI Emoji","Segoe UI Symbol","Cascadia Code","Cascadia Mono","Consolas","Arial","Georgia","Times New Roman","Times","Courier New","Courier","Verdana","Tahoma","Trebuchet MS","Malgun Gothic","Yu Gothic","Meiryo","Microsoft YaHei","Microsoft JhengHei","Liberation Sans","Liberation Serif","Liberation Mono","DejaVu Sans","DejaVu Serif","DejaVu Sans Mono","Ubuntu","Cantarell","Noto Sans","Noto Serif","Noto Color Emoji","Droid Sans","Droid Sans Mono"],yn={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:[]},Ot=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],mn={base:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...pe.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...pe.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore}}});import*as j from"node:fs";import"node:fs";import{createRequire as fs}from"node:module";import{resolve as at,join as Ae,dirname as De,relative as wn,normalize as gs,sep as En,extname as ms}from"node:path";import hs from"fast-glob";function Le(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EEXIST"}function Sn(o,e){return o().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Me,ee,xn,O,Y=_t(()=>{"use strict";q();Me={getGlobOptionsFor:st||void 0,SCAN_PATTERNS:pe||void 0,getPatternsFor:bn||void 0,I18N_PATHS:Fe||void 0},ee={error:(o,e)=>{},warn:(o,e)=>{},info:o=>{}};xn={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"},O=class o{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return o._instance||(o._instance=new o(e)),o._instance}static _reset(){o._instance=null}constructor(e={}){if(o._instance)return o._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,o._instance=this}normalizePath(e){if(!e)return"";try{return gs(e).split(En).join("/")}catch{return String(e).split(En).join("/")}}getRelativePath(e){let t=this.getAppRoot(),n=wn(t,e);return this.normalizePath(n)}getBasename(e){if(!e)return"";let n=this.normalizePath(e).split("/");return n[n.length-1]||""}getDirname(e){return e?this.normalizePath(De(e)):""}resolvePackage(e,t=null){try{let n=t||this.getAppRoot(),s=fs(Ae(n,"package.json")).resolve(e);return this.normalizePath(s)}catch{return null}}resolveFrameworkPackage(e,t=null){let n=this.resolvePackage(`${e}/package.json`,t);if(n)return this.getDirname(n);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 s=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(s)?s:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),n=at(t,e);return this.normalizePath(n)}resolveRepoPath(e){let t=this.getRepoRoot(),n=this.normalizePath(e),r=at(t,n);return this.normalizePath(r)}resolvePath(e,t){let n=this.normalizePath(t),r=this.normalizePath(e),s=at(n,r);return this.normalizePath(s)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=j.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:ms(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:n="auto",encoding:r="utf8"}=t,s=this._detectFormat(e,n);try{if(s==="buffer")return await j.promises.readFile(e);let a=await j.promises.readFile(e,r),i=this.stripBom(a);return s==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&ee.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:n="auto",encoding:r="utf8"}=t,s=this._detectFormat(e,n);try{if(s==="buffer")return j.readFileSync(e);let a=j.readFileSync(e,r),i=this.stripBom(a);return s==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&ee.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,n={}){let{format:r="auto",overwrite:s=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),c=this.normalizePath(De(l)),u=this.pathExists(l);if(u&&!s)return i&&ee.info(`Skipping existing file: ${l}`),!1;if(a)return ee.info(`[DRY RUN] Would write file: ${l}`),!0;try{await j.promises.mkdir(c,{recursive:!0})}catch(f){if(!Le(f))throw f}let p=this._detectFormat(e,r),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
2
+ `:d=String(t);try{return await Sn(async()=>(Buffer.isBuffer(d)?await j.promises.writeFile(l,d):await j.promises.writeFile(l,d,"utf8"),i&&ee.info(`${u?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,n={}){let{format:r="auto",overwrite:s=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),c=this.normalizePath(De(l)),u=this.pathExists(l);if(u&&!s)return i&&ee.info(`Skipping existing file: ${l}`),!1;if(a)return ee.info(`[DRY RUN] Would write file: ${l}`),!0;try{j.mkdirSync(c,{recursive:!0})}catch(f){if(!Le(f))throw f}let p=this._detectFormat(e,r),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
3
+ `:d=String(t);try{return Buffer.isBuffer(d)?j.writeFileSync(l,d):j.writeFileSync(l,d,"utf8"),this._writtenPaths?.add(l),i&&ee.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,n={}){let{overwrite:r=!1,dryRun:s=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&ee.info(`Skipping existing file: ${i}`),!1;if(s)return ee.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(De(i));try{await j.promises.mkdir(c,{recursive:!0})}catch(u){if(!Le(u))throw u}try{return await Sn(async()=>(await j.promises.copyFile(e,i),a&&ee.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,n={}){let{overwrite:r=!1,dryRun:s=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&ee.info(`Skipping existing file: ${i}`),!1;if(s)return ee.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(De(i));try{j.mkdirSync(c,{recursive:!0})}catch(u){if(!Le(u))throw u}try{return j.copyFileSync(e,i),this._writtenPaths?.add(i),a&&ee.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return j.existsSync(e)}catch(n){return t||ee.error(`Error checking path existence: ${e}`,n),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return j.existsSync(t)||j.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return j.readdirSync(e,t)}catch(n){return this.options.debug&&ee.warn(`Failed to read directory: ${e}`,n),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return j.statSync(e)}catch(t){return this.options.debug&&ee.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return j.realpathSync(e)}watch(e,t,n){return j.watch(e,t,n)}lstatSync(e){try{return j.lstatSync(e)}catch(t){return this.options.debug&&ee.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await j.promises.mkdir(e,{recursive:!0})}catch(t){if(!Le(t))throw t}}ensureDirSync(e){try{j.mkdirSync(e,{recursive:!0})}catch(t){if(!Le(t))throw t}}async remove(e){await j.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){j.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return j.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=Ae(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(at(e)),n=this.getAppRoot(),r=wn(n,t),s=this.normalizePath(r);return!s.startsWith("../")&&!s.startsWith("/")}async findFiles(e,t,n={}){let r=this.normalizePath(Ae(e,t)),s=this.getAppRoot(),a=this.normalizePath(s),i=r.startsWith(a)?r.slice(a.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:Me.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...n})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Me.I18N_PATHS;if(!t)return null;let n=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let s=this.normalizePath(Ae(r,t.PUBLISHED_ROOT,n)),a=s.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),s}async _globWithNormalization(e,t){return(await hs(e,t)).map(r=>{let s=typeof r=="string"?r:r.path;return this.normalizePath(s)}).sort()}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 n=[...e.framework,...e.consumer];for(let u of n)if(typeof u!="string"||u.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),s=Me.getGlobOptionsFor?Me.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={...s,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(!Me.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),n=this.getRepoRoot();if(e==="i18n"&&(!t||t===n))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${n}). Ensure configResolved hook has run before discovery.`);let r=Me.getPatternsFor(e),s=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:s?(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:s?(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:s?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),n=0,r=this.options.maxLevels;for(;n<r;){let s=this.normalizePath(Ae(t,xn.TOOLING)),a=this.normalizePath(Ae(t,xn.CORE));if(this.pathExists(s)&&this.pathExists(a))return t;let i=Ae(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(Ae(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(De(t))===t)return t;let c=this.normalizePath(De(t));if(c===t)break;t=c,n++}return this.normalizePath(e)}}});var es={};as(es,{createDndevPlugin:()=>Nl});import{execSync as Se,execFileSync as Ve,spawn as nl}from"node:child_process";function re(){return O.getInstance()}function ce(){return re().getRepoRoot()}function Yr(){return re().resolveRepoPath(".dndev")}function b(o,e,t=200){o.writeHead(t,{"Content-Type":"application/json"}),o.end(JSON.stringify(e))}function _e(o,e=ol){return new Promise((t,n)=>{let r="",s=0;o.on("data",a=>{if(s+=a.length,s>e){o.destroy(),n(new Error("Request body too large"));return}r+=a.toString()}),o.on("end",()=>t(r)),o.on("error",n)})}function rl(o){let e=o.lastIndexOf(".");return e===-1?"":o.slice(e).toLowerCase()}function sl(){let o=re(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",s=Se(r,{encoding:"utf8"}).trim().split(`
4
+ `)[0];e.push(s)}catch{}let n=[process.env.NVM_DIR,o.resolvePath(".nvm",t)].filter(Boolean);for(let r of n)try{let s=o.resolvePath("versions/node",r),a=o.readdirSync(s).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(o.resolvePath(`${i}/bin/node`,s))}catch{}if(process.env.NVM_BIN&&e.push(o.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 s=o.resolvePath("nvm",r),a=o.readdirSync(s).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(o.resolvePath(`${i}/node.exe`,s))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let r of e)try{let s=o.realpathSync(r);if(s.includes("bun")||!o.pathExists(s))continue;return r}catch{continue}return"node"}function Zr(o){if(!o||typeof o!="string"||o.includes("\0"))return!1;let e=o.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 al(o){return o.includes("..")?!1:o.startsWith(".dndev/")||o.startsWith("docs/")||o.startsWith("guides/")}function Xr(o){let e=re(),t=e.getRepoRoot(),n=e.resolvePath(o,t),r=e.normalizePath(t),s=e.normalizePath(n);return!s.startsWith(r+"/")&&s!==r?null:n}async function ll(o,e){let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("path");if(!n)return b(e,{error:"path parameter required"},400);if(!Zr(n))return b(e,{error:"Access denied"},403);let r=Xr(n);if(!r)return b(e,{error:"Access denied"},403);let s=re();if(!s.pathExists(r))return b(e,{error:"File not found"},404);let a=rl(r);if(il.has(a)){let i=s.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":Qr[a]||"application/octet-stream","Content-Length":i.byteLength}),void e.end(Buffer.from(i))):b(e,{error:"Failed to read file"},500)}if(a===".json")try{let i=await s.read(r);return i===null?b(e,{error:"Failed to read file"},500):b(e,{path:n,content:i})}catch{return b(e,{error:"Invalid JSON"},500)}try{let i=await s.read(r,{format:"text"});if(i===null)return b(e,{error:"Failed to read file"},500);b(e,{path:n,content:i})}catch{b(e,{error:"Failed to read file"},500)}}function cl(o,e){let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("dir"),r=re(),s=r.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(u,p){try{let d=r.readdirSync(u,{withFileTypes:!0});for(let f of d){let g=p?`${p}/${f.name}`:f.name;f.isDirectory()&&i.has(f.name)||(f.isDirectory()?(a.push({path:g,name:f.name,isDirectory:!0}),l(r.resolvePath(f.name,u),g)):f.name.endsWith(".md")&&a.push({path:g,name:f.name,isDirectory:!1}))}}catch{}}let c=[".dndev","docs","guides"];if(n){if(n.includes("..")||n.includes("\0"))return b(e,{error:"Access denied"},403);if(!c.includes(n)&&!c.some(f=>n.startsWith(f+"/")))return b(e,{error:"Directory not allowed"},403);let u=r.resolvePath(n,s),p=r.normalizePath(s);if(!r.normalizePath(u).startsWith(p+"/"))return b(e,{error:"Access denied"},403);r.pathExists(u)&&(a.push({path:n,name:r.getBasename(n),isDirectory:!0}),l(u,n))}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(s,{withFileTypes:!0});for(let p of u)!p.isDirectory()&&p.name.endsWith(".md")&&a.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}b(e,{entries:a})}async function ul(o,e){let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("path");if(!n)return b(e,{error:"path parameter required"},400);if(!Zr(n))return b(e,{error:"Access denied"},403);if(!al(n))return b(e,{error:"Write not allowed to this path"},403);let r=Xr(n);if(!r)return b(e,{error:"Access denied"},403);try{let s=await _e(o),{content:a}=JSON.parse(s);if(a===void 0)return b(e,{error:"content field required"},400);let i=typeof a=="string"?a:JSON.stringify(a,null,2);await re().write(r,i,{overwrite:!0}),b(e,{ok:!0})}catch{b(e,{error:"Failed to write file"},500)}}async function pl(o,e){try{let t=await _e(o),{line:n,checked:r}=JSON.parse(t);if(typeof n!="number")return b(e,{error:"line number required"},400);let s=re(),a=s.resolveRepoPath(".dndev/implementation.md");if(!s.pathExists(a))return b(e,{error:"implementation.md not found"},404);let i=await s.read(a,{format:"text"});if(i===null)return b(e,{error:"Failed to read file"},500);let l=i.split(`
5
+ `);if(n<0||n>=l.length)return b(e,{error:"Line out of range"},400);let c=l[n];l[n]=r?c.replace("- [ ]","- [x]"):c.replace("- [x]","- [ ]"),await s.write(a,l.join(`
6
+ `),{overwrite:!0}),b(e,{ok:!0,line:l[n]})}catch{b(e,{error:"Failed to update progress"},500)}}async function dl(o,e){try{let t=await _e(o),{id:n,data:r}=JSON.parse(t);if(!n||!r)return b(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(n))return b(e,{error:"Invalid screenshot ID"},400);let s=re(),a=s.resolveRepoPath(".dndev/bugs");s.ensureDirSync(a);let i=Buffer.from(r,"base64"),l=s.resolvePath(`${n}.png`,a);await s.write(l,i,{overwrite:!0}),b(e,{ok:!0,path:`.dndev/bugs/${n}.png`})}catch{b(e,{error:"Failed to save screenshot"},500)}}async function fl(o,e){try{let t=await _e(o),{action:n,phase:r}=JSON.parse(t);if(!n||typeof r!="number")return b(e,{error:"action and phase required"},400);let s=re(),a=Yr();s.ensureDirSync(a);let i=s.resolvePath("protocol.json",a),l={currentPhase:0,phases:{}};if(s.pathExists(i))try{let c=await s.read(i);c&&(l=c)}catch{}n==="start"?(l.currentPhase=r,l.phases[r]||(l.phases[r]={}),l.phases[r].status="active",l.phases[r].startedAt=new Date().toISOString()):n==="complete"&&(l.phases[r]||(l.phases[r]={}),l.phases[r].status="completed",l.phases[r].completedAt=new Date().toISOString()),await s.write(i,l,{overwrite:!0}),b(e,{ok:!0,protocol:l})}catch{b(e,{error:"Failed to update phase"},500)}}function gl(o,e){try{let t=ce(),n=Se("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=Se("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();b(e,{commit:n,branch:r})}catch{b(e,{commit:"unknown",branch:"unknown"})}}async function ml(o,e){try{let t=await _e(o),n=JSON.parse(t);if(!n.id||!n.type||!n.result)return b(e,{error:"id, type, and result required"},400);let r=re(),s=Yr();r.ensureDirSync(s);let a=r.resolvePath("health.json",s),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===n.id);l>=0?i.actions[l]={...i.actions[l],...n}:i.actions.unshift(n),await r.write(a,i,{overwrite:!0}),b(e,{ok:!0})}catch{b(e,{error:"Failed to append action"},500)}}function hl(o,e){let t=re(),n=t.resolveRepoPath("apps");try{let s=t.readdirSync(n).filter(a=>{if(a==="dndev")return!1;let i=t.resolvePath(a,n);return t.statSync(i)?.isDirectory()&&t.pathExists(t.resolvePath("package.json",i))}).map(a=>{try{let i=t.resolvePath(`${a}/package.json`,n),l=t.readSync(i);return{name:a,packageName:l?.name||a}}catch{return{name:a,packageName:a}}});b(e,{apps:s})}catch{b(e,{apps:[]})}}function vl(o,e){try{let t=ce(),n=Se("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),r=[],s={};for(let a of n.split(`
7
+ `))a.startsWith("worktree ")?(s.path&&r.push(s),s={path:a.slice(9)}):a.startsWith("HEAD ")?s.head=a.slice(5):a.startsWith("branch ")?(s.branch=a.slice(7),s.shortBranch=s.branch.replace("refs/heads/","")):a==="detached"&&(s.detached=!0);s.path&&r.push(s),b(e,{worktrees:r})}catch(t){b(e,{error:t.message},500)}}async function yl(o,e){try{let t=await _e(o),{branch:n}=JSON.parse(t);if(!n||typeof n!="string")return b(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(n))return b(e,{error:"Invalid branch name"},400);let r=ce(),s=re(),a=s.resolvePath("..",r),i=s.getBasename(r),l=s.resolvePath(`${i}-${n.replace(/\//g,"-")}`,a);Ve("git",["worktree","add",l,"-b",n],{cwd:r,encoding:"utf-8",timeout:3e4}),b(e,{ok:!0,path:l,branch:n})}catch(t){b(e,{error:t.message},500)}}async function bl(o,e){try{let t=await _e(o),{path:n}=JSON.parse(t);if(!n||typeof n!="string")return b(e,{error:"path required"},400);let r=ce();Ve("git",["worktree","remove",n,"--force"],{cwd:r,encoding:"utf-8",timeout:1e4}),b(e,{ok:!0})}catch(t){b(e,{error:t.message},500)}}function wl(o,e){try{let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("branch");if(!n)return b(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(n))return b(e,{error:"Invalid branch name"},400);let r=ce(),s=Ve("git",["diff",`main...${n}`,"--stat"],{cwd:r,encoding:"utf-8",timeout:1e4}).trim(),a=Ve("git",["diff",`main...${n}`],{cwd:r,encoding:"utf-8",timeout:3e4});b(e,{stat:s,diff:a})}catch(t){b(e,{error:t.message},500)}}async function El(o,e){try{let t=await _e(o),{branch:n,title:r,bodyText:s}=JSON.parse(t);if(!n)return b(e,{error:"branch required"},400);let a=ce(),i=["pr","create","--head",n];r&&i.push("--title",r),s&&i.push("--body",s);let l=Ve("gh",i,{cwd:a,encoding:"utf-8",timeout:3e4}).trim();b(e,{ok:!0,url:l})}catch(t){b(e,{error:t.message},500)}}function Sl(o,e){try{let t=ce(),n=Se("git remote get-url origin",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=null;n.includes("github.com")?r="github":n.includes("gitlab")&&(r="gitlab"),b(e,{platform:r,remoteUrl:n})}catch{b(e,{platform:null,remoteUrl:null})}}function xl(o,e){try{let t=ce(),n=Se("gh pr list --json number,title,state,author,headRefName,url,isDraft,reviewDecision,statusCheckRollup --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});b(e,{prs:JSON.parse(n)})}catch(t){b(e,{prs:[],error:t.message})}}function $l(o,e){try{let t=ce(),n=Se("gh issue list --json number,title,state,labels,assignees --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});b(e,{issues:JSON.parse(n)})}catch(t){b(e,{issues:[],error:t.message})}}function Pl(o,e){try{let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("number");if(!n||!/^\d+$/.test(n))return b(e,{error:"PR number required"},400);let r=ce(),s=Se(`gh pr diff ${n}`,{cwd:r,encoding:"utf-8",timeout:3e4});b(e,{diff:s})}catch(t){b(e,{error:t.message},500)}}function Rl(o,e){try{let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("number");if(!n||!/^\d+$/.test(n))return b(e,{error:"PR number required"},400);let r=ce(),s=Se(`gh pr checks ${n} --json name,state,status`,{cwd:r,encoding:"utf-8",timeout:15e3});b(e,{checks:JSON.parse(s)})}catch(t){b(e,{checks:[],error:t.message})}}async function Cl(o,e){try{let t=await _e(o),{number:n,action:r,comment:s}=JSON.parse(t);if(!n||!r)return b(e,{error:"number and action required"},400);let a=["approve","request-changes","comment"];if(!a.includes(r))return b(e,{error:`Invalid action. Use: ${a.join(", ")}`},400);let i=ce(),l=["pr","review",String(n),`--${r}`];s&&l.push("--body",s),Ve("gh",l,{cwd:i,encoding:"utf-8",timeout:15e3}),b(e,{ok:!0})}catch(t){b(e,{error:t.message},500)}}function _l(o){if(ln)return;let e=re(),t=e.normalizePath(o.config.root),n=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(n))return;try{let i=Se(`fuser ${Kr}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}ln=!0;let r=e.getRepoRoot(),s=sl(),a=nl(s,[n],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(Kr),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{ln=!1}),process.on("exit",()=>{a.kill()})}function Al(o){let e=re(),t=e.getRepoRoot(),n=[".dndev","docs","guides"];for(let r of n){let s=e.resolveRepoPath(r);if(!e.pathExists(s))continue;let a=e.watch(s,{recursive:!0},(i,l)=>{if(!l||l==="dashboard.json")return;let c=`${r}/${l}`,u=`change:${c}`;cn.has(u)||(cn.set(u,!0),setTimeout(()=>cn.delete(u),300),o.hot.send("dndev:file-changed",{path:c,timestamp:Date.now()}))});o.httpServer?.on("close",()=>a.close())}}function Nl(o={}){return{name:"dndev",configureServer(e){let t=ce();o.debug,e.middlewares.use((n,r,s)=>{let a=n.url;if(!a?.startsWith(qr))return s();let l=new URL(a,`http://${n.headers.host}`).pathname.slice(qr.length),c=n.method?.toUpperCase();if(c==="GET")return l==="/file"?void ll(n,r):l==="/tree"?void cl(n,r):l==="/git/head"?void gl(n,r):l==="/apps"?void hl(n,r):l==="/worktrees"?void vl(n,r):l==="/worktrees/diff"?void wl(n,r):l==="/git/platform"?void Sl(n,r):l==="/git/prs"?void xl(n,r):l==="/git/issues"?void $l(n,r):l==="/git/pr/diff"?void Pl(n,r):l==="/git/pr/checks"?void Rl(n,r):b(r,{error:"Not found"},404);if(c==="POST")return l==="/file"?void ul(n,r):l==="/progress/toggle"?void pl(n,r):l==="/bugs/screenshot"?void dl(n,r):l==="/phase"?void fl(n,r):l==="/actions/append"?void ml(n,r):l==="/worktrees/add"?void yl(n,r):l==="/worktrees/remove"?void bl(n,r):l==="/worktrees/pr"?void El(n,r):l==="/git/pr/review"?void Cl(n,r):b(r,{error:"Not found"},404);b(r,{error:"Method not allowed"},405)}),_l(e),Al(e)}}}var qr,ol,Qr,il,Kr,ln,cn,ts=_t(()=>{"use strict";Y();qr="/api/dndev";ol=5*1024*1024;Qr={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},il=new Set(Object.keys(Qr));Kr=24681,ln=!1;cn=new Map});import ys from"@rollup/plugin-strip";import{visualizer as bs}from"rollup-plugin-visualizer";var At=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],is={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 ls(o){let e=o.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function dn(o){let e=o.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function fn(o,e=At){return e.some(t=>o.includes(t))}function cs(o){for(let[e,t]of Object.entries(is))if(t.some(n=>o.includes(n)))return e}function us(o){let e=ls(o);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=dn(o);if(!t)return;if(fn(t))return"react-core";let n=cs(t);if(n)return n}function ps(o=[]){let e=o.filter(n=>!At.includes(n)),t=[...At,...e];return function(n){let r=dn(n);if(r&&fn(r,t))return"react-core"}}var pn={development:{manualChunks:void 0},production:{manualChunks:us}};function gn(o,e={}){let t=pn[o]||pn.production,n=e.reactCore||[];return n.length>0?{manualChunks:ps(n)}:t}Y();import*as le from"@clack/prompts";var me={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 vs(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function ye(o,e){return vs()?`${e}${o}${me.reset}`:o}function G(o,e,t,n={}){let{logDir:r=".dndev-logs",fileLogging:s=!1}=n,a=O.getInstance(),i=null;if(s){let u=a.resolveAppPath(r);a.pathExists(u)||a.mkdir(u),i=a.resolveAppPath(`${r}/${o.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${o} Log Started at ${new Date().toISOString()} ===
8
+ `;a.writeSync(i,p)}let l=(u,p,d)=>{if(i){let f=new Date().toISOString(),g=d.length>0?" "+d.map(h=>typeof h=="object"?JSON.stringify(h,null,2):String(h)).join(" "):"",v=`${f} [${u}] ${p}${g}
9
+ `;a.appendFile(i,v)}},c=(u,p)=>{if(p.length===0)return u;let d=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${u} ${d}`};return{debug:(u,...p)=>{e&&(s?l("DEBUG",u,p):le.log.message(ye(c(u,p),me.gray)))},verbose:(u,...p)=>{t&&(s?l("VERBOSE",u,p):le.log.message(c(u,p)))},info:(u,...p)=>{s?l("INFO",u,p):le.log.info(ye(c(u,p),me.brightCyan))},warn:(u,...p)=>{e&&s?l("WARN",u,p):le.log.warn(ye(c(u,p),me.brightYellow))},error:(u,...p)=>{e&&s?l("ERROR",u,p):le.log.error(ye(c(u,p),me.brightRed))},success:(u,...p)=>{e&&s?l("SUCCESS",u,p):le.log.success(ye(c(u,p),me.brightGreen))},when:(u,p="debug")=>(d,...f)=>{if(u){let g=c(d,f);switch(p){case"verbose":t&&(le.log.message(g),l("VERBOSE",d,f));break;case"info":le.log.info(ye(g,me.brightCyan)),l("INFO",d,f);break;case"warn":le.log.warn(ye(g,me.brightYellow)),l("WARN",d,f);break;case"error":le.log.error(ye(g,me.brightRed)),l("ERROR",d,f);break;case"success":le.log.success(ye(g,me.brightGreen)),l("SUCCESS",d,f);break;default:e&&(le.log.message(ye(g,me.gray)),l("DEBUG",d,f))}}},getLogFilePath:()=>i}}Y();function $n(o={}){let{mode:e="development",chunkingOptions:t={},debug:n,verbose:r=!0,isDev:s,isDebug:a,shouldAnalyze:i,build:l={}}=o,c=G("build",n,r),u=gn(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:s||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:ws(),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(d,f){d.code!=="MODULE_LEVEL_DIRECTIVE"&&f(d)},plugins:[...a?[]:[ys({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let d=O.getInstance(),f=d.getAppRoot(),g="dist",v=d.resolveAppPath(`${g}/stats.html`),h=()=>{try{let $=d.resolveAppPath(g);d.pathExists($)||d.mkdir($)}catch{}},y=bs({filename:v,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:s||a,projectRoot:f});if(y.buildStart){let $=y.buildStart.bind(y);y.buildStart=function(...S){h();let x=$.apply(this,S);return x&&typeof x.then=="function"?x.catch(N=>{}):x}}else y.buildStart=function(){h()};let C=["generateBundle","writeBundle","closeBundle"];for(let $ of C)if(y[$]){let S=y[$];y[$]=function(...x){try{h();let N=S.apply(this,x);return N&&typeof N.then=="function"?N.catch(D=>{let P=D?.message||D?.toString()||String(D)||"Unknown error";c.warn(`Bundle visualizer warning in ${$}: ${P}`),$==="closeBundle"&&c.warn(`You can manually open ${v} to view the bundle analysis`)}):N}catch(N){let D=N?.message||N?.toString()||String(N)||"Unknown error";c.warn(`Bundle visualizer warning in ${$}: ${D}`),$==="closeBundle"&&c.warn(` You can manually open ${v} to view the bundle analysis`)}}}return y})()]:[]]}}}function ws(o){return o?["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 Es(){let o=!1,e=O.getInstance();if((e.pathExists("/.dockerenv")||e.pathExists("/run/.containerenv"))&&(o=!0),!o&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(o=!0),!o&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(o=!0),!o&&process.platform==="linux"&&e.pathExists("/proc/self/cgroup"))try{let r=e.readSync("/proc/self/cgroup");r&&(r.includes("docker")||r.includes("containerd"))&&(o=!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 n=typeof process.versions?.bun=="string";return{isDocker:o,isWSL2:t,isBun:n}}function Ss(o,e){if(o!==void 0)return o;let{isDocker:t,isWSL2:n,isBun:r}=Es();if(t||n||r){let s=t?"Docker":n?"WSL2":"Bun";return e.info(`Detected ${s} environment - enabling polling mode for file watching`),!0}}function Pn(o,e={},t){let n=O.getInstance(),r=n.getRepoRoot(),{watch:s,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},d=i!==void 0?i:!0,f=l.https===!0;return{port:o,host:d,open:e.open!==void 0?e.open:!0,https:f,fs:{allow:[r,n.resolveRepoPath("packages"),n.resolveRepoPath("node_modules")],strict:!1},watch:(()=>{let g=Ss(e?.watch?.usePolling,t);return{usePolling:g,interval:e?.watch?.interval??2e3,...g&&{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 Rn(o={}){let e=o.https===!0;return{...o,https:e}}q();var Cn={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 de={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function Ne(o,e,t,n={}){let{protectedKeys:r=[],onConflict:s}=n;if(e==null)return o;switch(t){case de.CONCATENATE_DEDUPE:{if(!Array.isArray(o)||!Array.isArray(e))return e;let a=[...o,...e];return[...new Set(a)]}case de.SHALLOW_MERGE:return typeof o!="object"||typeof e!="object"||o===null||e===null||Array.isArray(o)||Array.isArray(e)?e:{...o,...e};case de.DEEP_MERGE:{if(typeof o!="object"||typeof e!="object"||o===null||e===null||Array.isArray(o)||Array.isArray(e))return e;let a={...o};for(let i in e){if(r.includes(i)){s&&s(i,o[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]=Ne(a[i],e[i],de.DEEP_MERGE,{protectedKeys:r,onConflict:s}):a[i]=e[i]}return a}case de.REPLACE:default:return e}}function _n(o,e,t=[],n){let r=[...o,...e||[]],s=[...new Set(r)];return[...new Set([...s,...t])]}var je={...Cn,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:[...Pe.mandatoryIncludes],exclude:[...Pe.buildTools,...Object.values(V)],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 An(o={},e={}){let{onConflict:t}=e,n={...je},r=[],s=(a,i,l,c)=>{r.push({key:a,frameworkValue:i,userValue:l,reason:c}),t&&t(a,i,l,c)};if("prerender"in o){let a=o.prerender;a===!1?o.prerender={routes:[]}:a===!0?o.prerender={routes:"auto"}:Array.isArray(a)&&(o.prerender={routes:a})}return Object.keys(o).forEach(a=>{let i=o[a],l=n[a];if(a==="optimizeDeps"&&typeof i=="object"&&i!==null){let c=l?.include||[],u=l?.exclude||[],p=i.include||[],d=i.exclude||[],f=c.filter(C=>!C.startsWith("@donotdev/")),g=d.filter(C=>f.includes(C));if(g.length>0)for(let C of g)s("optimizeDeps.exclude",C,"excluded",`Framework requires ${C} to be included. It will be included despite your exclusion.`);let v=_n(c,p,f),h=Ne(u,d,de.CONCATENATE_DEDUPE),y=Ne(l?.esbuildOptions||{},i.esbuildOptions||{},de.DEEP_MERGE,{protectedKeys:["external"],onConflict:C=>s(`optimizeDeps.esbuildOptions.${C}`,l?.esbuildOptions?.[C],i.esbuildOptions?.[C],`Framework requires ${C} to remain as configured.`)});n[a]={...l,include:v,exclude:h,esbuildOptions:y,...Object.fromEntries(Object.entries(i).filter(([C])=>!["include","exclude","esbuildOptions"].includes(C)))};return}if(a==="css"&&typeof i=="object"&&i!==null){n[a]=Ne(l||{},i,de.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>s("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){n[a]=Ne(l||{},i,de.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:c=>s(`define.${c}`,l?.[c],i[c],`Framework requires ${c} to remain as configured.`)});return}if(Array.isArray(i)){Array.isArray(l)?n[a]=Ne(l,i,de.CONCATENATE_DEDUPE):n[a]=i;return}if(typeof i=="object"&&i!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){n[a]=Ne(l,i,de.SHALLOW_MERGE);return}n[a]=i}),n}function Nn(o){let{server:e={},preview:t={},mode:n,build:r={},resolve:s={},routes:a={},themes:i={},i18n:l={},assets:c={},features:u={},seo:p={},prerender:d={},pwa:f={},serverShim:g={},chunking:v={},discovery:h={},pluginFactory:y={},debug:C,verbose:$,base:S,define:x={},optimizeDeps:N={},plugins:D=[],css:P={},envDir:k,reactCompiler:_=!1,...m}=o,A=n==="development",B=C||A,w=n==="production"&&(r.analyze??je.build.analyze);return{mode:n,debug:C,verbose:$,isDev:A,isDebug:B,shouldAnalyze:w,serverOptions:e,previewOptions:t,buildOverrides:r,resolveOptions:s,routeOptions:a,themeOptions:i,i18nOptions:l,assetOptions:c,featureOptions:u,seoOptions:p,prerenderOptions:d,pwaOptions:f,serverShimOptions:g,chunkingOptions:v,discoveryOptions:h,pluginFactoryOptions:y,base:S,defineOptions:x,optimizeDepsOptions:N,pluginsOptions:D,cssOptions:P,envDir:k,reactCompiler:_,restOptions:m}}Y();import xs from"autoprefixer";import $s from"postcss-import";import Ps from"postcss-nesting";function kn({postcssImport:o,postcssNesting:e,autoprefixer:t,resolve:n}){return{plugins:[n?o({resolve:n}):o,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function Dn(o={}){if(o.postcss)return o.postcss;let e=O.getInstance();return kn({postcssImport:$s,postcssNesting:Ps,autoprefixer:xs,resolve:(n,r)=>{let s=e.resolvePackage(n,r);if(s)return s;if(n.startsWith("@donotdev/")){let a=n.split("/")[0]+"/"+n.split("/")[1],i=n.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(n,r)}})}import Xi from"@vitejs/plugin-basic-ssl";import Qi from"@vitejs/plugin-react";import el from"vite-tsconfig-paths";var ae=class{static generateVirtualModule(e,t,n=!1,r=void 0,s=void 0){return t.isEmpty(e)?t.generateEmpty(e,n,r,s):t.generateModule(e,n,s)}static generateInspection(e,t,n,r){return t.generateInspection.length>=3?t.generateInspection(e,n,r):t.generateInspection(e,n)}static wrapVirtualModule(e,t){return`// Virtual module: ${e}
11
11
  // Generated by @donotdev/config discovery
12
12
  // Version: 1.0.0
13
13
 
14
- ${t}`}static generateGlobals(e,t,s=""){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return`
14
+ ${t}`}static generateGlobals(e,t,n=""){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return`
15
15
  if (typeof window !== 'undefined') {
16
16
  window.${e} = ${r};
17
- ${s?`console.log('${s}');`:""}
18
- }`}static generateInspectionHeader(e,t="",s=""){return`// Auto-generated ${e} inspection file
17
+ ${n?`console.log('${n}');`:""}
18
+ }`}static generateInspectionHeader(e,t="",n=""){return`// Auto-generated ${e} inspection file
19
19
  // Generated by @donotdev/config ${e} discovery at ${new Date().toISOString()}
20
20
  // Version: 1.0.0${t?`
21
- // Source: ${t}`:""}${s?`
22
- // Runtime usage: ${s}`:""}
21
+ // Source: ${t}`:""}${n?`
22
+ // Runtime usage: ${n}`:""}
23
23
 
24
- `}static generateExports(e){return Object.entries(e).map(([t,s])=>typeof s=="function"?`export ${s.toString().replace("function ",`function ${t} `)};`:`export const ${t} = ${JSON.stringify(s,null,2)};`).join(`
24
+ `}static generateExports(e){return Object.entries(e).map(([t,n])=>typeof n=="function"?`export ${n.toString().replace("function ",`function ${t} `)};`:`export const ${t} = ${JSON.stringify(n,null,2)};`).join(`
25
25
 
26
- `)}static generateDefaultExport(e){return`export default ${JSON.stringify(e,null,2)};`}static generateManifest(e,t){let s={generatedAt:new Date().toISOString(),version:"1.0.0",timestamp:Date.now()};return t&&typeof t=="function"?{...s,...t(e)}:s}static generateCSSModule(e){if(e.size===0)return`// No utilities generated
26
+ `)}static generateDefaultExport(e){return`export default ${JSON.stringify(e,null,2)};`}static generateManifest(e,t){let n={generatedAt:new Date().toISOString(),version:"1.0.0",timestamp:Date.now()};return t&&typeof t=="function"?{...n,...t(e)}:n}static generateCSSModule(e){if(e.size===0)return`// No utilities generated
27
27
  export const utilities = {};
28
28
  export default utilities;`;let t=Object.fromEntries(e);return`// Auto-generated utility classes from discovered CSS variables
29
29
  // Generated by @donotdev/config at ${new Date().toISOString()}
@@ -38,20 +38,20 @@ var gr=Object.defineProperty;var st=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&
38
38
  generatedAt: '${new Date().toISOString()}'
39
39
  };
40
40
 
41
- export default utilities;`}static generateHelperFunctions(e,t){let s=Object.entries(t).map(([r,n])=>typeof n=="function"?n.toString().replace("function ",`function ${r} `):`function ${r}() { ${n} }`).join(`
41
+ export default utilities;`}static generateHelperFunctions(e,t){let n=Object.entries(t).map(([r,s])=>typeof s=="function"?s.toString().replace("function ",`function ${r} `):`function ${r}() { ${s} }`).join(`
42
42
 
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:n=()=>"",generateInspection:a=()=>"",generateManifest:i=()=>({}),logConfig:l=()=>{},logStats:u=()=>{},logManifest:c=()=>{}}=t;return{isEmpty:s,generateModule:r,generateEmpty:n,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"}}};G();G();function Fr(o){let e=o.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 n=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[n]=a}return t}function He(o,e={}){let{blogPath:t="/blog"}=e,s=E.getInstance(),r=e.appRoot||s.getAppRoot();if(!o.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),g=s.readSync(p,{format:"text"}),f=g?Fr(g):{};l.push({path:`${t}/${c}`,auth:!1,meta:{namespace:"blog",seo:{title:f.title||c,description:f.description||null,image:f.image||null,type:"article"}}})}return l}catch{return[]}}function Te(o={}){let{logger:e}=o,t=E.getInstance(),s=o.appRoot||t.getAppRoot();try{let r=t.resolvePath("public/route-manifest.json",s),n=t.readSync(r,{format:"json"});if(!n)return e?.error?.(`Route manifest not found at ${r}. Routes will be empty.`),{routes:[],errors:[`Route manifest missing: ${r}`],source:"fallback"};let a=n.routes||[];return{routes:a,errors:[],source:n.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 Yt(o){return o.filter(e=>{let t=e.path||e;return!(e.auth&&e.auth.required||typeof t=="string"&&t.includes(":"))}).map(e=>e.path||e)}function he(o){let{pluginName:e,icon:t,virtualModuleId:s,DiscoveryClass:r,discoveryMethod:n,filePatterns:a,templates:i,manifestFileName:l,createDiscovery:u,discoveryOptions:c={},configKey:p}=o;return function(f={}){let{debug:m,verbose:R,virtualModuleId:v=s,hmrDebounceMs:x,hmrCacheTimeout:P,hmrSmartDetection:b,disableHmr:D,...S}=f;if(!ee.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let k={...Ne.discovery,...c,debug:m,verbose:R,...S},N=p||(()=>{let w=e.match(/dndev-vite-(\w+)-discovery/);return w?w[1]:null})(),h=T(e,m,R,{fileLogging:k.fileLogging,logDir:k.logDir}),F=E.getInstance(),C=()=>{let w=F.getAppRoot(),_=F.getRepoRoot();return w&&w!==_},d=Date.now(),L=u?u(F,k):new r(F,k),j="\0"+v,I="",V=!1,te=null,Y=0,ue=!1,W=null,Re=!1,$=null,A=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(L.clearCache(),W=null,h.info("Discovery cache cleared manually"),"Cache cleared"));function M(w){let q=ee.generateVirtualModule(w,i,m,k,N).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!D&&V&&(q+=`
46
+ ${n}`}static validateTemplates(e){return["isEmpty","generateModule","generateEmpty","generateInspection"].every(n=>e[n]&&typeof e[n]=="function")}static createTemplateConfig(e,t){let{isEmpty:n=()=>!1,generateModule:r=()=>"",generateEmpty:s=()=>"",generateInspection:a=()=>"",generateManifest:i=()=>({}),logConfig:l=()=>{},logStats:c=()=>{},logManifest:u=()=>{}}=t;return{isEmpty:n,generateModule:r,generateEmpty:s,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 n=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(n):r.errors===void 0&&(r.errors=[n]),r.source==="empty"&&(r.source="error"),r}catch{return{errors:[n],source:"error"}}return{errors:[n],source:"error"}}};import{existsSync as _s,readdirSync as As}from"node:fs";import{join as Ns}from"node:path";var Rs=/^---\r?\n([\s\S]*?)\r?\n---/,Cs=/^\r?\n/;function Tn(o){let e=o.match(Rs);if(!e)return{meta:{},content:o};let t={};for(let n of(e[1]??"").split(`
47
+ `)){let r=n.indexOf(":");if(r===-1)continue;let s=n.slice(0,r).trim();if(!s)continue;let a=n.slice(r+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return{meta:t,content:o.slice(e[0].length).replace(Cs,"")}}Y();function On(o){return o.filter(e=>e.endsWith("_en.md")).sort()}function In(o){let e=Ns(o,"src","content","blog");try{return _s(e)?On(As(e)).length>0:!1}catch{return!1}}function it(o,e){let t=O.getInstance(),n=t.resolvePath("src/content/blog",o);try{if(!t.pathExists(n))return[];let r=On(t.readdirSync(n));if(r.length===0)return[];let s=[];for(let a of r){let i=t.resolvePath(a,n),l=t.readSync(i,{format:"text"}),c=a.replace(/_en\.md$/,""),{meta:u}=Tn(l),p=u.date;if(!p)try{p=t.statSync(i).mtime.toISOString().split("T")[0],e.warn(`Blog post "${c}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],e.warn(`Blog post "${c}" has no date and file stat failed, using today`)}s.push({slug:c,title:u.title||c,description:u.description||"",date:p,tags:u.tags?u.tags.split(",").map(d=>d.trim()):[],image:u.image||null})}return s.sort((a,i)=>i.date.localeCompare(a.date)),e.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(r){return e.debug(`Blog content discovery skipped: ${r.message}`),[]}}function H(o,e,t="configuration-error",n={}){let r=`[${o}] ${e}`,s=new Error(r);return s.code=t,s.pluginName=o,s.context=n,s}function be(o){return o instanceof Error&&typeof o.pluginName=="string"}Y();function Fn(o,e,t={}){let{blogPath:n="/blog"}=t;return!o.some(s=>{let a=s.path||s;return typeof a=="string"&&a.startsWith(n+"/")&&a.includes(":")})||e.length===0?[]:[{path:n,auth:!1,meta:{namespace:"blog"}},...e.map(s=>({path:`${n}/${s.slug}`,auth:!1,meta:{namespace:"blog",seo:{title:s.title,description:s.description||null,image:s.image,type:"article"}}}))]}function Mn(){let o=null,e,t=new Promise(n=>{e=n});return{set({routes:n,source:r,blogPosts:s}){if(!Array.isArray(s))throw new Error("[dndev] Route manifest: set() needs the build's blogPosts (readBlogPosts).");o={routes:n,errors:[],source:r,blogPosts:s}},useEntityResolver(n){e(n)},entityResolver:()=>t,get(){if(!o)throw new Error("[dndev] Route manifest unavailable: route discovery did not run or failed (see the error above).");return o}}}function Ln(o){return o.filter(e=>{let t=e.path||e;return!(e.auth&&e.auth.required||typeof t=="string"&&t.includes(":"))}).map(e=>e.path||e)}function we(o){let{pluginName:e,icon:t,virtualModuleId:n,DiscoveryClass:r,discoveryMethod:s,filePatterns:a,templates:i,manifestFileName:l,createDiscovery:c,discoveryOptions:u={},configKey:p}=o;return function(f={}){let{debug:g,verbose:v,virtualModuleId:h=n,hmrDebounceMs:y,hmrCacheTimeout:C,hmrSmartDetection:$,disableHmr:S,routeManifest:x,discoveryStore:N,...D}=f;if(!ae.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let P={...je.discovery,...u,debug:g,verbose:v,...D},k=p||(()=>{let E=e.match(/dndev-vite-(\w+)-discovery/);return E?E[1]:null})(),_=G(e,g,v,{fileLogging:P.fileLogging,logDir:P.logDir}),m=O.getInstance(),A=()=>{let E=m.getAppRoot(),T=m.getRepoRoot();return E&&E!==T},B=Date.now(),w=c?c(m,P):new r(m,P),M="\0"+h,L="",z=!1,K=null,U=0,Z=!1,R=null,I=!1,F=null,W=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(w.clearCache(),R=null,_.info("Discovery cache cleared manually"),"Cache cleared"));function Q(E){let J=ae.generateVirtualModule(E,i,g,P,k).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!S&&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
- `),q}function U(w){let _=w.replace(/\\/g,"/");if(D||_.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 q=F.getRelativePath(_);if(q.startsWith("packages/"))return!1;let ge=q.startsWith("src/")&&/\.(ts|tsx)$/.test(q);return ge?Array.isArray(a)&&a.length>0?a.some(X=>typeof X=="function"?X(_):typeof X=="string"?X.startsWith("**/")?_.endsWith(X.slice(3)):_.endsWith(X):!1):ge:!1}function pe(w){if(D)return h.debug("Virtual modules are static - HMR disabled"),[];let _=Date.now();return Re?(h.debug("HMR already in progress, skipping update"),[]):_-Y<x?(ue||(ue=!0,te=setTimeout(()=>{ue=!1,Y=Date.now(),_e(w)},x)),[]):(Y=_,_e(w))}function _e(w){let _=Date.now();if($===w.file&&_-Y<100)return h.debug(`Same file processed too recently: ${w.file}`),[];if(!U(w.file))return h.debug(`Skipping irrelevant file change: ${w.file}`),[];h.debug(`Relevant file changed: ${w.file}`),Re=!0,$=w.file;try{let q=Date.now()-(W?.timestamp||0);if(q<P&&W){h.debug(`Using cached discovery data (age: ${q}ms)`);let X=w.server.moduleGraph.getModuleById(j);return X&&w.server.reloadModule(X),[]}L.clearCache();let ge=w.server.moduleGraph.getModuleById(j);return ge&&w.server.reloadModule(ge),[]}finally{Re=!1,setTimeout(()=>{$===w.file&&($=null)},200)}}return{name:e,enforce:"pre",configResolved(w){I=w.root,V=w.command==="serve",m&&h.debug(`${t} ${e} initialized`),V&&h.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),i.logConfig&&i.logConfig(k)},config(w){return w.optimizeDeps||(w.optimizeDeps={}),w.optimizeDeps.exclude||(w.optimizeDeps.exclude=[]),w.optimizeDeps.exclude.includes(v)||w.optimizeDeps.exclude.push(v),w},resolveId(w){return w===v?(h.debug(`Resolving virtual module: ${w}`),{id:j,moduleSideEffects:!0}):null},async load(w){if(w!==j)return null;if(h.debug(`Loading virtual module: ${w}`),!C()){h.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let _=0;for(;!C()&&_<100;)await new Promise(q=>setTimeout(q,10)),_++;if(!C())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let _;return W?(h.debug("Using cached discovery data for virtual module"),_=W):(h.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 L[n](),W=_,h.debug("Discovery completed for virtual module")),M(_)}catch(_){return h.error(`${e} virtual module (${j}) failed to load: ${_.message}`),h.error(`Stack: ${_.stack||"No stack trace available"}`),i.generateEmpty({},m,k,N)}},async buildStart(){if(A=!1,!C()){h.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let w=0;for(;!C()&&w<100;)await new Promise(_=>setTimeout(_,10)),w++;if(!C())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let w=await L[n](!W);if(W=w,l&&p==="routes"&&w?.routes)try{let _=He(w.routes,{appRoot:F.getAppRoot()}),q=[...w.routes.map(ke=>({path:ke.path,auth:ke.auth,meta:ke.meta})),..._],ge={routes:q,source:w.source||"auto-discovery",totalRoutes:q.length,generatedAt:new Date().toISOString()},X=F.resolveAppPath(`public/${l}`);await F.write(X,JSON.stringify(ge,null,2)),h.debug(`Generated route manifest: public/${l}`)}catch(_){h.error(`Failed to write route manifest: ${_.message}`)}i.logStats&&i.logStats(w,t,h)}catch(w){h.error(`${e} discovery failed during file scanning: ${w.message}`),h.error(`Stack: ${w.stack||"No stack trace available"}`),W=ee.getEmptyResultWithError(L,w)}finally{A=!0}},configureServer(){A=!0},handleHotUpdate(w){return D?[]:A?pe(w):(h.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!W){h.warn("No cached discovery data for manifest generation - skipping");return}try{let w=ee.generateManifest(W,i.generateManifest);this.emitFile({type:"asset",fileName:l,source:JSON.stringify(w,null,2)}),R&&i.logManifest&&i.logManifest(W,e)}catch(w){h.error(`${e} manifest generation failed: ${w.message}`),h.error(`Stack: ${w.stack||"No stack trace available"}`)}},transform(w,_){return _===j?{code:w,map:null}:null}}}}var la={generateGlobals:ee.generateGlobals,generateExports:ee.generateExports,generateDefaultExport:ee.generateDefaultExport,wrapVirtualModule:ee.wrapVirtualModule,generateInspectionHeader:ee.generateInspectionHeader,validateTemplates:ee.validateTemplates,createTemplateConfig:ee.createTemplateConfig};B();var le=class o{constructor(e,t={}){if(this.constructor===o)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=T(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),n=await this._processFiles(r);this.cache={...n,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],n=s.split(".").pop();return{fileName:s,baseName:r,extension:n,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}};B();var Pe={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Je=class extends le{constructor(e,t={}){super(e,{assets:ae.assets.fallback,assetPatterns:ae.assets.patterns,frameworkPackage:nt.package,assetsPath:nt.assetsPath,modernFormats:ae.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(n=>n.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",n=r.match(/(\d+)x(\d+)/),a=n?{width:parseInt(n[1]),height:parseInt(n[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(n=>n.path),r=t||this.options.modernFormats;for(let n of r){let a=`/${e}.${n}`;if(s.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let 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 n of this.options.assets)await this._ensureAsset(n,r,s)&&t.push(n);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 n=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(n)){if(await this.pathResolver.copy(n,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 n=s.split("/").pop()||s.split("\\").pop(),a=this._analyzeAsset(n,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 n=`/${e}.${r}`;if(t.includes(n))return n}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 n=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,n)}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(),n=Math.min(Pe.logoWidth/s,Pe.logoHeight/r),a=await e(t,{density:Math.ceil(72*n)}).resize(Pe.logoWidth,Pe.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:Pe.width,height:Pe.height,channels:4,background:Pe.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"}],n=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...n,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of n){let p=`${s}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,l),a.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),i.push(c.name)}}let u=await import("sharp").catch(()=>null);if(!u)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(c=>c.name));else{for(let p of r){let g=`${s}/${p.name}`;if(this.pathResolver.pathExists(g)){i.push(p.name);continue}try{let f=u.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 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}}}};G();var Kt={data:null},Ir={isEmpty:o=>!o.manifest||o.assets?.length===0,generateModule:(o,e,t="assets")=>{let{manifest:s,assets:r,copiedAssets:n}=o,a=s.logoSvgContent||null,i={totalAssets:r.length,copiedAssets:n.length,hasLogo:s.logo.optimal!==null,hasFavicon:s.favicon.optimal!==null,hasManifest:s.manifest!==null,timestamp:new Date().toISOString()};return`// ${z.assets} - Generated asset manifest
54
- const assetManifest = ${JSON.stringify(s,null,2)};
53
+ `),J}function X(E){let T=E.replace(/\\/g,"/");if(S||T.includes("/node_modules/")||T.includes("/.git/")||T.includes("/dist/")||T.includes("/build/")||T.includes("/coverage/")||T.includes("/.vite/")||T.includes("/.turbo/")||T.endsWith(".d.ts")||T.endsWith(".tsbuildinfo")||T.endsWith(".map")||T.endsWith(".css.map")||T.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(T))return!1;let J=m.getRelativePath(T);if(J.startsWith("packages/"))return!1;let he=J.startsWith("src/")&&/\.(ts|tsx)$/.test(J);return he?Array.isArray(a)&&a.length>0?a.some(ne=>typeof ne=="function"?ne(T):typeof ne=="string"?ne.startsWith("**/")?T.endsWith(ne.slice(3)):T.endsWith(ne):!1):he:!1}function te(E){if(S)return _.debug("Virtual modules are static - HMR disabled"),[];let T=Date.now();return I?(_.debug("HMR already in progress, skipping update"),[]):T-U<y?(Z||(Z=!0,K=setTimeout(()=>{Z=!1,U=Date.now(),xe(E)},y)),[]):(U=T,xe(E))}function xe(E){let T=Date.now();if(F===E.file&&T-U<100)return _.debug(`Same file processed too recently: ${E.file}`),[];if(!X(E.file))return _.debug(`Skipping irrelevant file change: ${E.file}`),[];_.debug(`Relevant file changed: ${E.file}`),I=!0,F=E.file;try{let J=Date.now()-(R?.timestamp||0);if(J<C&&R){_.debug(`Using cached discovery data (age: ${J}ms)`);let ne=E.server.moduleGraph.getModuleById(M);return ne&&E.server.reloadModule(ne),[]}w.clearCache();let he=E.server.moduleGraph.getModuleById(M);return he&&E.server.reloadModule(he),[]}finally{I=!1,setTimeout(()=>{F===E.file&&(F=null)},200)}}return{name:e,enforce:"pre",configResolved(E){L=E.root,z=E.command==="serve",g&&_.debug(`${t} ${e} initialized`),z&&_.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),i.logConfig&&i.logConfig(P)},config(E){return E.optimizeDeps||(E.optimizeDeps={}),E.optimizeDeps.exclude||(E.optimizeDeps.exclude=[]),E.optimizeDeps.exclude.includes(h)||E.optimizeDeps.exclude.push(h),E},resolveId(E){return E===h?(_.debug(`Resolving virtual module: ${E}`),{id:M,moduleSideEffects:!0}):null},async load(E){if(E!==M)return null;if(_.debug(`Loading virtual module: ${E}`),!A()){_.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let T=0;for(;!A()&&T<100;)await new Promise(J=>setTimeout(J,10)),T++;if(!A())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let T;return R?(_.debug("Using cached discovery data for virtual module"),T=R):(_.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.`),T=await w[s](),R=T,_.debug("Discovery completed for virtual module")),Q(T)}catch(T){if(be(T))throw T;return _.error(`${e} virtual module (${M}) failed to load: ${T.message}`),_.error(`Stack: ${T.stack||"No stack trace available"}`),i.generateEmpty({},g,P,k)}},async buildStart(){if(W=!1,!A()){_.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let E=0;for(;!A()&&E<100;)await new Promise(T=>setTimeout(T,10)),E++;if(!A())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let E=await w[s](!R);if(R=E,p==="routes"&&E?.routes){let T=it(m.getAppRoot(),_),J=Fn(E.routes,T),he=[...E.routes.map(ne=>({path:ne.path,auth:ne.auth,meta:ne.meta})),...J];x?.set({routes:he,source:E.source||"auto-discovery",blogPosts:T})}i.logStats&&i.logStats(E,t,_)}catch(E){if(be(E))throw E;_.error(`${e} discovery failed during file scanning: ${E.message}`),_.error(`Stack: ${E.stack||"No stack trace available"}`),R=ae.getEmptyResultWithError(w,E)}finally{W=!0}N?.set(R),p==="routes"&&x?.useEntityResolver(w.getEntityResolver())},configureServer(){W=!0},handleHotUpdate(E){return S?[]:W?te(E):(_.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!R){_.warn("No cached discovery data for manifest generation - skipping");return}try{let E=ae.generateManifest(R,i.generateManifest);this.emitFile({type:"asset",fileName:l,source:JSON.stringify(E,null,2)}),v&&i.logManifest&&i.logManifest(R,e)}catch(E){_.error(`${e} manifest generation failed: ${E.message}`),_.error(`Stack: ${E.stack||"No stack trace available"}`)}},transform(E,T){return T===M?{code:E,map:null}:null}}}}var Pc={generateGlobals:ae.generateGlobals,generateExports:ae.generateExports,generateDefaultExport:ae.generateDefaultExport,wrapVirtualModule:ae.wrapVirtualModule,generateInspectionHeader:ae.generateInspectionHeader,validateTemplates:ae.validateTemplates,createTemplateConfig:ae.createTemplateConfig};q();var fe=class o{constructor(e,t={}){if(this.constructor===o)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=G(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 n=await this._getPatterns();this.options.verbose&&n&&(typeof n=="object"&&n.pattern?this.logger.verbose(`Pattern: ${n.pattern}`):typeof n=="string"&&this.logger.verbose(`Pattern: ${n}`),n.dirs&&this.logger.verbose(`Search directories: ${n.dirs.slice(0,3).join(", ")}${n.dirs.length>3?` (${n.dirs.length} total)`:""}`));let r=await this._prepareFiles(),s=await this._scanFiles(n),a=await this._processFiles(s,r);this.cache={...a,timestamp:Date.now()};let i=Date.now()-t;return this.logger.debug(`Discovery completed in ${i}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){if(be(n))throw n;return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${n.message}`),this.logger.error(`Stack: ${n.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 _prepareFiles(){return{}}async _processFiles(e,t){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("/"),n=t[t.length-1],r=n.split(".")[0],s=n.split(".").pop();return{fileName:n,baseName:r,extension:s,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let n=this.pathResolver.getFileInfo(e);return n?await t(n):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(n){if(be(n))throw n;return this.logger.debug(`Error processing file ${e}: ${n.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}};q();var Nc={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},jn=[{id:"en",name:"English",nativeName:"English",flagCode:"gb"},{id:"us",name:"English (US)",nativeName:"English (US)",countryCode:"US",dialCode:"+1"},{id:"gb",name:"English (UK)",nativeName:"English (UK)",countryCode:"GB",dialCode:"+44"},{id:"en-ca",name:"English (Canada)",nativeName:"English (Canada)",flagCode:"ca",countryCode:"CA",dialCode:"+1"},{id:"au",name:"English (Australia)",nativeName:"English (Australia)",countryCode:"AU",dialCode:"+61"},{id:"ie",name:"English (Ireland)",nativeName:"English (Ireland)",countryCode:"IE",dialCode:"+353"},{id:"es",name:"Spanish",nativeName:"Espa\xF1ol",countryCode:"ES",dialCode:"+34"},{id:"mx",name:"Spanish (Mexico)",nativeName:"Espa\xF1ol (M\xE9xico)",countryCode:"MX",dialCode:"+52"},{id:"es-ar",name:"Spanish (Argentina)",nativeName:"Espa\xF1ol (Argentina)",flagCode:"ar",countryCode:"AR",dialCode:"+54"},{id:"fr",name:"French",nativeName:"Fran\xE7ais",flagCode:"fr",countryCode:"FR",dialCode:"+33"},{id:"fr-be",name:"French (Belgium)",nativeName:"Fran\xE7ais (Belgique)",flagCode:"be",countryCode:"BE",dialCode:"+32"},{id:"ch",name:"French (Switzerland)",nativeName:"Fran\xE7ais (Suisse)",countryCode:"CH",dialCode:"+41"},{id:"de",name:"German",nativeName:"Deutsch",countryCode:"DE",dialCode:"+49"},{id:"at",name:"German (Austria)",nativeName:"Deutsch (\xD6sterreich)",countryCode:"AT",dialCode:"+43"},{id:"it",name:"Italian",nativeName:"Italiano",countryCode:"IT",dialCode:"+39"},{id:"pt",name:"Portuguese",nativeName:"Portugu\xEAs",countryCode:"PT",dialCode:"+351"},{id:"br",name:"Portuguese (Brazil)",nativeName:"Portugu\xEAs (Brasil)",flagCode:"br",countryCode:"BR",dialCode:"+55"},{id:"ru",name:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",countryCode:"RU",dialCode:"+7"},{id:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",countryCode:"JP",dialCode:"+81"},{id:"ko",name:"Korean",nativeName:"\uD55C\uAD6D\uC5B4",countryCode:"KR",dialCode:"+82"},{id:"zh",name:"Chinese",nativeName:"\u4E2D\u6587",countryCode:"CN",dialCode:"+86"},{id:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flagCode:"sa",countryCode:"SA",dialCode:"+966"},{id:"ar-ma",name:"Arabic (Morocco)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0645\u063A\u0631\u0628)",flagCode:"ma",countryCode:"MA",dialCode:"+212"},{id:"ar-dz",name:"Arabic (Algeria)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u062C\u0632\u0627\u0626\u0631)",flagCode:"dz",countryCode:"DZ",dialCode:"+213"},{id:"ar-tn",name:"Arabic (Tunisia)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u062A\u0648\u0646\u0633)",flagCode:"tn",countryCode:"TN",dialCode:"+216"},{id:"ar-ly",name:"Arabic (Libya)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0644\u064A\u0628\u064A\u0627)",flagCode:"ly",countryCode:"LY",dialCode:"+218"},{id:"ar-mr",name:"Arabic (Mauritania)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627)",flagCode:"mr",countryCode:"MR",dialCode:"+222"},{id:"hi",name:"Hindi",nativeName:"\u0939\u093F\u0928\u094D\u0926\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"nl",name:"Dutch",nativeName:"Nederlands",countryCode:"NL",dialCode:"+31"},{id:"sv",name:"Swedish",nativeName:"Svenska",countryCode:"SE",dialCode:"+46"},{id:"da",name:"Danish",nativeName:"Dansk",countryCode:"DK",dialCode:"+45"},{id:"no",name:"Norwegian",nativeName:"Norsk",countryCode:"NO",dialCode:"+47"},{id:"fi",name:"Finnish",nativeName:"Suomi",countryCode:"FI",dialCode:"+358"},{id:"pl",name:"Polish",nativeName:"Polski",countryCode:"PL",dialCode:"+48"},{id:"tr",name:"Turkish",nativeName:"T\xFCrk\xE7e",countryCode:"TR",dialCode:"+90"},{id:"th",name:"Thai",nativeName:"\u0E44\u0E17\u0E22",countryCode:"TH",dialCode:"+66"},{id:"vi",name:"Vietnamese",nativeName:"Ti\u1EBFng Vi\u1EC7t",countryCode:"VN",dialCode:"+84"},{id:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",countryCode:"ID",dialCode:"+62"},{id:"ms",name:"Malay",nativeName:"Bahasa Melayu",flagCode:"my",countryCode:"MY",dialCode:"+60"},{id:"tl",name:"Filipino",nativeName:"Tagalog",countryCode:"PH",dialCode:"+63"},{id:"bg",name:"Bulgarian",nativeName:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",countryCode:"BG",dialCode:"+359"},{id:"cs",name:"Czech",nativeName:"\u010Ce\u0161tina",countryCode:"CZ",dialCode:"+420"},{id:"el",name:"Greek",nativeName:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",countryCode:"GR",dialCode:"+30"},{id:"he",name:"Hebrew",nativeName:"\u05E2\u05D1\u05E8\u05D9\u05EA",countryCode:"IL",dialCode:"+972"},{id:"hu",name:"Hungarian",nativeName:"Magyar",countryCode:"HU",dialCode:"+36"},{id:"is",name:"Icelandic",nativeName:"\xCDslenska",countryCode:"IS",dialCode:"+354"},{id:"lt",name:"Lithuanian",nativeName:"Lietuvi\u0173",countryCode:"LT",dialCode:"+370"},{id:"lv",name:"Latvian",nativeName:"Latvie\u0161u",countryCode:"LV",dialCode:"+371"},{id:"mt",name:"Maltese",nativeName:"Malti",countryCode:"MT",dialCode:"+356"},{id:"ro",name:"Romanian",nativeName:"Rom\xE2n\u0103",countryCode:"RO",dialCode:"+40"},{id:"sk",name:"Slovak",nativeName:"Sloven\u010Dina",countryCode:"SK",dialCode:"+421"},{id:"sl",name:"Slovenian",nativeName:"Sloven\u0161\u010Dina",flagCode:"si",countryCode:"SI",dialCode:"+386"},{id:"uk",name:"Ukrainian",nativeName:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flagCode:"ua",countryCode:"UA",dialCode:"+380"},{id:"et",name:"Estonian",nativeName:"Eesti",countryCode:"EE",dialCode:"+372"},{id:"ca",name:"Catalan",nativeName:"Catal\xE0",countryCode:"ES",dialCode:"+34"},{id:"eu",name:"Basque",nativeName:"Euskara",countryCode:"ES",dialCode:"+34"},{id:"gl",name:"Galician",nativeName:"Galego",countryCode:"ES",dialCode:"+34"},{id:"cy",name:"Welsh",nativeName:"Cymraeg",countryCode:"GB",dialCode:"+44"},{id:"ga",name:"Irish",nativeName:"Gaeilge",flagCode:"ie",countryCode:"IE",dialCode:"+353"},{id:"gd",name:"Scottish Gaelic",nativeName:"G\xE0idhlig",flagCode:"gb-sct",countryCode:"GB",dialCode:"+44"},{id:"br-fr",name:"Breton",nativeName:"Brezhoneg",flagCode:"bzh",countryCode:"FR",dialCode:"+33"},{id:"co",name:"Corsican",nativeName:"Corsu",flagCode:"fr-cor",countryCode:"FR",dialCode:"+33"},{id:"oc",name:"Occitan",nativeName:"Occitan",countryCode:"FR",dialCode:"+33"},{id:"rm",name:"Romansh",nativeName:"Rumantsch",countryCode:"CH",dialCode:"+41"},{id:"lb",name:"Luxembourgish",nativeName:"L\xEBtzebuergesch",countryCode:"LU",dialCode:"+352"},{id:"af",name:"Afrikaans",nativeName:"Afrikaans",countryCode:"ZA",dialCode:"+27"},{id:"sw",name:"Swahili",nativeName:"Kiswahili",countryCode:"KE",dialCode:"+254"},{id:"am",name:"Amharic",nativeName:"\u12A0\u121B\u122D\u129B",flagCode:"et",countryCode:"ET",dialCode:"+251"},{id:"bn",name:"Bengali",nativeName:"\u09AC\u09BE\u0982\u09B2\u09BE",flagCode:"bd",countryCode:"BD",dialCode:"+880"},{id:"gu",name:"Gujarati",nativeName:"\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"kn",name:"Kannada",nativeName:"\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ml",name:"Malayalam",nativeName:"\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"mr",name:"Marathi",nativeName:"\u092E\u0930\u093E\u0920\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ne",name:"Nepali",nativeName:"\u0928\u0947\u092A\u093E\u0932\u0940",flagCode:"np",countryCode:"NP",dialCode:"+977"},{id:"pa",name:"Punjabi",nativeName:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"si",name:"Sinhala",nativeName:"\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",countryCode:"LK",dialCode:"+94"},{id:"ta",name:"Tamil",nativeName:"\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"te",name:"Telugu",nativeName:"\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ur",name:"Urdu",nativeName:"\u0627\u0631\u062F\u0648",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"fa",name:"Persian",nativeName:"\u0641\u0627\u0631\u0633\u06CC",flagCode:"ir",countryCode:"IR",dialCode:"+98"},{id:"ps",name:"Pashto",nativeName:"\u067E\u069A\u062A\u0648",countryCode:"AF",dialCode:"+93"},{id:"uz",name:"Uzbek",nativeName:"O\u02BBzbek",countryCode:"UZ",dialCode:"+998"},{id:"kk",name:"Kazakh",nativeName:"\u049A\u0430\u0437\u0430\u049B",flagCode:"kz",countryCode:"KZ",dialCode:"+7"},{id:"ky",name:"Kyrgyz",nativeName:"\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430",flagCode:"kg",countryCode:"KG",dialCode:"+996"},{id:"tg",name:"Tajik",nativeName:"\u0422\u043E\u04B7\u0438\u043A\u04E3",flagCode:"tj",countryCode:"TJ",dialCode:"+992"},{id:"mn",name:"Mongolian",nativeName:"\u041C\u043E\u043D\u0433\u043E\u043B",countryCode:"MN",dialCode:"+976"},{id:"my",name:"Burmese",nativeName:"\u1019\u103C\u1014\u103A\u1019\u102C",flagCode:"mm",countryCode:"MM",dialCode:"+95"},{id:"km",name:"Khmer",nativeName:"\u1781\u17D2\u1798\u17C2\u179A",flagCode:"kh",countryCode:"KH",dialCode:"+855"},{id:"lo",name:"Lao",nativeName:"\u0EA5\u0EB2\u0EA7",flagCode:"la",countryCode:"LA",dialCode:"+856"},{id:"ka",name:"Georgian",nativeName:"\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",flagCode:"ge",countryCode:"GE",dialCode:"+995"},{id:"hy",name:"Armenian",nativeName:"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",flagCode:"am",countryCode:"AM",dialCode:"+374"},{id:"az",name:"Azerbaijani",nativeName:"Az\u0259rbaycan",countryCode:"AZ",dialCode:"+994"},{id:"be",name:"Belarusian",nativeName:"\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",flagCode:"by",countryCode:"BY",dialCode:"+375"},{id:"mk",name:"Macedonian",nativeName:"\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",countryCode:"MK",dialCode:"+389"},{id:"sr",name:"Serbian",nativeName:"\u0421\u0440\u043F\u0441\u043A\u0438",countryCode:"RS",dialCode:"+381"},{id:"bs",name:"Bosnian",nativeName:"Bosanski",flagCode:"ba",countryCode:"BA",dialCode:"+387"},{id:"hr",name:"Croatian",nativeName:"Hrvatski",countryCode:"HR",dialCode:"+385"},{id:"sq",name:"Albanian",nativeName:"Shqip",flagCode:"al",countryCode:"AL",dialCode:"+355"},{id:"md",name:"Moldovan",nativeName:"Moldoveneasc\u0103",countryCode:"MD",dialCode:"+373"}],ks={US:"United States",GB:"United Kingdom",CA:"Canada",AU:"Australia",IE:"Ireland",FR:"France",BE:"Belgium",CH:"Switzerland",DE:"Germany",AT:"Austria",IT:"Italy",PT:"Portugal",BR:"Brazil",ES:"Spain",MX:"Mexico",AR:"Argentina",RU:"Russia",JP:"Japan",KR:"South Korea",CN:"China",SE:"Sweden",NO:"Norway",DK:"Denmark",FI:"Finland",NL:"Netherlands",PL:"Poland",CZ:"Czech Republic",HU:"Hungary",RO:"Romania",BG:"Bulgaria",GR:"Greece",TR:"Turkey",IL:"Israel",IN:"India",ZA:"South Africa"};function Ds(){return jn.filter(o=>o.countryCode!==void 0&&o.dialCode!==void 0).map(o=>({code:o.countryCode,dialCode:o.dialCode,flagCode:o.flagCode||o.id,name:o.countryName||ks[o.countryCode]||o.name}))}var Ts=Ds(),Ke="/flags";function lt(o){return`${o.toLowerCase()}.svg`}function It(o){return jn.find(t=>t.id===o)?.flagCode||o}function ct(){return[...new Set(Ts.map(o=>o.flagCode))]}var Te={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Os="public/logo.svg is missing: it is the site logo (Organization / publisher logo in the JSON-LD, the default logo) and the source of the favicon, PWA icons and og-image.png. Add public/logo.svg.",zn="/manifest.json",Ye=class extends fe{constructor(e,t={}){super(e,{assets:pe.assets.fallback,assetPatterns:pe.assets.patterns,frameworkPackage:kt.package,assetsPath:kt.assetsPath,modernFormats:pe.assets.modern,...t}),this.hasRunForSession=!1,this.flagCodes=null,this.entityResolver=null}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _prepareFiles(){let e=this.pathResolver.getAppRoot(),t=await this._ensureDefaultAssets(e);if(this.flagCodes){let i=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(i?[...new Set([...this.flagCodes,...ct()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${Ke}/: ${l.join(", ")}`)}let n=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(n)||this.logger.warn(Os);let s=[],a=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(s=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:s}}async _processFiles(e,{copiedAssets:t,generatedAssets:n}){let r=this.pathResolver.getAppRoot(),{consumerFiles:s}=e,a=await this._processAssetFiles(s),i=this._buildAssetManifest(a,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${zn}`))}),l=await this._readLogoSvgContent("/logo.svg",r);return{assets:a,manifest:{...i,logoSvgContent:l},copiedAssets:t,generatedAssets:n}}_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`}useFlagCodes(e,t){this.flagCodes=e,this.entityResolver=t}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 n=this.getAssets().map(s=>s.path),r=t||this.options.modernFormats;for(let s of r){let a=`/${e}.${s}`;if(n.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let n=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${n}`),!n)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath($e.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let s of this.options.assets)await this._ensureAsset(s,r,n)&&t.push(s);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(n){this.logger.debug(`Failed to ensure default assets: ${n.message}`)}return t}async _ensureAsset(e,t,n){let r=this.pathResolver.resolveAppPath(`${$e.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let s=this.pathResolver.normalizePath(`${n}/${e}`);if(this.pathResolver.pathExists(s)){if(await this.pathResolver.copy(s,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}_ensureFlags(e){let t=this.pathResolver.resolveFrameworkPackage("@donotdev/core");if(!t)throw new Error("Flag copy: @donotdev/core not found");let n=this.pathResolver.normalizePath(`${t}/${Fe.PUBLISHED_FLAGS}`),r=`${$e.public}${Ke}`,s=[];for(let a of e){let i=lt(a),l=this.pathResolver.resolveAppPath(`${r}/${i}`);if(this.pathResolver.pathExists(l))continue;let c=`${n}/${i}`;if(!this.pathResolver.pathExists(c)){this.logger.warn(`No flag artwork for "${a}": add ${r}/${i} to the app`);continue}if(!this.pathResolver.copySync(c,l))throw new Error(`Flag copy: cannot copy ${c} to ${l}`);s.push(i)}return s}async _processAssetFiles(e){let t=[];for(let n of e)try{let r=this.pathResolver.getFileInfo(n);if(r&&r.isFile){let s=n.split("/").pop()||n.split("\\").pop(),a=this._analyzeAsset(s,r.size);a&&t.push(a)}}catch(r){this.logger.debug(`Error processing asset file ${n}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let n=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:n,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 n=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(n)?"image":["woff2","woff","ttf","otf"].includes(n)?"font":["json"].includes(n)?"json":["ico"].includes(n)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}_matchesPattern(e,t){let n=t.split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let n=e.map(s=>s.path);return{logo:{optimal:this._getOptimalAsset("logo",n,this.options.modernFormats),fallback:this._getOptimalAsset("logo",n,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",n,["svg","ico"]),fallback:this._getOptimalAsset("favicon",n,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",n,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",n,["png"]),512:this._getOptimalAsset("android-chrome-512x512",n,["png"])},manifest:t?zn:null,modernFormats:e.filter(s=>s.isModern).map(s=>s.path),fallbackFormats:e.filter(s=>!s.isModern).map(s=>s.path)}}_getOptimalAsset(e,t,n){for(let r of n){let s=`/${e}.${r}`;if(t.includes(s))return s}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),n=await this._resolvePackage("@donotdev/ui",t);if(!n)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${n}/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 n=this.pathResolver.resolveFrameworkPackage(e,t);return n?(this.logger.debug(`Found package: ${n}`),n):(this.logger.debug(`Package ${e} not found`),null)}catch(n){return this.logger.debug(`Error resolving package ${e}: ${n.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 n=e.slice(1),r=this.pathResolver.resolveAppPath(`${$e.public}/${n}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(n){return this.logger.debug(`Failed to read logo SVG content: ${n.message}`),null}}async _renderOgImage(e,t){let{width:n,height:r}=await e(t).metadata(),s=Math.min(Te.logoWidth/n,Te.logoHeight/r),a=await e(t,{density:Math.ceil(72*s)}).resize(Te.logoWidth,Te.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:Te.width,height:Te.height,channels:4,background:Te.background}}).composite([{input:a}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),n=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"}],s=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...s,...r].map(u=>u.name),error:"Failed to read logo.svg"};for(let u of s){let p=`${n}/${u.name}`;if(this.pathResolver.pathExists(p)){i.push(u.name);continue}try{await this.pathResolver.write(p,l),a.push(u.name)}catch(d){this.logger.debug(`Failed to copy ${u.name}: ${d.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 d=`${n}/${p.name}`;if(this.pathResolver.pathExists(d)){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}}),g;p.format==="ico"?g=await f.toFormat("png").toBuffer():g=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(d,g),a.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),i.push(p.name)}}let u=qe.slice(1);if(this.pathResolver.pathExists(`${n}/${u}`))i.push(u);else try{let p=await this._renderOgImage(c.default,t);await this.pathResolver.write(`${n}/${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:[...s,...r].map(c=>c.name),error:l.message}}}};Y();var Is={isEmpty:o=>!o.manifest||o.assets?.length===0,generateModule:(o,e,t="assets")=>{let{manifest:n,assets:r,copiedAssets:s}=o,a=n.logoSvgContent||null,i={totalAssets:r.length,copiedAssets:s.length,hasLogo:n.logo.optimal!==null,hasFavicon:n.favicon.optimal!==null,hasManifest:n.manifest!==null,timestamp:new Date().toISOString()};return`// ${V.assets} - Generated asset manifest
54
+ const assetManifest = ${JSON.stringify(n,null,2)};
55
55
  const assetStats = ${JSON.stringify(i,null,2)};
56
56
 
57
57
  // Populate unified DnDev config for runtime access
@@ -68,7 +68,7 @@ if (typeof globalThis !== 'undefined') {
68
68
  }
69
69
 
70
70
  // Populate assets configuration
71
- globalThis._DNDEV_CONFIG_.${K[t]} = {
71
+ globalThis._DNDEV_CONFIG_.${oe[t]} = {
72
72
  mapping: assetManifest,
73
73
  logoSvgContent: ${JSON.stringify(a)},
74
74
  manifest: {
@@ -120,7 +120,7 @@ export default {
120
120
  getManifest,
121
121
  getAllAssets
122
122
  };
123
- `},generateEmpty:(o,e,t,s="assets")=>{let r={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${z.assets} - Empty asset manifest
123
+ `},generateEmpty:(o,e,t,n="assets")=>{let r={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${V.assets} - Empty asset manifest
124
124
  const assetManifest = {
125
125
  logo: { optimal: null, fallback: null },
126
126
  favicon: { optimal: null, fallback: null },
@@ -146,7 +146,7 @@ if (typeof globalThis !== 'undefined') {
146
146
  }
147
147
 
148
148
  // Populate empty assets configuration
149
- globalThis._DNDEV_CONFIG_.${K[s]} = {
149
+ globalThis._DNDEV_CONFIG_.${oe[n]} = {
150
150
  mapping: assetManifest,
151
151
  logoSvgContent: null,
152
152
  manifest: {
@@ -190,7 +190,7 @@ export default {
190
190
  getManifest,
191
191
  getAllAssets
192
192
  };
193
- `},generateInspection:o=>{let{assets:e,manifest:t,copiedAssets:s}=o;return!e||e.length===0?`/**
193
+ `},generateInspection:o=>{let{assets:e,manifest:t,copiedAssets:n}=o;return!e||e.length===0?`/**
194
194
  * Generated Asset Discovery Results
195
195
  * Source: empty
196
196
  * Generated at: ${new Date().toISOString()}
@@ -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 '${z.assets}'
222
+ * Import from '${V.assets}'
223
223
  */
224
224
 
225
225
  export const discoveredAssets = ${JSON.stringify(e,null,2)};
@@ -228,7 +228,7 @@ export const assetManifest = ${JSON.stringify(t,null,2)};
228
228
 
229
229
  export const assetStats = {
230
230
  totalAssets: ${e.length},
231
- copiedAssets: ${s.length},
231
+ copiedAssets: ${n.length},
232
232
  hasLogo: ${t.logo.optimal!==null},
233
233
  hasFavicon: ${t.favicon.optimal!==null},
234
234
  hasManifest: ${t.manifest!==null},
@@ -236,17 +236,17 @@ export const assetStats = {
236
236
  };
237
237
 
238
238
  export default discoveredAssets;
239
- `},generateManifest:o=>({assets:o.assets?.length||0,copied:o.copiedAssets?.length||0,timestamp:Date.now(),hasLogo:o.manifest?.logo?.optimal!==null,hasFavicon:o.manifest?.favicon?.optimal!==null}),logConfig:o=>{},logStats:(o,e,t)=>{let s=o.assets?.length||0,r=o.generatedAssets?.length||0;t&&(r>0?t.info(`${e} Assets: ${s} found, ${r} generated`):t.info(`${e} Assets: ${s} found`))}},Mr=[o=>o.includes("/public/"),o=>o.endsWith(".png")||o.endsWith(".svg")||o.endsWith(".ico"),o=>o.includes("favicon")||o.includes("logo")||o.includes("manifest")];function Zt(o={}){let e=he({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:z.assets,DiscoveryClass:Je,discoveryMethod:"discoverAssets",filePatterns:Mr,templates:Ir,manifestFileName:de.manifests.asset,configKey:"assets"})(o),t=E.getInstance(),s=T("asset-plugin",o.debug,o.verbose),r=e.buildStart;return e.buildStart=async function(...n){r&&await r.apply(this,n)},e}B();var Qt=z.blog,Xt="\0"+Qt;function es(){return{name:"dndev-vite-blog",resolveId(o){if(o===Qt)return Xt},load(o){if(o===Xt)return`
239
+ `},generateManifest:o=>({assets:o.assets?.length||0,copied:o.copiedAssets?.length||0,timestamp:Date.now(),hasLogo:o.manifest?.logo?.optimal!==null,hasFavicon:o.manifest?.favicon?.optimal!==null}),logConfig:o=>{},logStats:(o,e,t)=>{let n=o.assets?.length||0,r=o.generatedAssets?.length||0;t&&(r>0?t.info(`${e} Assets: ${n} found, ${r} generated`):t.info(`${e} Assets: ${n} found`))}},Fs=[o=>o.includes("/public/"),o=>o.endsWith(".png")||o.endsWith(".svg")||o.endsWith(".ico"),o=>o.includes("favicon")||o.includes("logo")||o.includes("manifest")];function Bn({i18nStore:o,routeManifest:e,...t}={}){if(!o||!e)throw new Error("[dndev] createViteAssetPlugin: options.i18nStore and options.routeManifest are required (createVitePlugins passes the i18n and route plugins' stores).");let n=null,r=we({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:V.assets,DiscoveryClass:Ye,createDiscovery:(l,c)=>(n=new Ye(l,c),n),discoveryMethod:"discoverAssets",filePatterns:Fs,templates:Is,manifestFileName:ve.manifests.asset,configKey:"assets"})(t),s=r.buildStart,a=r.configureServer,i=null;return r.configureServer=function(l){return i=l,a.call(this,l)},r.buildStart=async function(...l){let[{flagCodes:c},u]=await Promise.all([o.ready(),e.entityResolver()]);n.useFlagCodes(c,u);let p=O.getInstance(),d=[...new Set([...c??[],...ct()])].map(f=>p.resolveAppPath(`public${Ke}/${lt(f)}`)).filter(f=>!p.pathExists(f));if(await s.apply(this,l),i)for(let f of d)p.pathExists(f)&&i.watcher.emit("add",f)},r}q();var Wn=V.blog,Un="\0"+Wn;function Gn(){return{name:"dndev-vite-blog",resolveId(o){if(o===Wn)return Un},load(o){if(o===Un)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 Lr}from"vite";B();var ts={isEmpty:o=>!o.env||Object.keys(o.env).length===0,generateModule:(o,e,t="env")=>{let{env:s,mode:r}=o;if(!s||Object.keys(s).length===0)return ts.generateEmpty(o,e,void 0,t);let n={totalVars:Object.keys(s).length,mode:r,source:o.source,generatedAt:new Date().toISOString()};return`// ${z.env} - Generated environment variables
246
+ `}}}import{loadEnv as Ms}from"vite";q();var Hn={isEmpty:o=>!o.env||Object.keys(o.env).length===0,generateModule:(o,e,t="env")=>{let{env:n,mode:r}=o;if(!n||Object.keys(n).length===0)return Hn.generateEmpty(o,e,void 0,t);let s={totalVars:Object.keys(n).length,mode:r,source:o.source,generatedAt:new Date().toISOString()};return`// ${V.env} - Generated environment variables
247
247
 
248
- const envData = ${JSON.stringify(s,null,2)};
249
- const envManifest = ${JSON.stringify(n,null,2)};
248
+ const envData = ${JSON.stringify(n,null,2)};
249
+ const envManifest = ${JSON.stringify(s,null,2)};
250
250
 
251
251
  // Freeze env data to prevent runtime tampering
252
252
  Object.freeze(envData);
@@ -272,7 +272,7 @@ if (typeof globalThis !== 'undefined') {
272
272
  }
273
273
 
274
274
  // Populate env configuration (frozen to prevent tampering)
275
- globalThis._DNDEV_CONFIG_.${K[t]} = envData;
275
+ globalThis._DNDEV_CONFIG_.${oe[t]} = envData;
276
276
  // Only freeze the env property, not the entire config (other plugins need to add properties)
277
277
  }
278
278
 
@@ -283,7 +283,7 @@ export const source = '${o.source}';
283
283
 
284
284
  // Default export
285
285
  export default envData;
286
- `},generateEmpty:(o,e,t,s="env")=>{let r={totalVars:0,mode:o.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${z.env} - Empty environment data
286
+ `},generateEmpty:(o,e,t,n="env")=>{let r={totalVars:0,mode:o.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${V.env} - Empty environment data
287
287
 
288
288
  const envData = {};
289
289
  const envManifest = ${JSON.stringify(r,null,2)};
@@ -312,7 +312,7 @@ if (typeof globalThis !== 'undefined') {
312
312
  }
313
313
 
314
314
  // Populate empty env configuration (frozen to prevent tampering)
315
- globalThis._DNDEV_CONFIG_.${K[s]} = envData;
315
+ globalThis._DNDEV_CONFIG_.${oe[n]} = envData;
316
316
  // Only freeze the env property, not the entire config (other plugins need to add properties)
317
317
  }
318
318
 
@@ -322,31 +322,37 @@ export const source = 'empty';
322
322
 
323
323
  export default envData;
324
324
  `},generateInspection:o=>{let{env:e,mode:t}=o;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:o=>({totalVars:Object.keys(o?.env||{}).length,mode:o?.mode||"development",variables:Object.keys(o?.env||{}),timestamp:Date.now()}),logStats:(o,e,t)=>{let s=Object.keys(o.env).length;t&&t.info(`${e} Env: ${s} VITE_* variables`)}},ut=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={...Lr(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 ss(o={}){return he({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:z.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:ts,manifestFileName:de.manifests.env,configKey:"env",createDiscovery:(e,t)=>new ut(e,{...t,mode:o.mode||t.mode||"development"})})({...o,disableHmr:!0})}B();var jr=["--font-family","--font-headline","--font-mono"],Ce=":root",zr=/\/\*[\s\S]*?\*\//g,Ur=/([^{}]+)\{([^{}]*)\}/g,Wr=/^(?::root|html|:where\(:root\))$/,Gr=/^(?::root|html)?\.([a-z][\w-]*)$/i,Br=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/;function os(o){let e=[],t=0,s="",r=0;for(let n=0;n<o.length;n++){let a=o[n];s?a===s&&(s=""):a==='"'||a==="'"?s=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(o.slice(r,n)),r=n+1)}return e.push(o.slice(r)),e.map(n=>n.trim())}function Vr(o){if(Wr.test(o))return Ce;let e=Gr.exec(o);return e?e[1]:null}function rs(o){let e=new Map,t=o.replace(zr,"");for(let[,s,r]of t.matchAll(Ur)){let n=s.split(";").pop(),a=os(n).map(Vr).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 pt(o,e,t){let s=os(o)[0];if(!s)return null;let r=Br.exec(s);if(r){let[,n,a]=r;return e.has(n)&&!t.has(n)?pt(e.get(n),e,new Set([...t,n])):a===void 0?null:pt(a,e,t)}return s.replace(/^['"]|['"]$/g,"").trim()}function ns({frameworkCss:o,appCss:e}){let t=rs(o),s=rs(e.join(`
326
- `)),r=new Set([Ce,...t.keys(),...s.keys()]),n=new Set;for(let a of r){let i=new Map([...t.get(Ce)??[],...s.get(Ce)??[],...a===Ce?[]:t.get(a)??[],...a===Ce?[]:s.get(a)??[]]);for(let l of jr){if(!i.has(l))continue;let u=pt(i.get(l),i,new Set([l]));u&&n.add(u)}}return[...n]}var Hr=new Map(Object.entries(Tt).map(([o,e])=>[o.toLowerCase(),e]));function as({families:o,locales:e=[]}){if(!Array.isArray(o))throw new Error("resolveFontManifest: families is required (ThemeDiscovery fontFamilies)");let t=new Set;for(let n of o){let a=Hr.get(n.toLowerCase());a&&t.add(a)}let s=new Set(["latin"]);for(let n of e)for(let a of Ct[n]??[])s.add(a);let r=new Set;for(let n of t)for(let a of s)for(let i of lt[n])r.add(`${n}-${a}-${i}-normal`);return{fontStems:t,subsets:s,stems:r}}function ft(o){let e=o.split(/[/\\]/).pop().toLowerCase();for(let t of Object.keys(lt)){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 is(o){return o.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}B();G();B();function Jr(o){if(!o)return[];let e=E.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",o);if(!s)return[];let r=e.getDirname(e.getDirname(s)),n;try{n=e.readdirSync(r)}catch{return[]}for(let a of n)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 qr(o){if(!o)return[];let e=E.getInstance();try{let t=e.resolvePath("package.json",o),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[n,a]of Object.entries(s.peerDependenciesMeta))a?.optional&&r.add(n);if(s.optionalDependencies)for(let n of Object.keys(s.optionalDependencies))r.add(n);return Array.from(r)}catch{return[]}}function Yr(o){let e=ye.optionalFeatures||[],t=Jr(o),s=qr(o);return[...new Set([...e,...t,...s])]}function Kr(o){let e=E.getInstance();try{let t=e.resolvePath("package.json",o),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 Zr(o,e,t){if(t.resolvePackage(o,e||void 0))return!0;let s=o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0],r=e;for(let n=0;n<10;n++){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(o){let e=Yr(o),t=[],s=[],r=E.getInstance(),n=Kr(o);for(let a of e)a.startsWith("@donotdev/")?n.has(a)?s.push(a):t.push(a):n.has(a)&&Zr(a,o,r)?s.push(a):t.push(a);return{missing:t,installed:s}}var Ee=class o extends le{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 n of Object.keys(r))t.includes(n)||delete r[n];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 n=Ve("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map($=>{let A=$.endsWith(".json")?$:`${$}/*_*.json`;return this.pathResolver.resolveAppPath(A)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let u=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${u.join(", ")}, framework lazy: ${c.join(", ")}`),u.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),f=($,A)=>{let M=this.pathResolver.normalizePath($),U=this.pathResolver.normalizePath(A);return M.startsWith(U)?M.slice(U.length+1):M},m=a.map($=>f($,t)),v=[...i,...l].map($=>f($,t)),x=u.map($=>f($,s)),P=c.map($=>f($,s)),b={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},D=await this.pathResolver._globWithNormalization(m,b),S=await this.pathResolver._globWithNormalization(v,b),k={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:n.ignore?.filter($=>$!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(k.ignore)}`);let N=await this.pathResolver._globWithNormalization(x,k),h=await this.pathResolver._globWithNormalization(P,k);this.logger.debug(`Found ${D.length} eager, ${S.length} lazy, ${N.length} framework eager, ${h.length} framework lazy files`),N.length>0?this.logger.debug(`Framework eager files (first 3): ${N.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${u.join(", ")}`),h.length>0?this.logger.debug(`Framework lazy files (first 3): ${h.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let F=[...new Set([...D,...S,...N,...h])],C=new Set([...D,...N]),d={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:L}=qe(t),j=new Set(L.filter($=>$.startsWith("@donotdev/")).map($=>$.replace("@donotdev/","")));j.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...j].join(", ")}] (packages not installed)`);let I=new Map,V=[...N,...h];for(let $ of V){let A=this._processTranslationFile($,N.includes($),t);if(A){if(j.has(A.namespace))continue;let M=`${A.namespace}_${A.language}`;I.set(M,A),d.allNamespaces.add(A.namespace),d.supportedLanguages.add(A.language),N.includes($)&&d.eagerNamespaces.add(A.namespace)}}let te=new Set;for(let $ of F){if(V.includes($))continue;let A=this._processTranslationFile($,C.has($),t);if(A){let{namespace:M,language:U,importPath:pe,content:_e}=A,w=`${A.namespace}_${A.language}`;if(I.has(w)){let _=I.get(w);A.content=this._mergeTranslations(_.content,_e)}d.allNamespaces.add(M),d.supportedLanguages.add(U),te.add(U),C.has($)&&d.eagerNamespaces.add(M),d.mapping[M]||(d.mapping[M]={}),d.mapping[M][U]=pe,A.content&&(d.content[M]||(d.content[M]={}),d.content[M][U]=A.content),d.files.push({path:$,relativePath:this.pathResolver.getRelativePath($),namespace:M,language:U,eager:C.has($),size:A.content?JSON.stringify(A.content).length:0})}}for(let[$,A]of I){let M=$.lastIndexOf("_"),U=$.slice(0,M),pe=$.slice(M+1);te.size>0&&!te.has(pe)||(!d.mapping[U]||!d.mapping[U][pe])&&(d.mapping[U]||(d.mapping[U]={}),d.mapping[U][pe]=A.importPath,d.content[U]||(d.content[U]={}),d.content[U][pe]=A.content,d.files.push({path:A.absolutePath,relativePath:this.pathResolver.getRelativePath(A.absolutePath),namespace:U,language:pe,eager:d.eagerNamespaces.has(U),size:A.content?JSON.stringify(A.content).length:0}))}let Y=te.size>0?[...te].sort():[this.options.fallbackLanguage],ue=this._getLanguageAllowlist(),W=Y;if(ue){let $=Y.filter(M=>ue.includes(M));W=$.length>0?$:[this.options.fallbackLanguage],this._restrictByLanguage(d.mapping,W),this._restrictByLanguage(d.content,W),d.files=d.files.filter(M=>W.includes(M.language));let A=new Set(Object.keys(d.mapping));d.allNamespaces=new Set([...d.allNamespaces].filter(M=>A.has(M))),d.eagerNamespaces=new Set([...d.eagerNamespaces].filter(M=>A.has(M))),this.logger.debug(`I18n restricted by i18n.only [${ue.join(", ")}]: languages [${W.join(", ")}], namespaces ${A.size}`)}let Re=[...new Set(W.map($=>o.LANGUAGE_FLAG_OVERRIDES[$]||$))];return{mapping:d.mapping,content:d.content,eagerNamespaces:[...d.eagerNamespaces].sort(),allNamespaces:[...d.allNamespaces].sort(),supportedLanguages:W,fallbackLanguage:this.options.fallbackLanguage,flagCodes:Re,files:d.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[o.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()||"",n,a,i=r.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,n,a]=i,!n||!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:n,language:a,importPath:u,absolutePath:e,content:c}}_mergeTranslations(e,t){let s={...e};for(let[r,n]of Object.entries(t))typeof n=="object"&&n!==null&&!Array.isArray(n)?s[r]=this._mergeTranslations(s[r]||{},n):s[r]=n;return s}};B();B();var Fe=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:{...it.selectors,...this.options.customPatterns?.selectors},themes:{...it.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=[],n,a=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(n=l.exec(i))!==null;){let[,u,c,p]=n;if(!u||!p)continue;let g=c.match(this.patterns.themes.themeIcon),f=c.match(this.patterns.themes.themeIsDark),m={name:u,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${u} (${p})`),r.push(m),s.themes.set(u,{name:u,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 n=r.slice(1);n.startsWith("_")||t.classes.add(n)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(n=>{n.startsWith("--")&&n.length>2?s==="framework"?t.variables.framework.add(n):t.variables.consumer.add(n):this._debug(`Skipping invalid CSS variable: ${n}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let n=r.replace("@keyframes","").trim();n&&t.keyframes.add(n)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(n=>{t.push(`Possible malformed CSS variable: ${n}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(n=>{if(!n.includes("--theme-label")&&n.includes("--")){let a=n.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&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},n=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:n,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 ls="@donotdev/components/styles",Xr=/@import\s+['"](\.[^'"]+)['"]\s*;/g,$e=class extends le{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new Fe(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),n=this._serializeThemes(),a=ns({frameworkCss:this._readFrameworkTokenCss(),appCss:r});return this.logger.debug("Theme font families:",a),this.logger.debug(`Discovered ${n.length} themes:`,n.map(i=>i.name)),{themes:n,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 ct.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 n=this.pathResolver.normalizePath(s);this.cssExtractor.extractThemes(r,n,this.discovered),this.cssExtractor.extractVariables(r,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(n)}`)}catch(r){this.logger.debug(`Error scanning consumer file ${s}: ${r.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(ls,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw new Error(`Theme discovery: cannot resolve ${ls} (framework font defaults)`);let t=new Set,s=r=>{if(t.has(r))return"";t.add(r);let n=this.pathResolver.readSync(r,{format:"text"});if(typeof n!="string")throw new Error(`Theme discovery: cannot read ${r}`);let a=this.pathResolver.getDirname(r);return n.replace(Xr,(i,l)=>s(this.pathResolver.resolvePath(l,a)))};return s(e)}_addEssentialThemes(){ct.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}))}};G();var Qr=3,gt="<!-- DNDEV_FONT_PRELOADS -->",eo=/url\(\s*['"]?([^'")]+)['"]?\s*\)/g;function cs(o={}){let{debug:e=!1,i18nOptions:t={}}=o,s=T("font-preload",e,!1),r,n={},a=!1,i=null,l=[];return{name:"vite-font-preload-plugin",enforce:"post",configResolved(u){a=u.command==="build",n={root:u.root,base:u.base&&u.base!=="/"?u.base.replace(/\/$/,""):"",outDir:u.build?.outDir??"dist"};try{r=E.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 R=await new Ee(r,{fallbackLanguage:t.fallbackLanguage||"en",only:t.only}).discoverTranslations();R?.supportedLanguages?.length&&(c=R.supportedLanguages)}catch(m){s.debug(`Font preload: i18n discovery failed, using 'en': ${m?.message}`)}let p=new $e(null,r,{debug:e}),{fontFamilies:g}=await p.discoverThemes(),f=as({families:g,locales:c});i=f.stems,s.debug(`Font filter: ${f.fontStems.size} font(s) [${[...f.fontStems].join(", ")}], ${f.subsets.size} subset(s), ${i.size} allowed stem(s)`)},generateBundle(u,c){if(!i)return;let p=x=>ft(x)!==null,g=x=>i.has(ft(x)),f=0,m=0;for(let x of Object.keys(c))c[x].type!=="asset"||!p(x)||(x.endsWith(".woff")?(delete c[x],f++):x.endsWith(".woff2")&&!g(x)&&(delete c[x],m++));s.debug(`Font filter: deleted ${f} .woff + ${m} .woff2 from bundle`);for(let[x,P]of Object.entries(c)){if(P.type!=="asset"||!x.endsWith(".css")||typeof P.source!="string")continue;let b=P.source,D=b.replace(/@font-face\s*\{[\s\S]*?\}/g,S=>{let k=[...S.matchAll(eo)].map(N=>N[1]);return k.some(p)?k.some(g)?is(S):"":S});D!==b&&(P.source=D)}let R=n.base||"",v=[];for(let[x,P]of Object.entries(c)){if(P.type!=="asset"||!x.endsWith(".woff2")||!g(x))continue;let b=R?`${R}/${x}`:`/${x}`;v.push(b)}l=v.slice(0,Qr)},writeBundle(){if(!a||!l.length)return;let u=r||E.getInstance(),c=n.root||process.cwd(),p=n.outDir||"dist",g=u.resolvePath(`${p}/index.html`,c);try{if(!u.pathExists(g)){s.debug(`Font preload: index.html not found at ${g}`);return}let f=u.readSync(g,{format:"text"}),m=l.map(R=>`<link rel="preload" as="font" href="${R}" type="font/woff2" crossorigin="anonymous" />`).join(`
327
- `);if(f.includes(gt))f=f.replace(gt,`${gt}
328
- ${m}`);else{let R=f.indexOf("<!-- Fonts:"),v=R!==-1?f.indexOf("-->",R)+3:f.indexOf("</head>");v!==-1&&(f=f.slice(0,v)+`
329
- ${m}`+f.slice(v))}u.writeSync(g,f,{overwrite:!0}),s.debug(`Font preload: injected ${l.length} link(s)`)}catch(f){s.debug(`Font preload: write failed: ${f?.message}`)}}}}import{existsSync as ds,readFileSync as ms,writeFileSync as to}from"node:fs";import{join as hs}from"node:path";var so="/(.*)",mt=Object.freeze(["default-src","script-src","style-src","img-src","font-src","connect-src","media-src","worker-src","manifest-src","frame-src","object-src","base-uri","form-action","frame-ancestors"]),ro=Object.freeze({"default-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"frame-src":["'none'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"]}),us=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),vs=Object.freeze({"@donotdev/supabase":{"connect-src":["https://*.supabase.co","wss://*.supabase.co"]},"@donotdev/firebase":{"script-src":["https://accounts.google.com","https://apis.google.com"],"connect-src":["https://identitytoolkit.googleapis.com","https://securetoken.googleapis.com","https://www.googleapis.com","https://*.googleapis.com","https://*.firebaseio.com"],"frame-src":["https://accounts.google.com"]}}),oo=Object.freeze([{key:"X-Content-Type-Options",value:"nosniff"},{key:"X-Frame-Options",value:"DENY"},{key:"X-XSS-Protection",value:"1; mode=block"},{key:"Referrer-Policy",value:"strict-origin-when-cross-origin"},{key:"Permissions-Policy",value:"geolocation=(), microphone=(), camera=()"}]),no=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),ao=31536e3,io=86400,ys=3600,ps=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(o=>`/assets/:path*.${o}`),"next-export":["/_next/static/:path*"],next:[]}),lo=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),co=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${ys}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),fs=Object.freeze(["csp","cache"]);function Ye(o,e=!1){return`public, max-age=${o}${e?", immutable":""}`}function dt(o,e){return{source:o,headers:[{key:"Cache-Control",value:e}]}}var gs=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),uo=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function po(o,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${o}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!gs.includes(e)&&!uo.test(e))throw new Error(`[dndev] appConfig.headers.csp['${o}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${gs.join(" ")} or a hash like 'sha256-<base64>').`)}function fo(o){if(o===void 0)return{csp:{},cache:[]};if(!o||typeof o!="object"||Array.isArray(o))throw new Error("[dndev] appConfig.headers must be an object.");for(let s of Object.keys(o))if(!fs.includes(s))throw new Error(`[dndev] appConfig.headers.${s} is not a header option (allowed: ${fs.join(", ")}).`);let e=o.csp??{};for(let[s,r]of Object.entries(e)){if(!mt.includes(s))throw new Error(`[dndev] appConfig.headers.csp['${s}'] is not a CSP directive the framework merges (allowed: ${mt.join(", ")}).`);if(!Array.isArray(r))throw new Error(`[dndev] appConfig.headers.csp['${s}'] must be an array of sources.`);for(let n of r)po(s,n)}let t=o.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let s of t){if(typeof s?.source!="string"||!s.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(s?.source)}).`);if(!Number.isInteger(s.maxAge)||s.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${s.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(s.maxAge)}).`)}return{csp:e,cache:t}}function go({csp:o={},providers:e=[],target:t}){if(!(t in us))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...mt.map(r=>{let n=[...r==="script-src"?us[t]:ro[r]??[],...e.flatMap(l=>vs[l]?.[r]??[]),...o[r]??[]],a=[...new Set(n)],i=a.length>1?a.filter(l=>l!=="'none'"):a;return i.length>0?`${r} ${i.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function bs({appConfig:o,target:e,providers:t=[],pwa:s=!1}){if(!(e in ps))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:r,cache:n}=fo(o?.headers),a=[{key:"Content-Security-Policy",value:go({csp:r,providers:t,target:e})},...o?.seo===!1?[no]:[],...oo].map(i=>({...i}));return[{source:so,headers:a},...ps[e].map(i=>dt(i,Ye(ao,!0))),...lo.map(i=>dt(`/:path*.${i}`,Ye(io))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:Ye(ys)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...s?co.map(i=>({source:i.source,headers:i.headers.map(l=>({...l}))})):[],...n.map(i=>dt(i.source,Ye(i.maxAge,i.immutable===!0)))]}function ws(o){let e=hs(o,"package.json");if(!ds(e))return[];let t=JSON.parse(ms(e,"utf8")),s={...t.dependencies,...t.devDependencies};return Object.keys(vs).filter(r=>!!s[r])}function mo(o){let e=hs(o,"vercel.json");if(!ds(e))return null;try{return{path:e,config:JSON.parse(ms(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function xs({appRoot:o,rules:e,ci:t,logger:s}){let r=mo(o);if(!r)return"absent";if(JSON.stringify(r.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${r.path}: "headers" differ from the framework header policy (appConfig.headers, appConfig.seo). The host reads the committed file, so this deploy would serve stale headers. Run the app locally (dev or build) to regenerate vercel.json, then commit it.`);let n=`${JSON.stringify({...r.config,headers:e},null,2)}
330
- `;return to(r.path,n),s?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function Ss({appConfig:o,pwa:e,debug:t,verbose:s}){let r=T("host-headers",t,s);return{name:"dndev-host-headers",configResolved(n){xs({appRoot:n.root,rules:bs({appConfig:o,target:"vite",providers:ws(n.root),pwa:e===!0}),ci:!!(process.env.CI||process.env.VERCEL),logger:r})}}}B();G();var Rs={isEmpty:o=>!o.mapping||Object.keys(o.mapping).length===0,generateModule:(o,e,t="i18n",s=!1)=>{let{mapping:r,eagerNamespaces:n,supportedLanguages:a,fallbackLanguage:i,stats:l,content:u={},files:c=[]}=o,p=s?Object.keys(u):n,g={};for(let x of p)u[x]&&(g[x]=u[x]);let f=[...new Set([...n,...Object.keys(u)])],m={mapping:r,languages:a,eager:s?f:n,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},R=[];if(!s)for(let[x,P]of Object.entries(r)){if(n.includes(x))continue;let b=[];for(let D of Object.keys(P))b.push(` '${D}': () => import('virtual:i18n-lazy-${x}-${D}')`);b.length>0&&R.push(` '${x}': {
331
- ${b.join(`,
325
+ `)},generateManifest:o=>({totalVars:Object.keys(o?.env||{}).length,mode:o?.mode||"development",variables:Object.keys(o?.env||{}),timestamp:Date.now()}),logStats:(o,e,t)=>{let n=Object.keys(o.env).length;t&&t.info(`${e} Env: ${n} VITE_* variables`)}},Ft=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 n={...Ms(this.mode,e,"VITE_")};return this.mode==="production"&&(delete n.VITE_USE_FIREBASE_EMULATOR,delete n.VITE_FIREBASE_EMULATOR_HOST,delete n.VITE_FIREBASE_AUTH_EMULATOR_HOST,delete n.VITE_FIREBASE_FIRESTORE_EMULATOR_HOST,delete n.VITE_FIREBASE_FUNCTIONS_EMULATOR_PORT),n.MODE=this.mode,n.DEV=this.mode==="development",n.PROD=this.mode==="production",n.SSR=!1,{env:n,mode:this.mode,source:`${e}/.env`,errors:[]}}catch(e){return{env:{},mode:this.mode,source:"error",errors:[e.message]}}}};function Vn(o={}){return we({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:V.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:Hn,manifestFileName:ve.manifests.env,configKey:"env",createDiscovery:(e,t)=>new Ft(e,{...t,mode:o.mode||t.mode||"development"})})({...o,disableHmr:!0})}function Ls(o,e,t,n={}){let{minLength:r=0,excludeEmpty:s=!0,customFilter:a}=n;return Array.from({length:t},(i,l)=>{let c=`${e}.${l}`;return o(c)}).filter((i,l)=>{let c=`${e}.${l}`;return!(i===c||s&&i.trim()===""||i.length<r||a&&!a(i,l))})}var Ze=(o,e,t)=>({tag:"meta",attributes:{[o]:e,content:t}});var js=20,Jn={defaultValue:""};function zs(o,e,t){if(o!==null)return o!==void 0?o:t(e,Jn)||void 0}function Bs(o,e){let t=s=>o(s,Jn),n=s=>t(`${e}:meta.${s}`)||void 0,r=Ls(t,`${e}:meta.keywords`,js);return{fullTitle:n("fullTitle"),image:n("image"),type:n("type"),keywords:r.length>0?r:void 0,author:n("author")}}function qn(o){let{meta:e,ns:t,defaultNs:n,t:r,siteName:s}=o,a=e.seo;if(!t&&!n)return{title:a?.fullTitle||s};let i=t?zs(a?.title,`${t}:title`,r):a?.title??void 0;return{title:a?.fullTitle||(t?Bs(r,t).fullTitle:void 0)||(i?`${i} | ${s}`:s),...i&&{pageTitle:i}}}var Kn={enabled:!0,themeColor:"#2563eb",backgroundColor:"#ffffff",includeManifestIcons:!0,includeMSIcons:!1};function Yn(o){let e=t=>o(t)?t:void 0;return{svg:e("/favicon.svg"),ico:e("/favicon.ico"),png16:e("/favicon-16x16.png"),png32:e("/favicon-32x32.png"),apple180:e("/apple-touch-icon.png"),android192:e("/icon-192x192.png"),android512:e("/icon-512x512.png")}}var ze=(o,e,t)=>({tag:"link",attributes:{rel:"icon",type:e,...t&&{sizes:t},href:o}});function Zn(o,e){let{enabled:t,appName:n,themeColor:r,includeManifestIcons:s,includeMSIcons:a}=e;if(t===!1)return[];let i=[];return o.svg&&i.push(ze(o.svg,"image/svg+xml")),o.ico&&i.push(ze(o.ico,"image/x-icon")),o.png16&&i.push(ze(o.png16,"image/png","16x16")),o.png32&&i.push(ze(o.png32,"image/png","32x32")),o.apple180&&(i.push({tag:"link",attributes:{rel:"apple-touch-icon",sizes:"180x180",href:o.apple180}}),n&&i.push(Ze("name","apple-mobile-web-app-title",n))),s&&(o.android192&&i.push(ze(o.android192,"image/png","192x192")),o.android512&&i.push(ze(o.android512,"image/png","512x512"))),a&&o.png32&&(i.push(Ze("name","msapplication-TileImage",o.png32)),r&&i.push(Ze("name","msapplication-TileColor",r))),r&&i.push(Ze("name","theme-color",r)),i.push(Ze("name","color-scheme","light dark")),i}var ut="dndev-fonts";function Mt(o){return o.map(e=>({tag:"link",attributes:{rel:"preload",as:"font",type:"font/woff2",href:e,crossorigin:"anonymous"}}))}Y();function Xn({appConfig:o}){let e=o.favicon;return{name:"dndev-favicon",transformIndexHtml(){if(e===!1)return[];let t=O.getInstance();return Zn(Yn(s=>t.pathExists(t.resolveAppPath(`public${s}`))),{...Kn,appName:o.app?.name,...e}).map(({tag:s,attributes:a})=>({tag:s,attrs:a,injectTo:"head"}))}}}q();q();var Be=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:(n,...r)=>{this.options.debug}},this.patterns={selectors:{...Tt.selectors,...this.options.customPatterns?.selectors},themes:{...Tt.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 n=t.split("-").filter(a=>a.length>0);if(n.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=n.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,n){let r=[],s,a=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(s=l.exec(i))!==null;){let[,c,u,p]=s;if(!c||!p)continue;let d=u.match(this.patterns.themes.themeIcon),f=u.match(this.patterns.themes.themeIsDark),g={name:c,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:d?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${p})`),r.push(g),n.themes.set(c,{name:c,displayName:p,isDark:g.isDark,file:a,variables:new Set,meta:g.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 s=r.slice(1);s.startsWith("_")||t.classes.add(s)})}extractVariables(e,t,n){(e.match(this.patterns.selectors.variable)||[]).forEach(s=>{s.startsWith("--")&&s.length>2?n==="framework"?t.variables.framework.add(s):t.variables.consumer.add(s):this._debug(`Skipping invalid CSS variable: ${s}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let s=r.replace("@keyframes","").trim();s&&t.keyframes.add(s)})}validateCSS(e){let t=[],n=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return n&&n.forEach(s=>{t.push(`Possible malformed CSS variable: ${s}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(s=>{if(!s.includes("--theme-label")&&s.includes("--")){let a=s.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,n="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},s=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,n),this.extractKeyframes(e,r);let a=this.validateCSS(e);return{themes:s,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 Qn="@donotdev/components/styles",Us=/@import\s+['"](\.[^'"]+)['"]\s*;/g,Oe=class extends fe{constructor(e,t,n={}){super(t,n),this.cssExtractor=e||new Be(t,{debug:n.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:n}=e;this.logger.debug(`Scanning ${t.length} framework + ${n.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",n),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),n.length>0?(this.logger.debug(`Consumer files found: ${n.length}`),this.logger.debug("Consumer files:",n)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t);let r=await this._processConsumerFiles(n),s=this._serializeThemes(),a={framework:this._readFrameworkTokenCss(),app:r};return this.logger.debug(`Discovered ${s.length} themes:`,s.map(i=>i.name)),{themes:s,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(),fontCss: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 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 n=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(n,r,this.discovered),this.cssExtractor.extractClasses(n,this.discovered),this.cssExtractor.extractVariables(n,this.discovered,"framework"),this.cssExtractor.extractKeyframes(n,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(n){this.logger.debug(`Error scanning framework file ${t}: ${n.message}`)}}async _processConsumerFiles(e){let t=[];for(let n of e)try{let r=await this.pathResolver.read(n,{format:"text"}),s=this.pathResolver.normalizePath(n);t.push({file:this.pathResolver.getRelativePath(s),css:r}),this.cssExtractor.extractThemes(r,s,this.discovered),this.cssExtractor.extractVariables(r,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(s)}`)}catch(r){this.logger.debug(`Error scanning consumer file ${n}: ${r.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(Qn,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw H("dndev-theme",`cannot resolve ${Qn} (framework font defaults), resolved from @donotdev/ui: check that @donotdev/ui and @donotdev/components are installed`,"missing-required-resource");let t=new Set,n=r=>{if(t.has(r))return"";t.add(r);let s=this.pathResolver.readSync(r,{format:"text"});if(typeof s!="string")throw H("dndev-theme",`cannot read ${r} (framework font defaults)`,"missing-required-resource");let a=this.pathResolver.getDirname(r);return s.replace(Us,(i,l)=>n(this.pathResolver.resolvePath(l,a)))};return n(e)}_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}))}};q();import{createHash as Sa}from"node:crypto";var no="src/**/*.{ts,tsx,js,jsx,mjs,cjs}",Lt=/\/\*[\s\S]*?\*\//g,Ws=/(^|\s)\/\/.*$/gm,Gs=/<!--[\s\S]*?-->/g,Hs=/(?:from\s*|import\s*\(\s*|require\s*\(\s*)['"]next\/font(?:\/[^'"]*)?['"]/g,Vs=/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)['"]@fontsource(?:-variable)?\/[^'"]*['"]/g,Js=/@import\s+(?:url\(\s*)?['"]?@fontsource(?:-variable)?\/[^'";)]*/g,eo=/@font-face\b/g,to="Name the family in src/themes.css (e.g. --font-sans: Manrope, 'Manrope Fallback', sans-serif;) and keep @fontsource-variable/<slug> or @fontsource/<slug> in package.json, or declare its woff2 files in appConfig.fonts.",qs={"next-font":{message:`imports next/font: its preload cannot work in a framework app (page files carry the \`.next.\` marker, Next's font manifest is keyed without it) and it is a second font pipeline. The framework ships the theme's fonts (preloaded, inline @font-face, size-matched fallback). ${to}`},fontsource:{message:`imports an @fontsource package: the framework ships the fonts the theme names (preloaded, inline @font-face, hashed /fonts/ files). Remove the import. ${to}`},"font-face":{message:"declares @font-face: the framework writes every @font-face of the app (one place, preloaded, hashed files). Declare the woff2 files in appConfig.fonts (src/config/app.ts: { category, faces: [{ file, weight, unicodeRange? }] }) and name the family in src/themes.css."}};function Ks(o,e){let t=o;for(let n of e)t=t.replace(n,(r,s)=>{let a=typeof s=="string"?s:"";return a+r.slice(a.length).replace(/[^\n]/g," ")});return t}var Ys=(o,e)=>o.slice(0,e).split(`
326
+ `).length;function Zs(o){let e=[];for(let{file:t,content:n}of o){if(/\.generated\.[a-z]+$/.test(t))continue;let r=t.endsWith(".css"),s=t.endsWith(".html"),a=Ks(n,s?[Gs,Lt]:r?[Lt]:[Lt,Ws]),i=r?[["fontsource",Js],["font-face",eo]]:s?[["font-face",eo]]:[["next-font",Hs],["fontsource",Vs]];for(let[l,c]of i)for(let u of a.matchAll(c))e.push({file:t,line:Ys(a,u.index),rule:l})}return e}function oo(o){let e=Zs(o);if(e.length===0)return;let t=e.map(({file:n,line:r,rule:s})=>` ${n}:${r} ${qs[s].message}`);throw H("dndev-fonts",`the app loads fonts itself; the framework font plan is the one way:
327
+ ${t.join(`
328
+ `)}`,"configuration-error")}import{brotliDecompressSync as Xs}from"node:zlib";var ro="aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ",Qs={"sans-serif":{locals:["Arial","Liberation Sans"],azAvgWidth:934.5116279069767,unitsPerEm:2048},serif:{locals:["Times New Roman","Liberation Serif"],azAvgWidth:854.3953488372093,unitsPerEm:2048}},ea={0:"cmap",1:"head",2:"hhea",3:"hmtx"},ta=63,so=48,na=2001684018;function ao(o,e){let t=0;for(let n=0;n<5;n++){let r=o[e+n];if(t=t*128+(r&127),(r&128)===0)return[t,e+n+1]}throw new Error("woff2: invalid UIntBase128")}function oa(o){if(o.length<so||o.readUInt32BE(0)!==na)throw new Error("woff2: bad signature");if(o.readUInt32BE(4)===1953784678)throw new Error("woff2: font collections are not supported");let e=o.readUInt16BE(12),t=o.readUInt32BE(20),n=so,r=[];for(let l=0;l<e;l++){let c=o[n++],u=c&63,p=c>>6,d=ea[u]??`#${u}`;u===ta&&(d=o.toString("latin1",n,n+4),n+=4);let f;[f,n]=ao(o,n);let g=u===10||u===11?p!==3:p!==0,v=f;g&&([v,n]=ao(o,n)),r.push({tag:d,length:v,transformed:g})}let s=Xs(o.subarray(n,n+t)),a=new Map,i=0;for(let{tag:l,length:c,transformed:u}of r)a.set(l,{data:s.subarray(i,i+c),transformed:u}),i+=c;return a}function ra(o){let e=o.readUInt16BE(2),t=[];for(let u=0;u<e;u++){let p=4+u*8,d=o.readUInt16BE(p),f=o.readUInt16BE(p+2),g=o.readUInt32BE(p+4);(d===0||d===3&&(f===1||f===10))&&t.push({offset:g,format:o.readUInt16BE(g)})}let n=t.find(u=>u.format===12)??t.find(u=>u.format===4);if(!n)throw new Error("font: no Unicode cmap (format 4 or 12)");let r=n.offset;if(n.format===12){let u=o.readUInt32BE(r+12);return p=>{for(let d=0;d<u;d++){let f=r+16+d*12,g=o.readUInt32BE(f),v=o.readUInt32BE(f+4);if(p>=g&&p<=v)return o.readUInt32BE(f+8)+(p-g)}return 0}}let s=o.readUInt16BE(r+6)/2,a=r+14,i=a+s*2+2,l=i+s*2,c=l+s*2;return u=>{for(let p=0;p<s;p++){if(u>o.readUInt16BE(a+p*2))continue;let d=o.readUInt16BE(i+p*2);if(u<d)return 0;let f=o.readInt16BE(l+p*2),g=c+p*2,v=o.readUInt16BE(g);if(v===0)return u+f&65535;let h=o.readUInt16BE(g+v+(u-d)*2);return h===0?0:h+f&65535}return 0}}function lo(o){let e=oa(o);for(let c of["head","hhea","hmtx","cmap"])if(!e.has(c))throw new Error(`font: missing ${c} table`);let t=e.get("head").data,n=e.get("hhea").data,r=e.get("hmtx"),s=n.readUInt16BE(34),a=c=>{let u=Math.min(c,s-1);return r.transformed?r.data.readUInt16BE(1+u*2):r.data.readUInt16BE(u*4)},i=ra(e.get("cmap").data),l=0;for(let c of ro){let u=i(c.codePointAt(0));if(u===0)throw new Error(`font: no glyph for '${c}'`);l+=a(u)}return{unitsPerEm:t.readUInt16BE(18),ascent:n.readInt16BE(4),descent:n.readInt16BE(6),lineGap:n.readInt16BE(8),azAvgWidth:l/ro.length}}var io=o=>`${Math.abs(o*100).toFixed(2)}%`;function pt(o){return`${o} Fallback`}function co({family:o,category:e,metrics:t}){let n=Qs[e];if(!n)throw new Error(`font fallback: unknown category '${e}'`);let{unitsPerEm:r,ascent:s,descent:a,lineGap:i,azAvgWidth:l}=t,c=l/r/(n.azAvgWidth/n.unitsPerEm),u=d=>io(d/(r*c)),p=pt(o);return[`/* ${p}: ${n.locals[0]} size-matched to ${o} */`,"@font-face {",` font-family: '${p}';`,` src: ${n.locals.map(d=>`local('${d}')`).join(", ")};`,` ascent-override: ${u(s)};`,` descent-override: ${u(a)};`,` line-gap-override: ${u(i)};`,` size-adjust: ${io(c)};`,"}"].join(`
329
+ `)}var sa=2001684018,dt=400;function gt(o){return o.trim().toLowerCase().replace(/\s+/g,"-")}function aa(o){let[e,t=e]=String(o).trim().split(/\s+/).map(Number);return[e,t]}var ft=([o,e],t)=>t>=o&&t<=e;function uo(o,e){if(e.some(s=>ft(s,o)))return o;let t=[...new Set(e.flat())],n=(s=1/0)=>t.filter(a=>a>o&&a<=s).sort((a,i)=>a-i)[0],r=()=>t.filter(s=>s<o).sort((s,a)=>a-s)[0];return o>=400&&o<=500?n(500)??r()??n():o<400?r()??n():n()??r()}function ge(o){return H("dndev-fonts",o,"configuration-error")}function ia(o){return!!(o&&o.length>=4&&o.readUInt32BE(0)===sa)}var la=o=>o==="serif"?"serif":"sans-serif";function ca({family:o,packageName:e,dir:t,pathResolver:n}){let r=n.readSync(n.resolvePath("metadata.json",t),{format:"json"}),s=n.readSync(n.resolvePath("unicode.json",t),{format:"json"});if(!r||!s)throw ge(`${e}: metadata.json or unicode.json missing in ${t} (not a fontsource package?).`);if(String(r.family).toLowerCase()!==o.toLowerCase())throw ge(`${e} is the family '${r.family}', the font stack names '${o}'. Write the family as the package names it.`);let a=e.startsWith("@fontsource-variable/"),i=r.variable?.wght;if(a&&!i)throw ge(`${e} has no wght axis: use @fontsource/${r.id} (static weights).`);let l=a?[Number(i.min),Number(i.max)]:null,c=["normal","italic"].filter(g=>r.styles.includes(g)),u=(g,v,h)=>n.resolvePath(`files/${r.id}-${g}-${a?"wght":v}-${h}.woff2`,t),p=g=>{if(!n.pathExists(g))throw ge(`${e}: font file missing: ${g}`);return g},d=r.subsets.includes("latin")?"latin":r.defSubset,f=r.weights.reduce((g,v)=>Math.abs(v-dt)<Math.abs(g-dt)?v:g);return{family:o,kind:a?"variable":"static",category:la(r.category),label:e,provides:g=>a?ft(l,g):r.weights.includes(g),matchWeight:g=>uo(g,a?[l]:r.weights.map(v=>[v,v])),faces({weights:g,subsets:v}){let h=v.filter($=>r.subsets.includes($)),y=a?[`${l[0]} ${l[1]}`]:g.map(String),C=[];for(let $ of h)for(let S of y)for(let x of c)C.push({file:p(u($,S,x)),weight:S,style:x,subset:$,unicodeRange:s[$]??null});return C},metricsFile:p(u(d,f,"normal"))}}function ua({family:o,config:e,pathResolver:t}){let n=`appConfig.fonts['${o}']`;if(e?.category!=="sans-serif"&&e?.category!=="serif")throw ge(`${n}.category must be 'sans-serif' or 'serif' (picks the size-matched fallback face's system font).`);if(!Array.isArray(e.faces)||e.faces.length===0)throw ge(`${n}.faces must list the family's woff2 files ({ file, weight, style?, unicodeRange?, subset? }).`);let r=e.faces.map((c,u)=>{let p=`${n}.faces[${u}]`;if(typeof c?.file!="string"||!c.file.endsWith(".woff2"))throw ge(`${p}.file must be a .woff2 path relative to the app root (e.g. 'src/assets/fonts/brand.woff2').`);let[d,f]=aa(c.weight);if(!Number.isFinite(d)||!Number.isFinite(f)||d>f)throw ge(`${p}.weight must be a weight (400) or a variable range ('300 600'). Got ${JSON.stringify(c.weight)}.`);let g=c.style??"normal";if(g!=="normal"&&g!=="italic")throw ge(`${p}.style must be 'normal' or 'italic'.`);let v=t.resolveAppPath(c.file),h=t.pathExists(v)?t.readSync(v,{format:"buffer"}):null;if(!h)throw ge(`${p}.file: ${c.file} does not exist.`);if(!ia(h))throw ge(`${p}.file: ${c.file} is not a woff2 font.`);return{file:v,weight:d===f?String(d):`${d} ${f}`,range:[d,f],style:g,subset:c.subset??null,unicodeRange:c.unicodeRange??null}}),s=r.filter(c=>c.style==="normal"),a=s.filter(c=>c.unicodeRange===null),i=({range:c})=>ft(c,dt)?0:Math.min(...c.map(u=>Math.abs(u-dt))),l=[...a.length>0?a:s].sort((c,u)=>i(c)-i(u))[0];if(!l)throw ge(`${n}.faces has no normal-style face: the size-matched fallback face is measured on one.`);return{family:o,kind:"local",category:e.category,label:n,provides:c=>s.some(u=>ft(u.range,c)),matchWeight:c=>uo(c,s.map(u=>u.range)),faces:()=>r.map(({range:c,...u})=>u),metricsFile:l.file}}function pa(o,e,t){if(!e)return null;let n=t.resolvePackage(`${o}/package.json`,e);return n?t.getDirname(n):null}function po(o,{appFonts:e={},appRoot:t,uiRoot:n,pathResolver:r}){let s=Object.keys(e).find(i=>i.toLowerCase()===o.toLowerCase());if(s)return ua({family:o,config:e[s],pathResolver:r});let a=gt(o);for(let i of[t,n])for(let l of[`@fontsource-variable/${a}`,`@fontsource/${a}`]){let c=pa(l,i,r);if(c)return ca({family:o,packageName:l,dir:c,pathResolver:r})}return null}var Bt=Object.freeze({body:"--font-family",headline:"--font-headline",mono:"--font-mono"}),da="--font-weight-",Ee=":root",fa="@donotdev/components/styles",ga=/\/\*[\s\S]*?\*\//g,ma=/([^{}]+)\{([^{}]*)\}/g,ha=/^(?::root|html|:where\(:root\))$/,va=/^(?::root|html)?\.([a-z][\w-]*)$/i,Ut=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/,fo={normal:400,bold:700};function Wt(o){let e=[],t=0,n="",r=0;for(let s=0;s<o.length;s++){let a=o[s];n?a===n&&(n=""):a==='"'||a==="'"?n=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(o.slice(r,s)),r=s+1)}return e.push(o.slice(r)),e.map(s=>s.trim()).filter(Boolean)}function ya(o){return o.replace(/^['"]|['"]$/g,"").trim()}function ba(o){if(ha.test(o))return Ee;let e=va.exec(o);return e?e[1]:null}function go(o,e=""){let t=new Map,n=o.replace(ga,"");for(let[,r,s]of n.matchAll(ma)){let a=r.split(";").pop(),i=Wt(a).map(ba).filter(l=>l!==null);if(i.length!==0)for(let l of s.split(";")){let c=l.indexOf(":");if(c===-1)continue;let u=l.slice(0,c).trim();if(!u.startsWith("--"))continue;let p=l.slice(c+1).replace(/!important\s*$/,"").replace(/\s+/g," ").trim();for(let d of i)t.has(d)||t.set(d,new Map),t.get(d).set(u,{value:p,source:e,scope:d})}}return t}function wa(o){let e=new Map;for(let t of o)for(let[n,r]of t){e.has(n)||e.set(n,new Map);for(let[s,a]of r)e.get(n).set(s,a)}return e}function mo({source:o,scope:e}){return`${o||"CSS"} (${e===Ee?":root":`.${e}`})`}function jt(o,e,t,n){let r=[];for(let s of Wt(e)){let a=Ut.exec(s);if(!a){r.push(ya(s));continue}let[,i,l]=a;if(t.has(i)&&!n.has(i))r.push(...jt(i,t.get(i).value,t,new Set([...n,i])));else if(l!==void 0)r.push(...jt(o,l,t,n));else throw H("dndev-fonts",`${o}: ${e} uses var(${i}), which no theme CSS defines (src/**/*.css and the framework tokens). Name the font family in the stack itself, e.g. ${o}: Manrope, 'Manrope Fallback', sans-serif; (a next/font or other runtime class variable is not a framework font).`,"configuration-error")}return r}function Ea(o,e){let t=new Set,n=o;for(;e.has(n)&&!t.has(n);){t.add(n);let r=e.get(n),s=Wt(r.value),a=s[0]&&Ut.exec(s[0]);if(!a)return{token:n,declaration:r,entries:s};n=a[1]}return null}function zt(o,e,t=new Set){let{value:n}=e.get(o),r=Ut.exec(n);if(r){let[,a,i]=r;if(e.has(a)&&!t.has(a))return zt(a,e,new Set([...t,o]));if(i!==void 0)return zt(o,new Map([[o,{value:i.trim()}]]),t)}if(n in fo)return fo[n];let s=Number(n);if(Number.isFinite(s)&&s>=1&&s<=1e3)return s;throw H("dndev-fonts",`${o}: ${n} is not a font weight (a number from 1 to 1000, normal or bold): the font plan ships the weights the --font-weight-* tokens name.`,"configuration-error")}function ho({frameworkCss:o,appCss:e}){if(typeof o!="string"||!Array.isArray(e))throw new Error("resolveThemeFonts: frameworkCss (string) and appCss ({ file, css }[]) are required (ThemeDiscovery fontCss)");let t=go(o,fa),n=wa(e.map(({file:s,css:a})=>go(a,s)));return[Ee,...new Set([...t.keys(),...n.keys()])].filter((s,a,i)=>i.indexOf(s)===a).map(s=>{let a=new Map([...t.get(Ee)??[],...n.get(Ee)??[],...s===Ee?[]:t.get(s)??[],...s===Ee?[]:n.get(s)??[]]),i={};for(let[c,u]of Object.entries(Bt))a.has(u)&&(i[c]={stack:jt(u,a.get(u).value,a,new Set([u])),origin:Ea(u,a)});let l=new Map;for(let c of a.keys())c.startsWith(da)&&l.set(c,{weight:zt(c,a),declaration:a.get(c)});return{scope:s,roles:i,weights:l}})}var yo="optional",Ht=$e.fonts,Vt=`/${Ht}`,xa=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),$a=new Set(vn.map(o=>o.toLowerCase())),Pa="--font-weight-normal",Ra="--font-weight-bold",Gt=o=>H("dndev-fonts",o,"configuration-error");function vo(o){let e=yn[o];return e&&e.length>0?[...e]:["latin"]}var bo=o=>`'${o.replace(/'/g,"\\'")}'`;function Ca(o,e){return["@font-face{",`font-family:${bo(o)};`,`font-style:${e.style};`,`font-weight:${e.weight};`,`font-display:${yo};`,`src:url(${e.url}) format('woff2');`,e.unicodeRange?`unicode-range:${e.unicodeRange};`:"","}"].join("")}function _a(o,e){let[t,n=t]=o.split(" ").map(Number);return e>=t&&e<=n}async function wo({fontCss:o,appFonts:e={},languages:t,publicPath:n="",indexHtml:r=null,pathResolver:s}){if(!o||typeof o.framework!="string"||!Array.isArray(o.app))throw new Error("[dndev-fonts] buildFontPlan: fontCss is required (ThemeDiscovery fontCss: theme discovery failed?)");if(!Array.isArray(t)||t.length===0)throw new Error("[dndev-fonts] buildFontPlan: languages is required (i18n discovery supportedLanguages)");let a=s.getAppRoot(),i=await s.findFiles(a,no);oo([...o.app.map(({file:m,css:A})=>({file:m,content:A})),...i.map(m=>({file:s.getRelativePath(m),content:s.readSync(m,{format:"text"})??""})),...r===null?[]:[{file:"index.html",content:r}]]);let l=ho({frameworkCss:o.framework,appCss:o.app}),c=s.resolveFrameworkPackage("@donotdev/ui"),u=new Map,p=m=>{let A=m.toLowerCase();return u.has(A)||u.set(A,po(m,{appFonts:e,appRoot:a,uiRoot:c,pathResolver:s})),u.get(A)},d=new Map,f=new Map,g=new Map,v=new Map,h=new Map;for(let{scope:m,roles:A,weights:B}of l)for(let[w,M]of Object.entries(A)){if(!M)continue;let L=Bt[w];M.stack.forEach((z,K)=>{let U=z.toLowerCase();if(xa.has(U)||$a.has(U))return;let Z=/^(.+) fallback$/i.exec(z)?.[1];if(Z&&p(Z))return;let R=p(z);if(!R){d.has(U)||d.set(U,{family:z,token:L,scope:m});return}v.has(U)||v.set(U,{source:R,weights:new Set,scopes:new Set});let I=v.get(U);I.scopes.add(m);for(let{weight:J}of B.values())I.weights.add(R.matchWeight(J)),!R.provides(J)&&!g.has(`${U}:${J}`)&&g.set(`${U}:${J}`,`${R.family}: weight ${J} not in source, browser-synthesized`);if(K!==0)return;h.set(U,R);let F=M.origin,W=F?F.entries[1]:M.stack[1],Q=pt(z);if(W&&W.replace(/^['"]|['"]$/g,"").trim().toLowerCase()===Q.toLowerCase())return;let X=F?.declaration??{source:"",scope:m},te=F?.token??L,xe=`${X.source}|${te}|${X.value??z}`;if(f.has(xe))return;let E=F?F.entries:[z],T=`${te}: ${[E[0],bo(Q),...E.slice(1)].join(", ")};`;f.set(xe,{location:mo(X),declared:te,family:z,expected:Q,line:T})})}let y=[];for(let{family:m,token:A,scope:B}of d.values())y.push(`${A} (${B===Ee?":root":`.${B}`}) names '${m}', which nothing provides: install @fontsource-variable/${gt(m)} or @fontsource/${gt(m)} in the app, declare its woff2 files in appConfig.fonts['${m}'], or use a system family (SYSTEM_FONT_FAMILIES) or a generic one (sans-serif, serif, monospace, system-ui\u2026).`);for(let{location:m,declared:A,family:B,expected:w,line:M}of f.values())y.push(`${m}: ${A} lacks '${w}' right after '${B}' (the size-matched fallback face: no layout shift, no flicker). Write:
330
+ ${M}`);if(y.length>0)throw Gt(`the theme fonts cannot ship:
331
+ - ${y.join(`
332
+ - `)}`);let C=[...new Set(["latin",...t.flatMap(vo)])],$=new Map,S=m=>{if(!$.has(m)){let A=s.readSync(m,{format:"buffer"}),B=Sa("sha256").update(A).digest("hex").slice(0,8),w=s.getBasename(m).replace(/\.woff2$/,"");$.set(m,`${n}${Vt}/${w}.${B}.woff2`)}return $.get(m)},x=[],N=[];for(let[m,{source:A,weights:B}]of v){let w=A.faces({weights:[...B].sort((M,L)=>M-L),subsets:C}).map(M=>({...M,family:A.family,url:S(M.file)}));N.push(...w),x.push({family:A.family,kind:A.kind,category:A.category,source:A.label,fallback:h.has(m)?pt(A.family):null})}let D=[...h.values()].map(m=>{try{return co({family:m.family,category:m.category,metrics:lo(s.readSync(m.metricsFile,{format:"buffer"}))})}catch(A){throw Gt(`'${m.family}' (${m.label}): cannot measure ${m.metricsFile} for its fallback face (${A.message}). Its core file must be a woff2 with the Latin letters a-z.`)}}),P=l.find(({scope:m})=>m===Ee),k=[["body",Pa],["headline",Ra]].flatMap(([m,A])=>{let B=P.roles[m]?.stack[0];if(!B||!v.has(B.toLowerCase()))return[];let w=P.weights.get(A)?.weight;if(w===void 0)throw Gt(`${A} is not defined: the framework tokens (@donotdev/components/styles) define it.`);let{source:M}=v.get(B.toLowerCase());return[{family:M.family,weight:M.matchWeight(w)}]}),_={};for(let m of t){let A=vo(m),B=[];for(let{family:w,weight:M}of k)for(let L of N){if(L.family!==w||L.style!=="normal"||!_a(L.weight,M))continue;(L.subset===null?L.unicodeRange===null:A.includes(L.subset))&&!B.includes(L.url)&&B.push(L.url)}_[m]=B}return{display:yo,families:x,files:[...$].map(([m,A])=>({source:m,url:A})),css:[...N.map(m=>Ca(m.family,m)),...D].join(`
333
+ `),preloads:_,notices:[...g.values()]}}function Eo(o,{pathResolver:e,publicPath:t=""}){let n=e.resolveAppPath(`public/${Ht}`);e.removeSync(n),e.ensureDirSync(n);let r=`${t}${Vt}/`;for(let{source:s,url:a}of o.files){if(!a.startsWith(r))throw new Error(`[dndev-fonts] writeFontPlan: ${a} is not under ${r}`);e.copySync(s,e.resolvePath(a.slice(r.length),n),{overwrite:!0})}return n}Y();var So=/[ \t]*<link rel="preload" as="font"[^>]*>\n?/g,Aa=o=>o.replace(/&/g,"&amp;").replace(/"/g,"&quot;");function xo(o,e){let t=Mt(e).map(({attributes:s})=>` <link ${Object.entries(s).map(([a,i])=>`${a}="${Aa(i)}"`).join(" ")}>
334
+ `).join(""),n=o.search(So);if(n===-1){if(e.length===0)return o;let s=o.indexOf(`<style id="${ut}"`);if(s===-1)throw new Error(`[dndev-fonts] Prerender: the SPA shell has no font tags (<style id="${ut}">): keep the font plugin (createVitePlugins) before the prerender.`);let a=o.lastIndexOf(`
335
+ `,s)+1;return o.slice(0,a)+t+o.slice(a)}let r=o.replace(So,"");return r.slice(0,n)+t+r.slice(n)}function $o(){let o=null;return{set(e){o=e},get(){if(!o)throw new Error("[dndev-fonts] The font plan is not built yet (the font plugin builds it in buildStart).");return o}}}function Po({appConfig:o,i18nStore:e,fontPlan:t,debug:n=!1}){if(!e||!t)throw new Error("[dndev] createViteFontPlugin: options.i18nStore and options.fontPlan are required (createVitePlugins passes the i18n plugin's createI18nStore and createFontPlanStore).");let r=G("fonts",n,!1),s="",a=null;async function i(){let l=O.getInstance(),{supportedLanguages:c,fallbackLanguage:u}=await e.ready(),{fontCss:p}=await new Oe(null,l,{debug:n}).discoverThemes(!0),d=l.resolveAppPath("index.html"),f=await wo({fontCss:p,appFonts:o?.fonts,languages:c,publicPath:s,indexHtml:l.pathExists(d)?l.readSync(d,{format:"text"}):null,pathResolver:l});Eo(f,{pathResolver:l,publicPath:s}),t.set(f),a=c.includes(u)?u:c[0],r.debug(`Font plan: ${f.families.map(({family:g})=>g).join(", ")||"system fonts only"} (${f.files.length} files)`);for(let g of f.notices)r.info(`\u{1F524} ${g}`)}return{name:"dndev-fonts",configResolved(l){s=l.base&&l.base!=="/"?l.base.replace(/\/$/,""):""},async buildStart(){await i()},configureServer(l){l.watcher.on("change",async c=>{if(!c.endsWith(".css"))return;let u=t.get();try{await i()}catch(d){l.config.logger.error(d.message),l.ws.send({type:"error",err:{message:d.message,stack:""}});return}let p=t.get();(p.css!==u.css||JSON.stringify(p.preloads)!==JSON.stringify(u.preloads))&&l.ws.send({type:"full-reload"})})},transformIndexHtml:{order:"pre",handler(){let l=t.get();return[...Mt(l.preloads[a]).map(({tag:c,attributes:u})=>({tag:c,attrs:u,injectTo:"head"})),...l.css?[{tag:"style",attrs:{id:ut},children:l.css,injectTo:"head"}]:[]]}}}}q();import{existsSync as No,readFileSync as ko,writeFileSync as Na}from"node:fs";import{join as Do}from"node:path";var ka="/(.*)",qt=Object.freeze(["default-src","script-src","style-src","img-src","font-src","connect-src","media-src","worker-src","manifest-src","frame-src","object-src","base-uri","form-action","frame-ancestors"]),Da=Object.freeze({"default-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"frame-src":["'none'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"]}),Ro=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),To=Object.freeze({"@donotdev/supabase":{"connect-src":["https://*.supabase.co","wss://*.supabase.co"]},"@donotdev/firebase":{"script-src":["https://accounts.google.com","https://apis.google.com"],"connect-src":["https://identitytoolkit.googleapis.com","https://securetoken.googleapis.com","https://www.googleapis.com","https://*.googleapis.com","https://*.firebaseio.com"],"frame-src":["https://accounts.google.com"]}}),Ta=Object.freeze([{key:"X-Content-Type-Options",value:"nosniff"},{key:"X-Frame-Options",value:"DENY"},{key:"X-XSS-Protection",value:"1; mode=block"},{key:"Referrer-Policy",value:"strict-origin-when-cross-origin"},{key:"Permissions-Policy",value:"geolocation=(), microphone=(), camera=()"}]),Oa=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),Ia=31536e3,Fa=86400,Oo=3600,Co=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(o=>`/assets/:path*.${o}`),"next-export":["/_next/static/:path*"],next:[]}),Ma=`/${$e.fonts}/:path*`,La=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),ja=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${Oo}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),_o=Object.freeze(["csp","cache"]);function mt(o,e=!1){return`public, max-age=${o}${e?", immutable":""}`}function Jt(o,e){return{source:o,headers:[{key:"Cache-Control",value:e}]}}var Ao=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),za=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function Ba(o,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${o}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!Ao.includes(e)&&!za.test(e))throw new Error(`[dndev] appConfig.headers.csp['${o}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${Ao.join(" ")} or a hash like 'sha256-<base64>').`)}function Ua(o){if(o===void 0)return{csp:{},cache:[]};if(!o||typeof o!="object"||Array.isArray(o))throw new Error("[dndev] appConfig.headers must be an object.");for(let n of Object.keys(o))if(!_o.includes(n))throw new Error(`[dndev] appConfig.headers.${n} is not a header option (allowed: ${_o.join(", ")}).`);let e=o.csp??{};for(let[n,r]of Object.entries(e)){if(!qt.includes(n))throw new Error(`[dndev] appConfig.headers.csp['${n}'] is not a CSP directive the framework merges (allowed: ${qt.join(", ")}).`);if(!Array.isArray(r))throw new Error(`[dndev] appConfig.headers.csp['${n}'] must be an array of sources.`);for(let s of r)Ba(n,s)}let t=o.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let n of t){if(typeof n?.source!="string"||!n.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(n?.source)}).`);if(!Number.isInteger(n.maxAge)||n.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${n.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(n.maxAge)}).`)}return{csp:e,cache:t}}function Wa({csp:o={},providers:e=[],target:t}){if(!(t in Ro))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...qt.map(r=>{let s=[...r==="script-src"?Ro[t]:Da[r]??[],...e.flatMap(l=>To[l]?.[r]??[]),...o[r]??[]],a=[...new Set(s)],i=a.length>1?a.filter(l=>l!=="'none'"):a;return i.length>0?`${r} ${i.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function Io({appConfig:o,target:e,providers:t=[],pwa:n=!1}){if(!(e in Co))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:r,cache:s}=Ua(o?.headers),a=[{key:"Content-Security-Policy",value:Wa({csp:r,providers:t,target:e})},...o?.seo===!1?[Oa]:[],...Ta].map(i=>({...i}));return[{source:ka,headers:a},...[...Co[e],Ma].map(i=>Jt(i,mt(Ia,!0))),...La.map(i=>Jt(`/:path*.${i}`,mt(Fa))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:mt(Oo)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...n?ja.map(i=>({source:i.source,headers:i.headers.map(l=>({...l}))})):[],...s.map(i=>Jt(i.source,mt(i.maxAge,i.immutable===!0)))]}function Fo(o){let e=Do(o,"package.json");if(!No(e))return[];let t=JSON.parse(ko(e,"utf8")),n={...t.dependencies,...t.devDependencies};return Object.keys(To).filter(r=>!!n[r])}function Ga(o){let e=Do(o,"vercel.json");if(!No(e))return null;try{return{path:e,config:JSON.parse(ko(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function Mo({appRoot:o,rules:e,ci:t,logger:n}){let r=Ga(o);if(!r)return"absent";if(JSON.stringify(r.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${r.path}: "headers" differ from the framework header policy (appConfig.headers, appConfig.seo). The host reads the committed file, so this deploy would serve stale headers. Run the app locally (dev or build) to regenerate vercel.json, then commit it.`);let s=`${JSON.stringify({...r.config,headers:e},null,2)}
336
+ `;return Na(r.path,s),n?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function Lo({appConfig:o,pwa:e,debug:t,verbose:n}){let r=G("host-headers",t,n);return{name:"dndev-host-headers",configResolved(s){Mo({appRoot:s.root,rules:Io({appConfig:o,target:"vite",providers:Fo(s.root),pwa:e===!0}),ci:!!(process.env.CI||process.env.VERCEL),logger:r})}}}q();q();Y();q();function Ha(o){if(!o)return[];let e=O.getInstance(),t=new Set;try{let n=e.resolvePackage("@donotdev/core",o);if(!n)return[];let r=e.getDirname(e.getDirname(n)),s;try{s=e.readdirSync(r)}catch{return[]}for(let a of s)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 Va(o){if(!o)return[];let e=O.getInstance();try{let t=e.resolvePath("package.json",o),n=e.readSync(t,{format:"json"});if(!n)return[];let r=new Set;if(n.peerDependenciesMeta)for(let[s,a]of Object.entries(n.peerDependenciesMeta))a?.optional&&r.add(s);if(n.optionalDependencies)for(let s of Object.keys(n.optionalDependencies))r.add(s);return Array.from(r)}catch{return[]}}function Ja(o){let e=Pe.optionalFeatures||[],t=Ha(o),n=Va(o);return[...new Set([...e,...t,...n])]}function qa(o){let e=O.getInstance();try{let t=e.resolvePath("package.json",o),n=e.readSync(t,{format:"json"});return n?new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{})]):new Set}catch{return new Set}}function Ka(o,e,t){let n=new Set,r=t.resolvePackage("@donotdev/core",o);if(!r)return n;let s=t.getDirname(t.getDirname(r));for(let a of e){if(!a.startsWith("@donotdev/"))continue;let i=t.resolvePath(`${a.slice(10)}/package.json`,s);if(!t.pathExists(i))continue;let l=t.readSync(i,{format:"json"});for(let c of Object.keys(l?.dependencies||{}))n.add(c)}return n}function Ya(o,e,t){if(t.resolvePackage(o,e||void 0))return!0;let n=o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0],r=e;for(let s=0;s<10;s++){let a=t.resolvePath(`node_modules/${n}`,r);if(t.pathExists(a))return!0;let i=t.getDirname(r);if(i===r)break;r=i}return!1}function ht(o){let e=Ja(o),t=[],n=[],r=O.getInstance(),s=qa(o),a=Ka(o,s,r);for(let i of e)i.startsWith("@donotdev/")?s.has(i)?n.push(i):t.push(i):(s.has(i)||a.has(i))&&Ya(i,o,r)?n.push(i):t.push(i);return{missing:t,installed:n}}var vt=class extends fe{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[n,r]of Object.entries(e)){for(let s of Object.keys(r))t.includes(s)||delete r[s];Object.keys(r).length===0&&delete e[n]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),n=this.pathResolver.getRepoRoot();if(!t||t===n)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${n})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${n}`);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 s=st("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(R=>{let I=R.endsWith(".json")?R:`${R}/*_*.json`;return this.pathResolver.resolveAppPath(I)});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),d=this.pathResolver.normalizePath(n),f=(R,I)=>{let F=this.pathResolver.normalizePath(R),W=this.pathResolver.normalizePath(I);return F.startsWith(W)?F.slice(W.length+1):F},g=a.map(R=>f(R,t)),h=[...i,...l].map(R=>f(R,t)),y=c.map(R=>f(R,n)),C=u.map(R=>f(R,n)),$={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},S=await this.pathResolver._globWithNormalization(g,$),x=await this.pathResolver._globWithNormalization(h,$),N={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:s.ignore?.filter(R=>R!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${n}, ignore: ${JSON.stringify(N.ignore)}`);let D=await this.pathResolver._globWithNormalization(y,N),P=await this.pathResolver._globWithNormalization(C,N);this.logger.debug(`Found ${S.length} eager, ${x.length} lazy, ${D.length} framework eager, ${P.length} framework lazy files`),D.length>0?this.logger.debug(`Framework eager files (first 3): ${D.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),P.length>0?this.logger.debug(`Framework lazy files (first 3): ${P.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${u.join(", ")}`);let k=[...new Set([...S,...x,...D,...P])],_=new Set([...S,...D]),m={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:A}=ht(t),B=new Set(A.filter(R=>R.startsWith("@donotdev/")).map(R=>R.replace("@donotdev/","")));B.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...B].join(", ")}] (packages not installed)`);let w=new Map,M=[...D,...P];for(let R of M){let I=this._processTranslationFile(R,D.includes(R),t);if(I){if(B.has(I.namespace))continue;let F=`${I.namespace}_${I.language}`;w.set(F,I),m.allNamespaces.add(I.namespace),m.supportedLanguages.add(I.language),D.includes(R)&&m.eagerNamespaces.add(I.namespace)}}let L=new Set;for(let R of k){if(M.includes(R))continue;let I=this._processTranslationFile(R,_.has(R),t);if(I){let{namespace:F,language:W,importPath:Q,content:X}=I,te=`${I.namespace}_${I.language}`;if(w.has(te)){let xe=w.get(te);I.content=this._mergeTranslations(xe.content,X)}m.allNamespaces.add(F),m.supportedLanguages.add(W),L.add(W),_.has(R)&&m.eagerNamespaces.add(F),m.mapping[F]||(m.mapping[F]={}),m.mapping[F][W]=Q,I.content&&(m.content[F]||(m.content[F]={}),m.content[F][W]=I.content),m.files.push({path:R,relativePath:this.pathResolver.getRelativePath(R),namespace:F,language:W,eager:_.has(R),size:I.content?JSON.stringify(I.content).length:0})}}for(let[R,I]of w){let F=R.lastIndexOf("_"),W=R.slice(0,F),Q=R.slice(F+1);L.size>0&&!L.has(Q)||(!m.mapping[W]||!m.mapping[W][Q])&&(m.mapping[W]||(m.mapping[W]={}),m.mapping[W][Q]=I.importPath,m.content[W]||(m.content[W]={}),m.content[W][Q]=I.content,m.files.push({path:I.absolutePath,relativePath:this.pathResolver.getRelativePath(I.absolutePath),namespace:W,language:Q,eager:m.eagerNamespaces.has(W),size:I.content?JSON.stringify(I.content).length:0}))}let z=L.size>0?[...L].sort():[this.options.fallbackLanguage],K=this._getLanguageAllowlist(),U=z;if(K){let R=z.filter(F=>K.includes(F));U=R.length>0?R:[this.options.fallbackLanguage],this._restrictByLanguage(m.mapping,U),this._restrictByLanguage(m.content,U),m.files=m.files.filter(F=>U.includes(F.language));let I=new Set(Object.keys(m.mapping));m.allNamespaces=new Set([...m.allNamespaces].filter(F=>I.has(F))),m.eagerNamespaces=new Set([...m.eagerNamespaces].filter(F=>I.has(F))),this.logger.debug(`I18n restricted by i18n.only [${K.join(", ")}]: languages [${U.join(", ")}], namespaces ${I.size}`)}let Z=[...new Set(U.map(It))];return{mapping:m.mapping,content:m.content,eagerNamespaces:[...m.eagerNamespaces].sort(),allNamespaces:[...m.allNamespaces].sort(),supportedLanguages:U,fallbackLanguage:this.options.fallbackLanguage,flagCodes:Z,files:m.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[It(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 n=await this._processFiles([]);this.cache={...n,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){throw this.logger.error(`I18n discovery failed: ${n.message}`),n}}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,n){let r=e.split("/").pop()||e.split("\\").pop()||"",s,a,i=r.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,s,a]=i,!s||!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:s,language:a,importPath:c,absolutePath:e,content:u}}_mergeTranslations(e,t){let n={...e};for(let[r,s]of Object.entries(t))typeof s=="object"&&s!==null&&!Array.isArray(s)?n[r]=this._mergeTranslations(n[r]||{},s):n[r]=s;return n}};var jo={isEmpty:o=>!o.mapping||Object.keys(o.mapping).length===0,generateModule:(o,e,t="i18n",n=!1)=>{let{mapping:r,eagerNamespaces:s,supportedLanguages:a,fallbackLanguage:i,stats:l,content:c={},files:u=[]}=o,p=n?Object.keys(c):s,d={};for(let y of p)c[y]&&(d[y]=c[y]);let f=[...new Set([...s,...Object.keys(c)])],g={mapping:r,languages:a,eager:n?f:s,fallback:i,content:d,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},v=[];if(!n)for(let[y,C]of Object.entries(r)){if(s.includes(y))continue;let $=[];for(let S of Object.keys(C))$.push(` '${S}': () => import('virtual:i18n-lazy-${y}-${S}')`);$.length>0&&v.push(` '${y}': {
337
+ ${$.join(`,
332
338
  `)}
333
- }`)}let v=R.length>0?`{
334
- ${R.join(`,
339
+ }`)}let h=v.length>0?`{
340
+ ${v.join(`,
335
341
  `)}
336
- }`:"{}";return`// ${z.i18n} - Generated by @donotdev/config
342
+ }`:"{}";return`// ${V.i18n} - Generated by @donotdev/config
337
343
  // Generated at: ${new Date().toISOString()}
338
344
 
339
345
  // ===== STATIC EXPORTS =====
340
- export const I18N_CONFIG = ${JSON.stringify(m,null,2)};
346
+ export const I18N_CONFIG = ${JSON.stringify(g,null,2)};
341
347
  export const LANGUAGES = ${JSON.stringify(a,null,2)};
342
348
  export const FALLBACK_LANGUAGE = '${i}';
343
- export const EAGER_NAMESPACES = ${JSON.stringify(n,null,2)};
349
+ export const EAGER_NAMESPACES = ${JSON.stringify(s,null,2)};
344
350
 
345
351
  const i18nPluginConfig = I18N_CONFIG;
346
352
 
347
353
  // ===== LAZY LOADERS =====
348
354
  // Static import() calls \u2014 Vite bundles each JSON as a separate async chunk
349
- const _lazyLoaders = ${v};
355
+ const _lazyLoaders = ${h};
350
356
 
351
357
  // ============================================================================
352
358
  // INITIALIZE DnDev CONFIG FOUNDATION
@@ -364,7 +370,7 @@ if (typeof globalThis !== 'undefined') {
364
370
  }
365
371
 
366
372
  // Add i18n plugin configuration + lazy loaders (functions, not serializable)
367
- globalThis._DNDEV_CONFIG_.${K[t]} = {
373
+ globalThis._DNDEV_CONFIG_.${oe[t]} = {
368
374
  ...i18nPluginConfig,
369
375
  loaders: _lazyLoaders,
370
376
  };
@@ -458,11 +464,11 @@ export default {
458
464
  getInlineContent,
459
465
  };
460
466
 
461
- `},generateEmpty:(o,e,t,s="i18n")=>{let r=t.fallbackLanguage||"en",n={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`// ${z.i18n} - Empty i18n configuration
467
+ `},generateEmpty:(o,e,t,n="i18n")=>{let r=t.fallbackLanguage||"en",s={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`// ${V.i18n} - Empty i18n configuration
462
468
  // No translation files found - using fallback configuration
463
469
  // Generated at: ${new Date().toISOString()}
464
470
 
465
- const i18nPluginConfig = ${JSON.stringify(n,null,2)};
471
+ const i18nPluginConfig = ${JSON.stringify(s,null,2)};
466
472
 
467
473
  // Initialize base config if needed (universal CSR/SSR)
468
474
  if (typeof globalThis !== 'undefined') {
@@ -476,7 +482,7 @@ if (typeof globalThis !== 'undefined') {
476
482
  };
477
483
  }
478
484
 
479
- globalThis._DNDEV_CONFIG_.${K[s]} = i18nPluginConfig;
485
+ globalThis._DNDEV_CONFIG_.${oe[n]} = i18nPluginConfig;
480
486
  }
481
487
 
482
488
  // Placeholder functions
@@ -525,7 +531,7 @@ export default {
525
531
  getFallbackLanguage,
526
532
  getInlineContent,
527
533
  };
528
- `},generateInspection:(o,e,t)=>{let{mapping:s,supportedLanguages:r,eagerNamespaces:n,files:a}=o;return!s||Object.keys(s).length===0?`/**
534
+ `},generateInspection:(o,e,t)=>{let{mapping:n,supportedLanguages:r,eagerNamespaces:s,files:a}=o;return!n||Object.keys(n).length===0?`/**
529
535
  * Generated i18n Discovery Results
530
536
  * Generated at: ${new Date().toISOString()}
531
537
  * Status: No translations found
@@ -556,11 +562,11 @@ export default {
556
562
  * Access via: globalThis._DNDEV_CONFIG_.i18n
557
563
  */
558
564
 
559
- export const discoveredTranslations = ${JSON.stringify(s,null,2)};
565
+ export const discoveredTranslations = ${JSON.stringify(n,null,2)};
560
566
 
561
567
  export const supportedLanguages = ${JSON.stringify(r,null,2)};
562
568
 
563
- export const eagerNamespaces = ${JSON.stringify(n,null,2)};
569
+ export const eagerNamespaces = ${JSON.stringify(s,null,2)};
564
570
 
565
571
  export const translationFiles = ${JSON.stringify(a.map(i=>({namespace:i.namespace,language:i.language,path:i.relativePath,eager:i.eager,size:i.size})),null,2)};
566
572
 
@@ -578,9 +584,37 @@ export default {
578
584
  files: translationFiles,
579
585
  manifest: i18nManifest,
580
586
  };
581
- `},generateManifest:o=>({namespaces:o.stats?.totalNamespaces||0,languages:o.stats?.totalLanguages||0,fallbackLanguage:o.fallbackLanguage,eagerNamespaces:o.stats?.eagerNamespaces||0,platform:"vite",timestamp:Date.now()}),logConfig:o=>{},logStats:(o,e,t)=>{let s=o.supportedLanguages||[],r=Object.keys(o.mapping||{}).filter(n=>n!=="default").length||0;t&&t.info(`${e} I18n: ${s.length} languages, ${r} namespaces`)}},ho=[o=>o.endsWith(".json")&&o.includes("locale"),o=>/[a-z]+_[a-z]{2}\.json$/i.test(o),o=>o.includes("/locales/")&&o.endsWith(".json")];function ht(o={}){return new Ee(E.getInstance(),Ps(o))}function Ps(o={}){return{...Ne.discovery,fallbackLanguage:o.fallbackLanguage||"en",...o}}function Es(o={}){let e=!1,t=new Map,s=E.getInstance(),r=ht(o);function n(c){t.clear();let{content:p,eagerNamespaces:g}=c;for(let[f,m]of Object.entries(p||{}))if(!g.includes(f))for(let[R,v]of Object.entries(m))t.set(`virtual:i18n-lazy-${f}-${R}`,v)}let a={...Rs,generateModule:(c,p,g)=>(e||n(c),Rs.generateModule(c,p,g,e))};return[he({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:z.i18n,DiscoveryClass:Ee,discoveryMethod:"discoverTranslations",filePatterns:ho,templates:a,manifestFileName:de.manifests.i18n,configKey:"i18n",discoveryOptions:Ps(o)})({...o,hmrSmartDetection:!1}),{name:"dndev-i18n-lazy-loader",enforce:"pre",configResolved(c){e=c.command==="serve"},async buildStart(){if(e)return;let c=()=>{let f=s.getAppRoot(),m=s.getRepoRoot();return f&&f!==m},p=0;for(;!c()&&p<100;)await new Promise(f=>setTimeout(f,10)),p++;if(!c())return;let g=await r.discoverTranslations();n(g)},resolveId(c){if(!e&&c.startsWith("virtual:i18n-lazy-"))return"\0"+c},load(c){if(!e&&c.startsWith("\0virtual:i18n-lazy-")){let p=c.slice(1),g=t.get(p);return`export default ${JSON.stringify(g||{})};`}}},{name:"dndev-i18n-flag-filter",enforce:"pre",async buildStart(){if(e)return;let c=()=>{let m=s.getAppRoot(),R=s.getRepoRoot();return m&&m!==R},p=0;for(;!c()&&p<100;)await new Promise(m=>setTimeout(m,10)),p++;if(!c())return;let f=(await r.discoverTranslations()).flagCodes||[];this._allowedFlags=new Set(f.map(m=>m.toUpperCase()))},resolveId(c,p){if(e||!p||!c.includes("flag"))return;let g=c.match(/flag([A-Z][A-Z0-9_-]*)\.(tsx|js)$/i);if(!g)return;let f=g[1].toUpperCase();if(f!=="BASE"&&!this._allowedFlags?.has(f))return"\0empty-flag"},load(c){if(c==="\0empty-flag")return"export default () => null;"}}]}G();function $s(o,e){return e.some(t=>o===t||o.startsWith(t+"/"))}function _s(o={}){let e=[],t="",s="";return{name:"dndev-optional-dep-resolver",enforce:"pre",config(r){let n={name:"dndev-optional-dep-esbuild",setup(i){i.onResolve({filter:/^[@a-z]/,namespace:"file"},l=>$s(l.path,e)?{path:s,external:!1}:null)}};return{optimizeDeps:{esbuildOptions:{plugins:[...r.optimizeDeps?.esbuildOptions?.plugins||[],n]}}}},configResolved(r){let n=E.getInstance(),a=n.getAppRoot();if(e=qe(a).missing,t=n.getEmptyModulePath(),s=n.getEmptyCjsModulePath(),e.length>0){let l=r.optimizeDeps?.exclude||[];r.optimizeDeps.exclude=[...l,...e]}o.debug&&e.length>0},resolveId(r){return $s(r,e)?{id:t,syntheticNamedExports:!0}:null}}}function vt(o){return!o||typeof o!="string"?null:o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0]}function vo(o){return!o||typeof o!="string"?!1:!o.startsWith(".")&&!o.startsWith("/")&&!o.startsWith("\\")&&!o.startsWith("\0")}function yo(o,e){if(!o||!e||!e.getRepoRoot())return!1;let s=o;o.startsWith("@fs/")&&(s=o.slice(4));let r=e.resolveRepoPath("packages"),n=e.normalizePath(s);return r&&n.startsWith(r)}function bo(o,e){if(!o||!e)return null;let t=vt(o);if(!t)return null;let s=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(s)?e.resolveAppPath(`node_modules/${o}`):null}function ks(o,e,t){return!vo(o)||!yo(e,t)?null:bo(o,t)}G();function Ds(o={}){let{debug:e=!1,verbose:t=!0}=o,s=T("peer-dependency-resolver",e,t);return{name:"dndev-peer-dependency-resolver",enforce:"pre",configResolved(r){let n=E.getInstance(),a=n.getAppRoot();if(!a){s.warn("App root not set, peer dependency resolution may fail");return}this.pathResolver=n,this.appRoot=a},resolveId(r,n){if(!n||!this.appRoot||!this.pathResolver)return null;if(ks(r,n,this.pathResolver)){let i=vt(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}}}G();B();G();function wo(o){return o?String(o).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function ce(o){return o?String(o).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function xo(o,e,t){let s=E.getInstance(),r=new Map,n=`_${e}.json`,a=[s.resolvePath("src/pages/locales",o),s.resolvePath("src/locales",o)];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(n))continue;let c=u.slice(0,-n.length);if(!r.has(c))try{let p=s.resolvePath(u,i),g=s.readSync(p,{format:"json"});g&&r.set(c,g)}catch(p){t.debug(` Failed to parse locale ${u}: ${p.message}`)}}}return r}function Ke(o,e,t){let s=o.get(e);if(!s)return;let r=t.split("."),n=s;for(let a of r){if(n==null||typeof n!="object")return;n=n[a]}return n}var Ze=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=E.getInstance(),r=s.resolvePath("index.html",this.outDir),n=s.readSync(r);if(!n)return this.logger.warn("dist/index.html not found. Skipping prerender."),[];let a="en",i=xo(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 g of e.routes)g.path&&u.set(g.path,g);let c=process.env.VITE_APP_URL||"",p=[];for(let g of t)try{let f=u.get(g)||{},m=this.resolveRouteSeo(f,g,i,l),R=this.injectMetaTags(n,g,m,c,l);await this.writePrerenderedFile(g,R),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 n=e.meta||{},a=n.seo||{},i=n.namespace||t.split("/").filter(Boolean)[0]||"home",l=Ke(s,i,"meta")||{},u=Ke(s,i,"title"),c=Ke(s,i,"description"),p=Ke(s,i,"subtitle"),g;if(l.fullTitle)g=l.fullTitle;else if(a.fullTitle)g=a.fullTitle;else{let P=a.title!==void 0?a.title:u;g=P?`${P} | ${r}`:r}let f=a.description!==void 0?a.description:c||p||null,m=a.image||l.image||De,R=a.type||l.type||"website",v=a.keywords||l.keywords||null,x=a.noindex||!1;return{title:g,description:f,image:m,type:R,keywords:v,noindex:x}}resolveSiteName(){let e=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,n){let a=e,{title:i,description:l,image:u,type:c,keywords:p,noindex:g}=s;i&&(a=a.replace(/<title>[^<]*<\/title>/,`<title>${wo(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="${ce(l)}" />`),m&&f.push(`<link rel="canonical" href="${ce(m)}" />`),i&&f.push(`<meta property="og:title" content="${ce(i)}" />`),l&&f.push(`<meta property="og:description" content="${ce(l)}" />`),m&&f.push(`<meta property="og:url" content="${ce(m)}" />`),u){let R=u.startsWith("http")?u:`${(r??"").replace(/\/$/,"")}${u}`;f.push(`<meta property="og:image" content="${ce(R)}" />`),f.push('<meta property="og:image:width" content="1200" />'),f.push('<meta property="og:image:height" content="630" />')}if(c&&f.push(`<meta property="og:type" content="${ce(c)}" />`),n&&f.push(`<meta property="og:site_name" content="${ce(n)}" />`),(i||l||u)&&(f.push('<meta name="twitter:card" content="summary_large_image" />'),i&&f.push(`<meta name="twitter:title" content="${ce(i)}" />`),l&&f.push(`<meta name="twitter:description" content="${ce(l)}" />`),u&&f.push(`<meta name="twitter:image" content="${ce(u)}" />`)),p){let R=Array.isArray(p)?p.join(", "):p;f.push(`<meta name="keywords" content="${ce(R)}" />`)}if(g&&f.push('<meta name="robots" content="noindex, nofollow" />'),f.length>0){let R=f.map(v=>` ${v}`).join(`
582
- `);a=a.replace("</head>",`${R}
583
- </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(n=>!n.includes("*"));let r=new Set;for(let n of this.routes)if(n.includes("*")){let a=n.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 "${n}" matched ${i.length} route(s)`)}}else{let a=t.find(i=>(i.path||i)===n);a&&this.isAuthProtected(a)?this.logger.warn(` Skipping auth-protected route: ${n}`):a?r.add(n):(r.add(n),this.debug&&this.logger.debug(` Route "${n}" not in manifest, including anyway`))}return[...r]}isAuthProtected(e){return typeof e=="string"?!1:e.auth?.required===!0}async writePrerenderedFile(e,t){let s=E.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 n=s.getDirname(r);if(s.ensureDirSync(n),!s.writeSync(r,t,{overwrite:!0}))throw new Error(`writeSync returned false for ${r}`)}};function As(o={}){let{routes:e="auto",debug:t,verbose:s,...r}=o;if(Array.isArray(e)&&e.length===0)return{name:"prerender-disabled"};let n=T("Prerender",t,s),a=E.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 g=Te({appRoot:u,logger:n}),f=Yt(g.routes),R=He(g.routes,{appRoot:u}).map(v=>v.path);if(p=[...new Set([...f,...R])],p.length===0){n.warn("No public static routes found for prerendering.");return}n.debug(`Auto-discovered ${p.length} route(s) to prerender`)}try{let f=await new Ze({...r,routes:p,debug:t,outDir:c,base:i.base,appRoot:u,logger:n}).run(),m=f.filter(S=>S.ok).length,R=f.filter(S=>!S.ok),v=f.length,x=f.filter(S=>S.ok&&S.route.startsWith("/blog/")).length,P=m-x,b=[];P>0&&b.push(`${P} static`),x>0&&b.push(`${x} blog`);let D=b.length>0?` (${b.join(", ")})`:"";if(m>0&&n.info(`Prerendered: ${m}/${v} pages${D}`),R.length>0)for(let S of R)n.warn(` Failed: ${S.route} - ${S.error}`)}catch(g){n.warn(`Prerendering failed: ${g.message}`),n.warn("SPA will serve all routes via index.html fallback (no impact on functionality)."),t&&g.stack&&n.debug(g.stack)}}}}import{VitePWA as So}from"vite-plugin-pwa";var Xe=class extends le{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 n=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),n=[...this.options.assetData.pwaIcons]);let a=await this._analyzePWAFiles(r),i=a.filter(g=>g.type==="manifest"||g.type==="service-worker");n.push(...i);let l=a.filter(g=>g.type==="icon"),u=new Set(n.filter(g=>g.type==="icon").map(g=>g.path)),c=l.filter(g=>!u.has(g.path));n.push(...c);let p=this._generatePWAManifest(n);return{assets:n,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,n=await this._analyzePWAAsset(r);n&&t.push(n)}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,n=t.precacheManifest||[],a=JSON.stringify(n,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
587
+ `},generateManifest:o=>({namespaces:o.stats?.totalNamespaces||0,languages:o.stats?.totalLanguages||0,fallbackLanguage:o.fallbackLanguage,eagerNamespaces:o.stats?.eagerNamespaces||0,platform:"vite",timestamp:Date.now()}),logConfig:o=>{},logStats:(o,e,t)=>{let n=o.supportedLanguages||[],r=Object.keys(o.mapping||{}).filter(s=>s!=="default").length||0;t&&t.info(`${e} I18n: ${n.length} languages, ${r} namespaces`)}},Za=[o=>o.endsWith(".json")&&o.includes("locale"),o=>/[a-z]+_[a-z]{2}\.json$/i.test(o),o=>o.includes("/locales/")&&o.endsWith(".json")];function zo(){let o=null,e,t=new Promise(n=>{e=n});return{set(n){o=n,e(n)},ready:()=>t,get(){if(!o)throw new Error("[dndev] i18n discovery unavailable: the i18n plugin did not run (see the error above).");return o}}}function Xa(o={}){return{...je.discovery,fallbackLanguage:o.fallbackLanguage||"en",...o}}function Bo({i18nStore:o,...e}={}){if(!o)throw new Error("[dndev] createViteI18nPlugin: options.i18nStore is required (createVitePlugins passes it, createI18nStore).");let t=!1,n=new Map;function r(l){n.clear();let{content:c,eagerNamespaces:u}=l;for(let[p,d]of Object.entries(c||{}))if(!u.includes(p))for(let[f,g]of Object.entries(d))n.set(`virtual:i18n-lazy-${p}-${f}`,g)}let s={...jo,generateModule:(l,c,u)=>(t||r(l),jo.generateModule(l,c,u,t))};return[we({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:V.i18n,DiscoveryClass:vt,discoveryMethod:"discoverTranslations",filePatterns:Za,templates:s,manifestFileName:ve.manifests.i18n,configKey:"i18n",discoveryOptions:Xa(e)})({...e,discoveryStore:o,hmrSmartDetection:!1}),{name:"dndev-i18n-lazy-loader",enforce:"pre",configResolved(l){t=l.command==="serve"},async buildStart(){if(t)return;let l=await o.ready();r(l)},resolveId(l){if(!t&&l.startsWith("virtual:i18n-lazy-"))return"\0"+l},load(l){if(!t&&l.startsWith("\0virtual:i18n-lazy-")){let c=l.slice(1),u=n.get(c);return`export default ${JSON.stringify(u||{})};`}}}]}Y();function Uo(o,e){return e.some(t=>o===t||o.startsWith(t+"/"))}function Wo(o={}){let e=[],t="",n="";return{name:"dndev-optional-dep-resolver",enforce:"pre",config(r){let s={name:"dndev-optional-dep-esbuild",setup(i){i.onResolve({filter:/^[@a-z]/,namespace:"file"},l=>Uo(l.path,e)?{path:n,external:!1}:null)}};return{optimizeDeps:{esbuildOptions:{plugins:[...r.optimizeDeps?.esbuildOptions?.plugins||[],s]}}}},configResolved(r){let s=O.getInstance(),a=s.getAppRoot();if(e=ht(a).missing,t=s.getEmptyModulePath(),n=s.getEmptyCjsModulePath(),e.length>0){let l=r.optimizeDeps?.exclude||[];r.optimizeDeps.exclude=[...l,...e]}o.debug&&e.length>0},resolveId(r){return Uo(r,e)?{id:t,syntheticNamedExports:!0}:null}}}function Kt(o){return!o||typeof o!="string"?null:o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0]}function Qa(o){return!o||typeof o!="string"?!1:!o.startsWith(".")&&!o.startsWith("/")&&!o.startsWith("\\")&&!o.startsWith("\0")}function ei(o,e){if(!o||!e||!e.getRepoRoot())return!1;let n=o;o.startsWith("@fs/")&&(n=o.slice(4));let r=e.resolveRepoPath("packages"),s=e.normalizePath(n);return r&&s.startsWith(r)}function ti(o,e){if(!o||!e)return null;let t=Kt(o);if(!t)return null;let n=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(n)?e.resolveAppPath(`node_modules/${o}`):null}function Go(o,e,t){return!Qa(o)||!ei(e,t)?null:ti(o,t)}Y();function Ho(o={}){let{debug:e=!1,verbose:t=!0}=o,n=G("peer-dependency-resolver",e,t);return{name:"dndev-peer-dependency-resolver",enforce:"pre",configResolved(r){let s=O.getInstance(),a=s.getAppRoot();if(!a){n.warn("App root not set, peer dependency resolution may fail");return}this.pathResolver=s,this.appRoot=a},resolveId(r,s){if(!s||!this.appRoot||!this.pathResolver)return null;if(Go(r,s,this.pathResolver)){let i=Kt(r),l=this.pathResolver.resolveAppPath(`node_modules/${r}`),c=this.pathResolver.resolveAppPath(`node_modules/${i}`);return this.pathResolver.pathExists(c)?r===i?((e||t)&&n.debug(`[PeerDeps] Resolving bare import "${r}" from app's node_modules: ${c}`),c):((e||t)&&n.debug(`[PeerDeps] Resolving subpath "${r}" from app's node_modules: ${l}`),l):(e&&n.debug(`[PeerDeps] Package directory not found: ${c}, skipping resolution`),null)}return null}}}Y();Y();function ni(o){return o?String(o).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function oi(o){return o?String(o).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function ri(o){return o.replace(/<meta\s+name="description"[^>]*\/?>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="twitter:[^"]*"[^>]*\/?>\s*/gi,"").replace(/<link\s+rel="canonical"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="robots"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="keywords"[^>]*\/?>\s*/gi,"")}var si="data-rh";function Vo({tag:o,attributes:e,text:t}){if(o==="title")return`<title>${ni(t)}</title>`;let n=Object.entries(e).map(([s,a])=>`${s}="${oi(a)}"`).join(" "),r=`<${o} ${n} ${si}="true"`;return o==="script"?`${r}>${t??""}</script>`:`${r} />`}function Jo(o,{tags:e,headScript:t,headElementId:n}){if(!/<title>[^<]*<\/title>/.test(o)||!o.includes("</head>"))throw new Error("[dndev] Prerender: dist/index.html has no <title> or </head>. Keep both in the app's index.html.");let r=e.filter(a=>a.tag==="title").map(Vo),s=e.filter(a=>a.tag!=="title").map(a=>` ${Vo(a)}`);return s.push(` <script type="application/json" id="${n}">${t}</script>`),ri(o).replace(/<title>[^<]*<\/title>/,()=>r.join("")).replace("</head>",()=>`${s.join(`
588
+ `)}
589
+ </head>`)}function qo(o){if(o==="/")return"/index.html";let e=[];for(let t of o.split("/").slice(1)){let n;try{n=decodeURIComponent(t)}catch{return null}if(!n||n==="."||n===".."||/[/\\\0]/.test(n))return null;e.push(n)}return`/${e.join("/")}.html`}function ai(o){return!o.includes(":")&&!o.includes("*")}var yt=class{constructor(e){this.routes=e.routes||[],this.outDir=e.outDir,this.debug=e.debug||!1,this.logger=e.logger}expandRoutes(e){let{routes:t,errors:n}=e;if(t.length===0)return n.length>0&&this.logger.warn("Route manifest unavailable. Using explicit routes only."),this.routes.filter(s=>!s.includes("*"));let r=new Set;for(let s of this.routes)if(s.includes("*")){let a=s.replace(/\/?\*.*$/,"");for(let i of t){let l=i.path||i;l.startsWith(a)&&ai(l)&&!this.isAuthProtected(i)&&r.add(l)}if(this.debug){let i=[...r].filter(l=>l.startsWith(a));this.logger.debug(` Pattern "${s}" matched ${i.length} route(s)`)}}else{let a=t.find(i=>(i.path||i)===s);a&&this.isAuthProtected(a)?this.logger.warn(` Skipping auth-protected route: ${s}`):(r.add(s),!a&&this.debug&&this.logger.debug(` Route "${s}" not in manifest, including anyway`))}return[...r]}isAuthProtected(e){return typeof e=="string"?!1:e.auth?.required===!0}async writeOutputFile(e,t){let n=O.getInstance(),r=n.resolvePath(e.replace(/^\//,""),this.outDir);if(n.ensureDirSync(n.getDirname(r)),!n.writeSync(r,t,{overwrite:!0}))throw new Error(`writeSync returned false for ${r}`)}};q();function ke(o){return o.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function ii(o,e){let t=e&&Object.hasOwn(e,o.collection)?e[o.collection]:void 0;if(!t)throw new Error(`[dndev] Route "${o.path}" reads "${o.collection}" records but no read schema was given for that collection (entityReadSchemas of the app's entities).`);return t}async function li(o,e,t,n){let r=ke(o.path),s=r[0];if(r.length!==1||!o.collection||!s)throw new Error(`[dndev] Cannot list the public URLs of route "${o.path}". Only single-param routes of an entity collection are expanded. Mark the page \`seo: { noindex: true }\` to keep it out of the sitemap and llms.txt.`);if(!e)throw new Error(`[dndev] Route "${o.path}" lists "${o.collection}" records but no server CRUD reader was given.`);let a=ii(o,n),i;try{i=await e.query(o.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3},a)}catch(c){let u=c?.details?.originalMessage??c?.message??String(c);throw new Error(`[dndev] Route "${o.path}" could not read its public "${o.collection}" records (signed-out visitor: RLS / Security Rules must allow it): ${u}`,{cause:c})}let l=[];for(let c of i.items){let u=c[s];typeof u!="string"&&typeof u!="number"||l.push({param:s,value:String(u),record:c})}return l}async function Ue(o,e,t,n){let r=[];for(let s of o){if(ke(s.path).length===0){r.push({route:s,path:s.path});continue}for(let{param:a,value:i,record:l}of await li(s,e,t,n))r.push({route:s,path:s.path.replace(`:${a}`,encodeURIComponent(i)),record:l})}return r}function Ko(o,e){return o.startsWith("/")?`${e}${o}`:o}function Yt(o){return typeof o=="object"&&o!==null&&"collection"in o&&"fields"in o}function Yo(o,e,t){for(let n of Object.values(o))if(Yt(n)&&n.collection===e)return n;throw new Error(`[dndev] Entity page "${t}": no entity definition for collection "${e}". Export it from the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`)}function Zo(o,e,t){let n=Object.create(null);for(let r of e)!r.collection||Object.hasOwn(n,r.collection)||(n[r.collection]=t(Yo(o,r.collection,r.path)).get);return Object.freeze(n)}function Xo(o,e){let{route:t,value:n,language:r,baseUrl:s,siteName:a,type:i}=e,l=Yo(e.entities,t.collection,t.path),c=e.deriveEntitySeo(l,o,{t:e.translate([l.namespace,"crud"]),locale:r}),u=ke(t.path)[0],p=t.path.replace(`:${u}`,encodeURIComponent(n)),d=y=>e.languageUrl(y,r,s,e.routing,e.trailingSlash),f=d(p),g=c.title?`${c.title} | ${a}`:a,v=Ko(c.image||e.defaultImage,s),h=i==="product"?e.buildProductJsonLd({...c,images:[...new Set(c.images.map(y=>Ko(y,s)))]},f):null;return{url:f,title:g,...c.description&&{description:c.description},image:v,type:i,jsonLd:h,breadcrumb:c.title?e.buildBreadcrumbJsonLd(p,a,d,c.title):null}}Y();function Qo(o){return(e,t)=>{let n=e.indexOf(":"),r=o[e.slice(0,n)];for(let s of e.slice(n+1).split("."))r=r&&typeof r=="object"&&s in r?r[s]:void 0;return typeof r=="string"?r:t?.defaultValue??e}}var ci="dndev",ui="crud",pi="entity-";function er(o,e,t){return e?o?.[e]?.[t]:void 0}function Re(o){return typeof o=="string"&&o.trim()!==""?o.trim():void 0}function tr(o){return o?.metaExport||o?.meta||{}}function di(o,{siteName:e,defaultNamespace:t,t:n}){let r=tr(o),{title:s,pageTitle:a}=qn({meta:r,ns:r.namespace||null,defaultNs:t,t:n,siteName:e});return a??s}function fi(o,e,t){let n=tr(o),r=n.seo||{};if(r.description===null)return;let s=er(e,n.namespace,t);return Re(r.description)??Re(s?.description)}function nr(o){let{siteName:e,description:t,baseUrl:n,sitemapRoutes:r,routes:s,blogPosts:a=[],blogPath:i="/blog",translations:l,language:c,defaultNamespace:u}=o,p=er(l,ci,c)?.seo,d=Re(p?.llmsPages),f=Re(p?.llmsBlog);if(!d||!f)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${c}".`);if(!u)throw new Error('[dndev] llms.txt: getLlmsTxtSource needs options.defaultNamespace (appConfig.seo.defaultNamespace, else "home").');let g=new Map(s.map(S=>[S.path,S])),v={siteName:e,defaultNamespace:u,t:Qo(Object.fromEntries(Object.entries(l||{}).map(([S,x])=>[S,x?.[c]])))},h=new Map(a.map(S=>[`${i}/${S.slug}`,S])),y=r.map(({path:S,collection:x})=>{let N=h.get(S);if(N)return{path:S,title:N.title,...Re(N.description)&&{description:Re(N.description)},section:f};if(x)return{path:S,collection:x};let D=g.get(S);if(!D&&S===i)return{path:S,title:f};let P=fi(D,l,c);return{path:S,title:di(D,v),...P&&{description:P}}}),C={},$={};for(let[S,x]of Object.entries(l||{})){if(S===ui&&x?.[c]&&($[S]=x[c]),!S.startsWith(pi))continue;x?.[c]&&($[S]=x[c]);let N=Re(x?.[c]?.namePlural);N&&(C[S]=N)}return{name:e,...Re(t)&&{summary:Re(t)},baseUrl:n,pagesHeading:d,routes:y,entityHeadings:C,language:c,translations:$}}function or(o={}){let{siteName:e,baseUrl:t,blogPosts:n=[],blogPath:r="/blog",appRoot:s,logger:a}=o;if(!e||!t)return null;if(n.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=O.getInstance(),l=s?i.resolvePath("src/content/blog",s):null;if(!l||!i.pathExists(l))return null;let c=[`# ${e}
590
+ `];o.description&&c.push(`> ${o.description}
591
+ `);for(let u of n){let p=i.resolvePath(`${u.slug}_en.md`,l);try{let d=i.readSync(p,{format:"text"});if(!d)continue;let f=d.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),g=`${t}${r}/${u.slug}`;c.push(`## ${u.title}
592
+ `),c.push(`Source: ${g}
593
+ `),u.date&&c.push(`Date: ${u.date}
594
+ `),c.push(f.trim()),c.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${u.slug}`)}}return c.join(`
595
+ `)}import gi from"i18next";function Xe(o){return o.replace(/\s+/g," ").trim()}function rr(o){let e=[`# ${Xe(o.name)}`,""];o.summary&&e.push(`> ${Xe(o.summary)}`,"");for(let t of o.sections)if(t.links.length!==0){e.push(`## ${Xe(t.heading)}`,"");for(let n of t.links){let r=`- [${Xe(n.title)}](${n.url})`;e.push(n.description?`${r}: ${Xe(n.description)}`:r)}e.push("")}return e.join(`
596
+ `)}function mi(o){let e=new Map;for(let t of Object.values(o))Yt(t)&&e.set(t.collection,t);return e}function hi(o,e){let t=gi.createInstance();return t.init({lng:o,resources:{[o]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),n=>t.getFixedT(o,[n,"crud"])}async function sr(o){let{crud:e,readSchemas:t,deriveEntitySeo:n,hiddenStatuses:r,formatTrailingSlash:s,trailingSlash:a}=o,i=mi(o.entities),l,c=new Map,u=p=>{let d=c.get(p);return d||(d={heading:p,links:[]},c.set(p,d)),d};u(o.pagesHeading);for(let{route:p,path:d,record:f}of await Ue(o.routes,e,r,t)){let g=`${o.baseUrl}${s(d,a)}`;if(!f){if(!p.title)throw new Error(`[dndev] llms.txt: source route "${p.path}" has no title (getLlmsTxtSource gives every static page one).`);u(p.section??o.pagesHeading).links.push({title:p.title,url:g,...p.description&&{description:p.description}});continue}let v=i.get(p.collection);if(!v)throw new Error(`[dndev] llms.txt: no entity definition for collection "${p.collection}" (route "${p.path}"). Export it from the app's \`entities\` package.`);let h=p.section??(v.namespace?o.entityHeadings[v.namespace]:void 0);if(!h)throw new Error(`[dndev] llms.txt: no heading for route "${p.path}". Add "namePlural" to the ${v.namespace??`entity-${v.name.toLowerCase()}`} translations.`);if(!l){if(!o.language||!o.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");l=hi(o.language,o.translations)}let y=n(v,f,{t:l(v.namespace),locale:o.language});u(h).links.push({title:y.title||o.name,url:g,...y.description&&{description:y.description}})}return rr({name:o.name,...o.summary&&{summary:o.summary},sections:[...c.values()]})}var ar=Object.freeze([{dependency:"@donotdev/supabase",module:"@donotdev/supabase/server",env:["SUPABASE_URL","SUPABASE_PUBLIC_KEY"],create:(o,[e,t])=>new o.SupabasePublicReader(o.createPublicServerClient(e,t))},{dependency:"@donotdev/firebase",module:"@donotdev/firebase/public",env:["FIREBASE_API_KEY","FIREBASE_PROJECT_ID"],create:(o,[e,t])=>new o.FirestorePublicReader(o.createPublicServerFirestore({apiKey:e,projectId:t}))}]);function ir(o){return ar.find(({dependency:e})=>o(e))}var lr=ar.map(({dependency:o})=>o).join(", ");function ie(o){return o?o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function cr(o){return o?o.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}function bt(o,e){return(o||e||"").trim().replace(/\/+$/,"")}var dr=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function vi(o,e){let t;try{let n=new URL(o);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error;t=n.hostname}catch{throw new Error(`[dndev] SEO: base URL "${o}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(dr.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: deploy build with base URL "${o}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}var yi="DNDEV_DEPLOY";function fr(o=process.env){let e=o.CI;return o[yi]==="1"||o.VERCEL==="1"||e!==void 0&&e!==""&&e!=="false"&&e!=="0"}var ur=new Set;function Qe(o,e,t,n=process.env){if(fr(n)){if(!o)throw new Error(`[dndev] SEO: deploy build without ${e}. The sitemap, robots.txt, llms.txt and canonical URLs need the production URL: set ${e} (or seo.baseUrl) in the build environment.`);return vi(o,e),o}let r=s=>{ur.has(s)||(ur.add(s),t.warn(s))};return!o||!bi(o)?(r(`[dndev] Local build without a usable ${e}${o?` ("${o}")`:""}: no sitemap.xml, llms.txt, robots.txt, rss.xml, canonical URLs or record pages. Set ${e} to build them.`),null):(wi(o)||r(`[dndev] Local build: sitemap.xml, llms.txt, canonical URLs and record pages carry ${o} (${e}). A deploy build (dndev deploy, Vercel, CI) needs the production URL.`),o)}async function wt(o,e,t,n=process.env){try{return await e(),!0}catch(r){if(be(r))throw r;let s=`${o.join(", ")} not written: ${r.message}`;if(fr(n))throw H("dndev-seo",`${s}. A deploy build publishes every SEO file.`,"seo-generation-failed",{files:o});return t.warn(`[dndev] Local build: ${s} (a deploy build fails on it).`),!1}}function bi(o){try{let{protocol:e}=new URL(o);return e==="https:"||e==="http:"}catch{return!1}}function wi(o){let{hostname:e}=new URL(o);return!dr.has(e)&&!e.endsWith(".localhost")}var Zt=Object.freeze(["/api"]),pr=new Set(["/404","/not-found","/500","/error"]);function Et(o){return o.auth&&o.auth!==!1||pr.has(o.path)||pr.has(o.meta?.route)?!1:o.meta?.seo?.noindex!==!0}function en(o){return typeof o.path=="string"&&o.path.split("/").includes("*")}function gr(o){if(!(typeof o.path!="string"||!o.path.includes(":"))&&Et(o))return o.meta?.entity||void 0}function mr(o){if(typeof o.path!="string"||o.path.includes("*")||ke(o.path).length!==1)return null;let e=gr(o);return e?{path:o.path,collection:e}:null}function Ei(o=[]){return{totalRoutes:o.length,publicRoutes:o.filter(e=>!e.auth||e.auth===!1).length,protectedRoutes:o.filter(e=>e.auth&&e.auth.required).length}}var We=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:n=!0,baseUrl:r,siteName:s,crawlDelay:a=1,aiCrawlers:i="recommended",routes:l={},...c}=e;if(!r||!s)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:n,baseUrl:r,siteName:s,crawlDelay:a,aiCrawlers:i,routes:l,blogPath:"/blog",...c},this.appRoot=c.appRoot||null,this.logger=G("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,n){let r={routes:e.routes||[],baseUrl:this.options.baseUrl,siteName:this.options.siteName},s={robotsTxt:null,rss:null,manifest:null};return this.options.generateRobotsTxt&&(s.robotsTxt=await this.generateRobotsTxt(r,t)),n.length>0&&(s.rss=await this.generateRSSFeed(n,t)),s.manifest=await this.generateManifest(r,t),s}async generateRobotsTxt(e,t){let n=this.options.shellPath?[...Zt,this.options.shellPath]:Zt,r=this.generateRobotsTxtContent({disallowedPaths:n,sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",r),{fileName:"robots.txt",content:r,disallowedPaths:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:n}=this.options,r=[];for(let s of e||[]){if(!Et(s)||typeof s.path!="string"||en(s))continue;let a=s.path===n||s.path.startsWith(`${n}/`);if(!(t.length>0&&a))if(s.path.includes(":")){if(a)continue;let i=gr(s);r.push({path:s.path,...i&&{collection:i}})}else r.push({path:s.path})}if(t.length>0){r.push({path:n,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let s of t)r.push({path:`${n}/${s.slug}`,priority:.6,changeFrequency:"monthly",...s.date&&{lastModified:s.date}})}return r}async generateManifest(e,t){let n={...Ei(e.routes),baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()},r=JSON.stringify(n,null,2);return await t("seo-manifest.json",r),{fileName:"seo-manifest.json",content:r,manifest:n}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:n=Zt,sitemap:r,crawlDelay:s}=e,a=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...n.map(c=>`Disallow: ${a(c)}`),...t.map(c=>`Allow: ${a(c)}`)];s&&i.push(`Crawl-delay: ${s}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Si(l))),i.join(`
597
+ `)}discoverBlogPosts(){return this.appRoot?it(this.appRoot,this.logger):[]}async generateRSSFeed(e,t){let n=e.map(s=>` <item>
598
+ <title><![CDATA[${cr(s.title)}]]></title>
599
+ <link>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}/${ie(s.slug)}</link>
600
+ <guid>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}/${ie(s.slug)}</guid>
601
+ <description><![CDATA[${cr(s.description)}]]></description>
602
+ <pubDate>${s.date?new Date(s.date).toUTCString():""}</pubDate>${s.tags.length?`
603
+ <category>${ie(s.tags.join(", "))}</category>`:""}${s.image?`
604
+ <enclosure url="${ie(this.options.baseUrl)}${ie(s.image)}" type="image/png" length="0"/>`:""}
605
+ </item>`).join(`
606
+ `),r=`<?xml version="1.0" encoding="UTF-8"?>
607
+ <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
608
+ <channel>
609
+ <title>${ie(this.options.siteName)}</title>
610
+ <link>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}</link>
611
+ <description>${ie(this.options.siteName)} Blog</description>
612
+ <language>en</language>
613
+ <atom:link href="${ie(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
614
+ ${n}
615
+ </channel>
616
+ </rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}},Xt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],Qt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Si(o){let e=["# AI Crawler Management"];if(o==="block-all"){for(let t of[...Xt,...Qt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(o==="allow-all"){for(let t of[...Xt,...Qt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of Xt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of Qt)e.push(`User-agent: ${t}`,"Allow: /","");return e}function St(o){return String(o).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function hr(o,{baseUrl:e,routing:t,trailingSlash:n,crud:r,readSchemas:s,languageUrls:a,hiddenStatuses:i}){let l=[],c=(u,p)=>{let d=a(u,e,t,n),f=t.languages.length>1?{alternates:{languages:d}}:{};for(let g of t.languages)l.push({url:d[g],...p,...f})};for(let{route:u,path:p,record:d}of await Ue(o,r,i,s)){if(!d){c(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??(p==="/"?1:.8),...u.lastModified&&{lastModified:u.lastModified}});continue}let f=d.updatedAt instanceof Date?d.updatedAt.toISOString():d.updatedAt;c(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??.7,...typeof f=="string"&&{lastModified:f}})}return l}function vr(o){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${o.some(n=>n.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let n of o){t.push(" <url>",` <loc>${St(n.url)}</loc>`);for(let[r,s]of Object.entries(n.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${St(r)}" href="${St(s)}" />`);n.lastModified&&t.push(` <lastmod>${St(n.lastModified)}</lastmod>`),n.changeFrequency&&t.push(` <changefreq>${n.changeFrequency}</changefreq>`),n.priority!==void 0&&t.push(` <priority>${n.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
617
+ `)}var et=!1,yr=["react-server","module","node","import","default"];function xi(o){let e=[];for(let t of o){let n=mr(t);n&&e.push({route:n,type:t.meta?.seo?.type??"website"})}return e}function $i(o,e,t){let n={...o?.dependencies,...o?.devDependencies},r=ir(i=>!!n[i]);if(!r)throw new Error(`[dndev] ${t.join(", ")} list published records, but the app's backend provider has no public reader (supported: ${lr}). Mark these pages \`seo: { noindex: true }\`.`);let s=r.env.map(i=>`VITE_${i}`),a=s.map(i=>e[i]);if(a.some(i=>!i))throw new Error(`[dndev] Set ${s.join(" and ")}: the build lists the published records of ${t.join(", ")} (record pages, sitemap.xml, llms.txt).`);return{module:r.module,create:i=>r.create(i,a)}}function Pi(o,e,t=process.env){if(!Qe(o||null,"VITE_APP_URL",e,t))return null;if(o.endsWith("/")||o!==o.trim())throw new Error(`[dndev] VITE_APP_URL "${o}" must have no trailing slash or spaces: the browser builds canonical URLs from it as is.`);return o}function Ri(o){let e=new Map;return{query(t,n,r){let s=JSON.stringify([t,n]);return e.has(s)||e.set(s,o.query(t,n,r)),e.get(s)}}}async function Ci({staticRoutes:o,records:e,crud:t,readSchemas:n,core:r,entities:s,translate:a,routing:i,baseUrl:l,siteName:c,hreflang:u,defaultNamespace:p,defaultImage:d,pageShell:f}){let g=u&&r.isMultilingual(i.languages),v=[],h=[],y=new Set,C=($,S)=>{let x=g?r.languageUrls($,l,i,et):null;for(let N of i.languages){let D=r.localizePath($,N,i),P=qo(D);if(!P||y.has(P)){h.push(D);continue}y.add(P);let k=r.languageUrl($,N,l,i,et),_=S(N,k),m=[..._.tags,...r.siteHeadTags({url:l?k:null,siteName:c,alternates:x,defaultLanguage:i.defaultLanguage})];v.push({file:P,html:Jo(f(N),{tags:m,headScript:r.jsonScriptText({url:k,..._}),headElementId:r.PRERENDERED_HEAD_ELEMENT_ID})})}};for(let $ of o){let S=$.meta??{},x=S.namespace||null;C($.path,(N,D)=>({tags:r.routeHeadTags(r.routeSeo({meta:S,ns:x,defaultNs:p,t:a([x??p],N),siteName:c,baseUrl:l,url:D,defaultImage:d,authOnly:!!$.auth}),{siteName:c,baseUrl:l}),breadcrumb:!1}))}if(e.length>0){let $=new Map(e.map(({route:x,type:N})=>[x.path,N])),S=await Ue(e.map(({route:x})=>x),t,r.HIDDEN_STATUSES,n);for(let{route:x,path:N,record:D}of S){let P=String(D[ke(x.path)[0]]);C(N,k=>{let _=Xo(D,{route:x,value:P,language:k,routing:i,baseUrl:l,trailingSlash:et,siteName:c,defaultImage:d,type:$.get(x.path),entities:s,translate:m=>a(m,k),deriveEntitySeo:r.deriveEntitySeo,buildProductJsonLd:r.buildProductJsonLd,buildBreadcrumbJsonLd:r.buildBreadcrumbJsonLd,languageUrl:r.languageUrl});return{tags:r.recordHeadTags(_),breadcrumb:_.breadcrumb!==null}})}}return{pages:v,skipped:h}}async function _i({routes:o,blogPosts:e,generator:t,crud:n,readSchemas:r,core:s,entities:a,routing:i,baseUrl:l,siteName:c,siteDescription:u,translations:p,defaultNamespace:d,sitemap:f,llmsTxt:g}){let v=t.getSitemapRoutes(o,e),h=[];if(f){let y=await hr(v,{baseUrl:l,routing:i,trailingSlash:et,crud:n,readSchemas:r,languageUrls:s.languageUrls,hiddenStatuses:s.HIDDEN_STATUSES});h.push({file:"/sitemap.xml",content:vr(y)})}if(g){let y=nr({siteName:c,description:u,baseUrl:l,sitemapRoutes:v,routes:o,blogPosts:e,blogPath:t.options.blogPath,translations:p,language:i.defaultLanguage,defaultNamespace:d});h.push({file:"/llms.txt",content:await sr({...y,trailingSlash:et,formatTrailingSlash:s.formatTrailingSlash,entities:a,crud:n,readSchemas:r,deriveEntitySeo:s.deriveEntitySeo,hiddenStatuses:s.HIDDEN_STATUSES})})}return h}async function xt(o,e,t){try{return await o.import(e)}catch(n){throw new Error(`[dndev] Build pages: cannot load "${e}" (${t}): ${n.message}`,{cause:n})}}async function br({appRoot:o,mode:e,manifestRoutes:t,blogPosts:n,staticRoutes:r,prerenderRecords:s,shellHtml:a,pageShell:i,seo:l,loadI18n:c,pkg:u,write:p,logger:d}){if(!a)throw new Error("[dndev] Build pages: the build output has no index.html (the SPA shell).");if(await p(`/${rt}`,a),l.disabled)return{pages:0,listings:[]};let{createServer:f,loadEnv:g}=await import("vite"),v=g(e,o,"VITE_"),h=l.siteName,y=l.defaultNamespace||"home",C=Qe(bt(l.baseUrl,v.VITE_APP_URL)||null,"VITE_APP_URL",d)??"",S=(l.generateSitemap!==!1||l.llmsTxt!==!1)&&!!(C&&h),x=xi(t),N=s&&x.length>0?Pi(v.VITE_APP_URL,d):null,D=N?x:[],P=x.length>0&&(D.length>0||S);if(r.length===0&&D.length===0&&!S)return{pages:0,listings:[]};if(!h)throw new Error("[dndev] Prerendered page titles end with the site name. Set appConfig.app.name (or appConfig.seo.siteName).");let k=null,_=x.map(({route:L})=>L.path);if(P){if(!{...u?.dependencies,...u?.devDependencies}.entities)throw new Error(`[dndev] ${_.join(", ")}: record pages derive their identity from the entity definition, but the app does not depend on an \`entities\` package. Add the entity to the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`);k=$i(u,v,_)}let m=N??v.VITE_APP_URL??"",A=await c(),B={languages:A.supportedLanguages,defaultLanguage:A.fallbackLanguage},w=await f({root:o,configFile:!1,envFile:!1,logLevel:"error",appType:"custom",server:{middlewareMode:!0,hmr:!1,ws:!1,watch:null},optimizeDeps:{noDiscovery:!0,include:[]},resolve:{conditions:yr},ssr:{resolve:{conditions:yr,externalConditions:["react-server"]}}}),M=globalThis._DNDEV_CONFIG_;globalThis._DNDEV_CONFIG_={...M,i18n:{languages:A.supportedLanguages,eager:A.eagerNamespaces,fallback:A.fallbackLanguage,content:A.content}};try{let L=w.environments.ssr.runner,z=await xt(L,"@donotdev/core/server","SEO helpers"),K=await xt(L,"@donotdev/core/rsc","translations"),U={},Z,R;if(k){U=await xt(L,"entities","the entity definitions");let X=await xt(L,k.module,"the public reader");Z=Ri(k.create(X)),R=Zo(U,x.map(({route:te})=>te),z.createSchemas)}let I=(X,te)=>K.useTranslation(X,{language:te}).t,{pages:F,skipped:W}=await Ci({staticRoutes:r,records:D,crud:Z,readSchemas:R,core:z,entities:U,translate:I,routing:B,baseUrl:m,siteName:h,hreflang:l.hreflang!==!1,defaultNamespace:y,defaultImage:l.defaultImage||qe,pageShell:i});for(let X of F)await p(X.file,X.html);W.length>0&&d.warn(`Pages left to the SPA shell (a static page serves the URL, or no file name can hold it): ${W.join(", ")}`);let Q=S?await _i({routes:t,blogPosts:n,generator:new We({baseUrl:C,siteName:h,appRoot:o}),crud:Z,readSchemas:R,core:z,entities:U,routing:B,baseUrl:C,siteName:h,siteDescription:l.siteDescription,translations:A.content,defaultNamespace:y,sitemap:l.generateSitemap!==!1,llmsTxt:l.llmsTxt!==!1}):[];for(let{file:X,content:te}of Q)await p(X,te);return{pages:F.length,listings:Q.map(({file:X})=>X)}}finally{M===void 0?delete globalThis._DNDEV_CONFIG_:globalThis._DNDEV_CONFIG_=M,await w.close()}}function Ai(o=!0){if(typeof o=="boolean")return o;throw new Error(`appConfig.prerenderRecords must be true or false. Got ${JSON.stringify(o)}.`)}function wr(o={}){let{routes:e="auto",prerenderRecords:t,seo:n={},i18nStore:r,fontPlan:s,debug:a,verbose:i,routeManifest:l}=o;if(!l||!r||!s)throw new Error("[dndev] createVitePrerenderPlugin: options.routeManifest, options.i18nStore and options.fontPlan are required (createVitePlugins passes the route, i18n and font plugins', createRouteManifestStore / createI18nStore / createFontPlanStore).");let c=e==="auto"&&Ai(t),u=G("Prerender",a,i),p=O.getInstance(),d=null,f=!1,g=!1;return{name:"dndev-prerender",enforce:"post",applyToEnvironment(v){return v.name==="client"},configResolved(v){f=v.command==="build",d={outDir:v.build?.outDir||"dist",mode:v.mode}},buildStart(){g=!1},writeBundle(){g=!0},async closeBundle(){if(!g||!d||!f)return;let v=p.getAppRoot(),h=p.resolveAppPath(d.outDir),y=l.get(),C=y.routes,$=new yt({routes:Array.isArray(e)?e:[],debug:a,outDir:h,logger:u}),S=new Map(C.map(m=>[m.path,m])),N=(e==="auto"?[...new Set(Ln(C).filter(m=>!m.includes("*")))]:$.expandRoutes(y)).map(m=>S.get(m)??{path:m}),D=p.readSync(p.resolvePath("index.html",h)),{preloads:P}=s.get(),{pages:k,listings:_}=await br({appRoot:v,mode:d.mode,manifestRoutes:C,blogPosts:y.blogPosts,staticRoutes:N,prerenderRecords:c,shellHtml:D,pageShell:m=>xo(D,P[m]),seo:n,loadI18n:async()=>r.get(),pkg:p.readSync(p.resolveAppPath("package.json"),{format:"json"}),write:(m,A)=>$.writeOutputFile(m,A),logger:u});k>0&&u.info(`Prerendered: ${k} pages`);for(let m of _)u.info(`\u{1F4C4} ${m.slice(1)}`)}}}import{VitePWA as Ni}from"vite-plugin-pwa";var $t=class extends fe{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:n}=e,r=[...t,...n];this.logger.debug(`Processing ${r.length} PWA files`);let s=await this._analyzePWAFiles(r),a=[...s.filter(l=>l.type==="manifest"||l.type==="service-worker"),...s.filter(l=>l.type==="icon")],i=this._generatePWAManifest(a);return{assets:a,manifest:i,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 n of e){let r=typeof n=="string"?{absolutePath:n,relativePath:this.pathResolver.getRelativePath(n),fileName:n.split("/").pop()||"",extension:(n.split(".").pop()||"").toLowerCase()}:n,s=await this._analyzePWAAsset(r);s&&t.push(s)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let n=e.relativePath,r=e.fileName;return r==="manifest.json"?this._parseManifestFile(t,n):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,n):this._isPWAIcon(r)?this._parseIconFile(e,n):null}_parseManifestFile(e,t){try{let n=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:n,size:typeof e=="string"?e.length:JSON.stringify(n).length}}catch(n){return this.logger.debug(`Failed to parse manifest: ${n.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let n=e.fileName,r=this._extractIconSize(n);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(n)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(n=>e.includes(n))}_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"),n=this._getDefaultManifest();return t.length>0&&(n.icons=t.map(r=>this.toManifestIcon(r))),n}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},n=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:n==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[n]||`image/${n}`,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 n=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,s=t.precacheManifest||[],a=JSON.stringify(s,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
584
618
  // Generated at ${new Date().toISOString()}
585
619
 
586
620
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
@@ -600,7 +634,7 @@ const precacheManifest = ${a.length>2?a:"self.__WB_MANIFEST || []"};
600
634
  precacheAndRoute(precacheManifest);
601
635
 
602
636
  // Runtime caching strategies
603
- ${this._generateWorkboxRuntimeCaching(s.runtimeCaching,t)}
637
+ ${this._generateWorkboxRuntimeCaching(n.runtimeCaching,t)}
604
638
 
605
639
  ${r?this._generateBackgroundSync(t.backgroundSync):""}
606
640
 
@@ -614,57 +648,61 @@ self.addEventListener('message', (event) => {
614
648
  self.addEventListener('activate', (event) => {
615
649
  event.waitUntil(self.clients.claim());
616
650
  });
617
- `}_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:n,handler:a,options:i={}}=s,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",u;typeof n=="function"?u="({ request }) => request.destination === 'document'":n instanceof RegExp?u=n.toString():u=JSON.stringify(n);let c=[];i.expiration&&c.push(`new ExpirationPlugin({
651
+ `}_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((n,r)=>{let{urlPattern:s,handler:a,options:i={}}=n,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",c;typeof s=="function"?c="({ request }) => request.destination === 'document'":s instanceof RegExp?c=s.toString():c=JSON.stringify(s);let u=[];i.expiration&&u.push(`new ExpirationPlugin({
618
652
  maxEntries: ${i.expiration.maxEntries||50},
619
653
  maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
620
- })`),i.cacheableResponse&&c.push(`new CacheableResponsePlugin({
654
+ })`),i.cacheableResponse&&u.push(`new CacheableResponsePlugin({
621
655
  statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
622
- })`),i.backgroundSync&&c.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
656
+ })`),i.backgroundSync&&u.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
623
657
  maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
624
658
  })`);let p="";return i.cacheName&&(p+=`
625
- cacheName: '${i.cacheName}',`),c.length>0&&(p+=`
659
+ cacheName: '${i.cacheName}',`),u.length>0&&(p+=`
626
660
  plugins: [
627
- ${c.join(`,
661
+ ${u.join(`,
628
662
  `)}
629
663
  ],`),i.networkTimeoutSeconds&&(p+=`
630
664
  networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${i.cacheName||"cache-"+r}
631
665
  registerRoute(
632
- ${u},
666
+ ${c},
633
667
  new ${l}({${p}
634
668
  })
635
669
  );`}).join(`
636
670
 
637
- `)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",s=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,n;return typeof r=="function"||r instanceof RegExp?n=r.toString():n=JSON.stringify(r),`
671
+ `)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",n=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,s;return typeof r=="function"||r instanceof RegExp?s=r.toString():s=JSON.stringify(r),`
638
672
  // Background sync for offline actions
639
673
  const { NetworkOnly } = workbox.strategies;
640
674
  registerRoute(
641
- ${n},
675
+ ${s},
642
676
  new NetworkOnly({
643
677
  plugins: [
644
678
  new BackgroundSyncPlugin('${t}', {
645
- maxRetentionTime: ${s},
679
+ maxRetentionTime: ${n},
646
680
  }),
647
681
  ],
648
682
  }),
649
683
  'POST'
650
684
  );
651
- `}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`),n=[];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/`,"")}`;n.push({url:p,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return n}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()}};G();function Os(o={}){if(!o.enabled)return null;let e=o.app||{},t=[];if(e.name||t.push("name"),e.shortName||t.push("shortName"),e.description||t.push("description"),t.length>0){let c=T("PWA",o.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=E.getInstance(),r=Kt.data,n=new Xe(s,{...o,assetData:r}),a=o.devEnabled===!0,i={registerType:o.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let c=o.app||{},g=(await n.discoverPWAAssets()).assets.filter(f=>f.type==="icon").map(f=>n.toManifestIcon(f));return{name:c.name,short_name:c.shortName,description:c.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:g.length>0?g:[]}},workbox:{globPatterns:["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:c})=>c.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:!0,skipWaiting:!0,clientsClaim:!0,maximumFileSizeToCacheInBytes:5*1024*1024,navigateFallback:"/index.html",navigateFallbackDenylist:[/^\/api\/.*/],manifestTransforms:[c=>{let p=c.find(g=>g.url==="/index.html"||g.url==="index.html");return p&&!c.find(g=>g.url==="/")&&c.push({url:"/",revision:p.revision}),{manifest:c,warnings:[]}}]},devOptions:{enabled:a,type:"module"}},u={...i,manifest:async()=>{let c=await i.manifest();if(o.manifest){if(typeof o.manifest=="function"){let p=await o.manifest();return{...c,...p}}return{...c,...o.manifest}}return c},workbox:{...i.workbox,...o.workbox||{},runtimeCaching:[...i.workbox.runtimeCaching,...o.workbox?.runtimeCaching||[]],manifestTransforms:[...i.workbox.manifestTransforms||[],...o.workbox?.manifestTransforms||[]]}};return So(u)}B();B();function Ns(o,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=o.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,u)=>`icon: '${u}'`);let n=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...o.matchAll(n)].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,Ts=null;function Ro(o){let t=(o.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Po(o){let e=o.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw new Error(`PageMeta signedInRedirect in ${o.file} must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`);if(e.split(/[?#]/)[0]===o.path)throw new Error(`PageMeta signedInRedirect in ${o.file} points at the page itself (${e}): signed-in visitors would loop. Use another page.`)}}var Qe=class extends le{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&&Ts===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 n=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(n)}`)}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},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,u=>this._analyzePageFile(u,t)),n=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(n,u=>this._analyzePageFile(u,t)),i=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${n.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),Po(u)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+n.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,n="/src/"+r.replace(/\\/g,"/");n=n.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(s,e.absolutePath),i=Ro(n),u=i===ot.HOMEPAGE_COMPONENT?ot.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:p,action:g,...f}=a||{};return{path:u,component:i,importPath:n,auth:a?.auth||!1,meta:{...c,...f,entity:c.entity,action:c.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=Ns(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),n=e.route.params;if(Array.isArray(n)&&n.length>0){let a=n.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 n=e.split("/"),a=null,i=null;return n.length>1&&(a=n[n.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}}};import{existsSync as Eo,readdirSync as $o}from"node:fs";import{join as _o}from"node:path";function Cs(o){let e=_o(o,"src","content","blog");try{return Eo(e)?$o(e).some(t=>t.endsWith("_en.md")):!1}catch{return!1}}G();var ko={isEmpty:o=>!o.routes||o.routes.length===0,generateModule:(o,e,t="routes")=>{let s={totalRoutes:o.routes.length,authRequired:o.routes.filter(n=>n.auth&&n.auth.required).length,publicRoutes:o.routes.filter(n=>!n.auth||n.auth===!1).length,source:o.source,generatedAt:new Date().toISOString(),errors:o.errors.length,hasBlogFeed:Cs(E.getInstance().getAppRoot())},r=o.routes.map(n=>` {
652
- path: '${n.path}',
653
- component: () => import('${n.importPath}'),
654
- auth: ${JSON.stringify(n.auth,null,2).replace(/\n/g,`
685
+ `}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`),n=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),s=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${n}/**/*.{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/`,"")}`;s.push({url:p,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return s}generatePrecacheManifest(e=[],t=null){let n=e;return t&&typeof t=="function"&&(n=t(n)),n}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};Y();function Er(o={}){if(!o.enabled)return null;let e=o.app||{},t=[];if(e.name||t.push("name"),e.shortName||t.push("shortName"),e.description||t.push("description"),t.length>0){let c=G("PWA",o.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 n=O.getInstance(),r=new $t(n,o),s=o.devEnabled===!0,a={registerType:o.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let c=o.app||{},p=(await r.discoverPWAAssets()).assets.filter(d=>d.type==="icon").map(d=>r.toManifestIcon(d));return{name:c.name,short_name:c.shortName,description:c.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:p.length>0?p:[]}},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 u=c.find(p=>p.url==="/index.html"||p.url==="index.html");return u&&!c.find(p=>p.url==="/")&&c.push({url:"/",revision:u.revision}),{manifest:c,warnings:[]}}]},devOptions:{enabled:s,type:"module"}},l={...a,manifest:async()=>{let c=await a.manifest();if(o.manifest){if(typeof o.manifest=="function"){let u=await o.manifest();return{...c,...u}}return{...c,...o.manifest}}return c},workbox:{...a.workbox,...o.workbox||{},runtimeCaching:[...a.workbox.runtimeCaching,...o.workbox?.runtimeCaching||[]],manifestTransforms:[...a.workbox.manifestTransforms||[],...o.workbox?.manifestTransforms||[]]}};return Ni(l)}q();q();var ki=/^[A-Za-z_$][\w$]*$/,Di=/^(?:'[^'\\]*'|"[^"\\]*"|`[^`\\$]*`|-?\d[\w.]*|null|undefined|true|false)$/;function Ti(o,e){let t=0;for(let n=e;n<o.length;n++){let r=o[n];if(r==="'"||r==='"'||r==="`"){for(n++;n<o.length&&o[n]!==r;n++)o[n]==="\\"&&n++;continue}if(t===0&&(r===","||r==="/"&&/[/*]/.test(o[n+1]??"")))return n;if("([{".includes(r))t++;else if(")]}".includes(r)){if(t===0)return n;t--}}return o.length}function Oi(o){let e=/(^|[{,\s])entity\s*:\s*/gm,t="",n=0,r;for(;r=e.exec(o);){let s=r.index+r[0].length,a=Ti(o,s),i=o.slice(s,a).trimEnd();if(!i)continue;let l=Di.test(i)?i:ki.test(i)?`{ identifier: '${i}' }`:`{ expression: ${JSON.stringify(i)} }`;t+=o.slice(n,s)+l,n=s+i.length,e.lastIndex=n}return t+o.slice(n)}function Ii(o){let e=o instanceof Error?o.message:String(o),t=/^(\S+) is not defined$/.exec(e)?.[1];return t?`\`${t}\` is not a literal value (an import, a variable or a call)`:`it is not a plain object literal (${e})`}function Sr(o,e="unknown"){let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,n=o.match(t);if(!n)return null;let r=n[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,l)=>`icon: '${l}'`),r=Oi(r);let s=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;[...o.matchAll(s)].forEach(i=>{let l=i[1],c=i[2];r=r.replace(new RegExp(`\\b${l}\\b`,"g"),`'${c}'`)});try{return Function(`return ${r}`)()}catch(i){throw H("dndev-routes",`${e}: PageMeta cannot be read at build: ${Ii(i)}. Without it the page would lose its route, auth and seo. The build reads PageMeta statically: write every value as a literal in the object (strings, numbers, booleans, null, arrays and objects of those, icon: <Icon />, a string constant declared in the page file: const NAMESPACE = 'home'), except entity, the defineEntity identifier imported from 'entities'. Example: auth: { required: true, role: 'admin' } instead of auth: ADMIN_ONLY.`,"invalid-configuration")}}function xr(o){return/^[ \t]*export\s+(?:(?:async\s+)?function\s*\*?\s*generateMetadata\b|(?:const|let)\s+generateMetadata\b|\{[^}]*\bgenerateMetadata\b[^}]*\})/m.test(o)}import{existsSync as nn,readFileSync as tn,realpathSync as Fi}from"node:fs";import{dirname as $r,join as tt,resolve as Pr}from"node:path";var Ce="dndev-routes",Pt="entities",Mi="@donotdev/core",Rr=[".ts",".tsx",".js",".jsx"],Li=`import { productEntity } from 'entities';
686
+ export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,Cr=null;async function kr(){return Cr??=import("@babel/core").then(o=>o.default??o),Cr}function Dr(o,e,t){let n=/\.[jt]sx$/.test(t);try{return o.parseSync(e,{configFile:!1,babelrc:!1,filename:t,sourceType:"module",parserOpts:{plugins:n?["typescript","jsx"]:["typescript"]}}).program}catch(r){throw H(Ce,`${t} could not be parsed to resolve entities (PageMeta entity, entity field types): ${r.message}. Fix the syntax error.`,"invalid-configuration")}}function Ie(o){return o.type==="StringLiteral"?o.value:o.name}function Ge(o){let e=o;for(;e&&["TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","ParenthesizedExpression"].includes(e.type);)e=e.expression;return e}function ji(o,e){for(let t of o.body)if(!(t.type!=="ImportDeclaration"||t.importKind==="type")){for(let n of t.specifiers)if(n.local.name===e)return t.source.value!==Pt||n.type!=="ImportSpecifier"||n.importKind==="type"?null:Ie(n.imported)}return null}function on(o){let e=null,t=new Map;function n(){let u=tt(o,"package.json"),p=nn(u)?JSON.parse(tn(u,"utf8")):null;return!!(p?.dependencies?.[Pt]||p?.devDependencies?.[Pt])}function r(u){if(e)return e;let p=n(),d=o,f=null;for(;p;){let h=tt(d,"node_modules",Pt);if(nn(tt(h,"package.json"))){f=Fi(h);break}let y=$r(d);if(y===d)break;d=y}if(!f)throw H(Ce,`${u}, but the app has no \`entities\` package (${p?"not installed: run bun install":"not in the dependencies of its package.json"}). The entity is read from the app's defineEntity definitions. Fix: add \`"entities": "workspace:*"\` to the app's dependencies and export the entity from the entities package.`,"missing-required-resource");let g=JSON.parse(tn(tt(f,"package.json"),"utf8")),v=Nr(Pr(f,g.main??"./index.ts"));if(!v)throw H(Ce,`The \`entities\` package (${f}) has no entry module (package.json "main": ${JSON.stringify(g.main??"./index.ts")}). Fix: set "main" to its index file (./index.ts).`,"missing-required-resource");return e=v,e}async function s(u){if(!t.has(u)){let p=await kr();t.set(u,Dr(p,tn(u,"utf8"),u))}return t.get(u)}function a(u,p){return p.startsWith(".")?Nr(Pr($r(u),p)):null}async function i(u,p,d){let f=`${u}#${p}`;if(d.has(f))return null;d.add(f);let g=await s(u),v=[];for(let h of g.body)if(h.type==="ExportNamedDeclaration"&&h.exportKind!=="type"){let y=Ar(h.declaration,p);if(y!==void 0)return{init:y,program:g,file:u};for(let C of h.specifiers??[]){if(C.exportKind==="type"||Ie(C.exported)!==p)continue;if(C.type!=="ExportSpecifier")return null;let $=Ie(C.local);if(h.source){let S=a(u,h.source.value);return S?i(S,$,d):null}return l(u,g,$,d)}}else if(h.type==="ExportAllDeclaration"&&h.exportKind!=="type"){let y=a(u,h.source.value);y&&v.push(y)}for(let h of v){let y=await i(h,p,d);if(y)return y}return null}async function l(u,p,d,f){for(let g of p.body){let v=Ar(g,d);if(v!==void 0)return{init:v,program:p,file:u};if(!(g.type!=="ImportDeclaration"||g.importKind==="type"))for(let h of g.specifiers){if(h.local.name!==d||h.type!=="ImportSpecifier")continue;let y=a(u,g.source.value);return y?i(y,Ie(h.imported),f):null}}return null}async function c(u){let p=[u];for(let d=0;d<p.length;d+=1){let f=await s(p[d]);for(let g of f.body){if(!(g.type==="ImportDeclaration"&&g.importKind!=="type"||g.type==="ExportNamedDeclaration"&&g.source&&g.exportKind!=="type"||g.type==="ExportAllDeclaration"&&g.exportKind!=="type"))continue;let h=a(p[d],g.source.value);h&&!p.includes(h)&&p.push(h)}}return p}return{async usesFieldType(u){if(!n())return!1;for(let p of await c(r("The app's package.json lists `entities` (its entity field types are read)")))if(zi(await s(p),u))return!0;return!1},async collectionOf(u,p){let d=await i(r(`${p} declares a PageMeta entity`),u,new Set);if(!d)throw H(Ce,`${p}: PageMeta entity \`${u}\` is not exported by the \`entities\` package. The page names the entity definition it shows a record of. Fix: export it from the entities package index (export { ${u} } from './\u2026').`,"invalid-configuration");return Bi(d,u,p)}}}function Tr(o){return o.body.filter(e=>e.type==="ImportDeclaration"&&e.source.value===Mi).flatMap(e=>e.specifiers).find(e=>e.type==="ImportSpecifier"&&Ie(e.imported)==="defineEntity")?.local.name}function _r(o,e){if(o?.type!=="ObjectExpression")return;let t=o.properties.find(n=>n.type==="ObjectProperty"&&!n.computed&&Ie(n.key)===e);return Ge(t?.value)}function zi(o,e){let t=Tr(o);if(!t)return!1;let n=r=>{if(!r||typeof r.type!="string")return!1;if(r.type==="CallExpression"&&r.callee.type==="Identifier"&&r.callee.name===t){let s=_r(Ge(r.arguments[0]),"fields");if(s?.type==="ObjectExpression"&&s.properties.some(a=>{let i=_r(Ge(a.value),"type");return i?.type==="StringLiteral"&&i.value===e}))return!0}for(let s of Object.keys(r)){if(s==="loc"||s==="leadingComments"||s==="trailingComments")continue;let a=r[s];if(Array.isArray(a)?a.some(n):a&&typeof a=="object"&&n(a))return!0}return!1};return n(o)}function Ar(o,e){if(o?.type==="VariableDeclaration"){for(let t of o.declarations)if(t.id.type==="Identifier"&&t.id.name===e)return t.init??null}}function Nr(o){let e=o.replace(/\.[cm]?js$/,""),t=[o,...Rr.map(n=>`${e}${n}`),...Rr.map(n=>tt(o,`index${n}`))];for(let n of t)if(/\.[cm]?[jt]sx?$/.test(n)&&nn(n))return n;return null}function Bi({init:o,program:e,file:t},n,r){let s=Ge(o),a=Tr(e);if(s?.type!=="CallExpression"||s.callee.type!=="Identifier"||!a||s.callee.name!==a)throw H(Ce,`${r}: PageMeta entity \`${n}\` (${t}) is not a defineEntity definition. The build reads the collection from \`defineEntity({ collection: ... })\` in the entities package. Fix: export const ${n} = defineEntity({ name: '...', collection: '...', fields: { ... } }) with defineEntity imported from '@donotdev/core'.`,"invalid-configuration");let i=Ge(s.arguments[0]),l=i?.type==="ObjectExpression"?i.properties.find(p=>p.type==="ObjectProperty"&&!p.computed&&Ie(p.key)==="collection"):void 0,c=Ge(l?.value),u=c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0].value.cooked:null;if(!u)throw H(Ce,`${r}: PageMeta entity \`${n}\` (${t}) has no literal \`collection\` in its defineEntity options. The page's records (sitemap, prerender, server metadata) are read from it. Fix: set collection: 'products' (a string literal) in the defineEntity call.`,"invalid-configuration");return u}async function Or(o,e,t,n){if(!o||o.entity===void 0)return null;let r=o.entity?.identifier,s=o.entity?.expression;if(typeof s=="string"){let l=s.match(/^[A-Za-z_$][\w$]*\s*\??\.\s*([A-Za-z_$][\w$]*)$/)?.[1]??"productEntity";throw H(Ce,`${t}: PageMeta entity \`${s}\` is not a bare identifier. The build reads the entity statically: only a defineEntity definition named-imported from 'entities' resolves to its collection (no namespace import, member access or call). Fix: import { ${l} } from 'entities'; then entity: ${l}`,"invalid-configuration")}if(typeof r!="string")throw H(Ce,`${t}: PageMeta entity must be the entity definition imported from 'entities' (got ${JSON.stringify(o.entity)}). The build resolves it to the entity's collection. Fix:
687
+ ${Li}`,"invalid-configuration");let a=Dr(await kr(),e,t),i=ji(a,r);if(!i)throw H(Ce,`${t}: PageMeta entity \`${r}\` is not imported from 'entities'. The page's entity must be a defineEntity definition of the app's \`entities\` package (one source for its collection). Fix: import { ${r} } from 'entities';`,"invalid-configuration");return n.collectionOf(i,t)}var He=null,Ir=null;function Ui(o){let t=(o.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Wi(o){let e=o.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw H("dndev-routes",`${o.file}: PageMeta signedInRedirect must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`,"invalid-configuration");if(e.split(/[?#]/)[0]===o.path)throw H("dndev-routes",`${o.file}: PageMeta signedInRedirect points at the page itself (${e}): signed-in visitors would loop. Use another page.`,"invalid-configuration")}}function Gi(o,{pageGenerateMetadata:e=!1}={}){if(!o.path.split("/").some(n=>n.startsWith(":"))||en(o)||!Et(o)||o.meta?.entity||o.metaExport?.namespace==="blog"||e&&o.exportsGenerateMetadata)return;let t=["declare the record entity it shows: import { productEntity } from 'entities'; then entity: productEntity in its PageMeta (title, description and image from the record)",...e?["export Next's generateMetadata from the page module (a server module, no 'use client')"]:[],"keep it out of search engines: seo: { noindex: true } in its PageMeta"];throw H("dndev-routes",`${o.file}: public dynamic route ${o.path} has no per-URL SEO: every URL would get the same title and description (PageMeta + i18n), duplicate pages for search engines. Fix, one of:
688
+ `+t.map((n,r)=>` ${r+1}. ${n}`).join(`
689
+ `),"invalid-configuration")}var Rt=class extends fe{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(),n=process.env.DNDEV_BUILD_ID;if(He&&Ir===n)return this.logger.debug("Using cached route discovery results"),this.routes=He.routes,this.errors=He.errors,this.source=He.source,this.entityResolver=He.entityResolver,{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 s=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(s)}`)}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/"),He={routes:this.routes,errors:this.errors,source:this.source,entityResolver:this.entityResolver},Ir=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"}`}getEntityResolver(){return this.entityResolver??=on(this.pathResolver.getAppRoot()),this.entityResolver}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:n}=e;this.entityResolver=on(t);let r=await this._batchProcessFiles(n,c=>this._analyzePageFile(c,t)),s=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(s,c=>this._analyzePageFile(c,t)),i=[...r,...a];this.logger.debug(`Auto-discovering from ${n.length} app + ${s.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 H("dndev-routes",`${c.file}: route ${u} is also the route of ${p.file}: two pages cannot share a URL. Give one of them another path with a PageMeta route override, e.g. export const meta: PageMeta = { route: '/custom-path' };`,"invalid-configuration")}l.set(u,c),Wi(c),Gi(c,{pageGenerateMetadata:this.options.pageGenerateMetadata===!0})}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${n.length+s.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(n=>this.pathResolver.resolveAppPath(n));if(t.length===0)return[];try{let{consumerFiles:n}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return n}catch(n){return this.logger.debug(`Error scanning additional patterns: ${n.message}`),[]}}async _analyzePageFile(e,t){let n=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!n)return null;let r=e.relativePath,s="/src/"+r.replace(/\\/g,"/");s=s.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(n,r),i=Ui(s),c=i===Nt.HOMEPAGE_COMPONENT?Nt.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),u=this._extractPageMeta(r),p=await Or(a,n,r,this.entityResolver),{entity:d,action:f,...g}=a||{};return{path:c,component:i,importPath:s,auth:a?.auth||!1,meta:{...u,...g,...p&&{entity:p},action:u.action},metaExport:a&&{...a,...p&&{entity:p}},exportsGenerateMetadata:xr(n),file:r}}_extractMetaExport(e,t){try{let n=Sr(e,t);return n?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(n)}`),n):null}catch(n){if(be(n))throw n;return this.logger.debug(`Error parsing meta export from ${t}: ${n.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,n){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),s=e.route.params;if(Array.isArray(s)&&s.length>0){let a=s.map(i=>`:${i}`).join("/");return`${r}/${a}`}return r}return this.logger.warn(`Invalid route format in ${n}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${n}`),this._generateRoutePath(t)}_extractPageMeta(e){let t=e.split("/").pop()?.replace(".tsx","")||"",n=t.replace(/Page$/,"");n=n.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),n=n.charAt(0).toUpperCase()+n.slice(1);let r=e.split("/"),s=null;return r.length>1&&(t.includes("List")?s="list":t.includes("Form")||t.includes("Create")||t.includes("Edit")?s="form":(t.includes("Detail")||t.includes("View"))&&(s="detail")),{title:n,action:s,file:e}}};Y();var Hi={isEmpty:o=>!o.routes||o.routes.length===0,generateModule:(o,e,t="routes")=>{let n={totalRoutes:o.routes.length,authRequired:o.routes.filter(s=>s.auth&&s.auth.required).length,publicRoutes:o.routes.filter(s=>!s.auth||s.auth===!1).length,source:o.source,generatedAt:new Date().toISOString(),errors:o.errors.length,hasBlogFeed:In(O.getInstance().getAppRoot())},r=o.routes.map(s=>` {
690
+ path: '${s.path}',
691
+ component: () => import('${s.importPath}'),
692
+ auth: ${JSON.stringify(s.auth,null,2).replace(/\n/g,`
655
693
  `)},
656
- meta: ${JSON.stringify(n.meta,null,2).replace(/\n/g,`
694
+ meta: ${JSON.stringify(s.meta,null,2).replace(/\n/g,`
657
695
  `)}
658
696
  }`).join(`,
659
697
  `);return`
660
- // ${z.routes} - Generated route data
698
+ // ${V.routes} - Generated route data
661
699
  import { lazy } from 'react';
662
700
 
663
701
  const routeData = [
664
702
  ${r}
665
703
  ];
666
704
 
667
- const routeManifest = ${JSON.stringify(s,null,2)};
705
+ const routeManifest = ${JSON.stringify(n,null,2)};
668
706
 
669
707
  // Populate unified DnDev config for runtime access
670
708
  if (typeof globalThis !== 'undefined') {
@@ -679,13 +717,13 @@ if (typeof globalThis !== 'undefined') {
679
717
  }
680
718
 
681
719
  // Include all routes in mapping (navigation store will filter by hideFromMenu)
682
- globalThis._DNDEV_CONFIG_.${K[t]} = {
720
+ globalThis._DNDEV_CONFIG_.${oe[t]} = {
683
721
  mapping: routeData,
684
722
  manifest: {
685
723
  totalRoutes: ${o.routes.length},
686
- authRequired: ${o.routes.filter(n=>n.auth&&n.auth.required).length},
687
- publicRoutes: ${o.routes.filter(n=>!n.auth||n.auth===!1).length},
688
- hasBlogFeed: ${s.hasBlogFeed},
724
+ authRequired: ${o.routes.filter(s=>s.auth&&s.auth.required).length},
725
+ publicRoutes: ${o.routes.filter(s=>!s.auth||s.auth===!1).length},
726
+ hasBlogFeed: ${n.hasBlogFeed},
689
727
  generatedAt: new Date().toISOString(),
690
728
  },
691
729
  };
@@ -697,8 +735,8 @@ export const manifest = routeManifest;
697
735
  export const source = '${o.source}';
698
736
 
699
737
  export default { routes: routeData, manifest: routeManifest, source: '${o.source}' };
700
- `},generateEmpty:(o,e,t,s="routes")=>{let r={totalRoutes:0,authRequired:0,publicRoutes:0,source:"empty",generatedAt:new Date().toISOString()};return`
701
- // ${z.routes} - Empty route data
738
+ `},generateEmpty:(o,e,t,n="routes")=>{let r={totalRoutes:0,authRequired:0,publicRoutes:0,source:"empty",generatedAt:new Date().toISOString()};return`
739
+ // ${V.routes} - Empty route data
702
740
 
703
741
  const routeData = [];
704
742
  const routeManifest = ${JSON.stringify(r,null,2)};
@@ -717,7 +755,7 @@ if (typeof globalThis !== 'undefined') {
717
755
  }
718
756
 
719
757
  // Populate empty routes configuration
720
- globalThis._DNDEV_CONFIG_.${K[s]} = {
758
+ globalThis._DNDEV_CONFIG_.${oe[n]} = {
721
759
  mapping: [],
722
760
  manifest: {
723
761
  totalRoutes: 0,
@@ -750,19 +788,19 @@ export const routeManifest = {
750
788
  };
751
789
 
752
790
  export default discoveredRoutes;
753
- `;let t=o.routes.map(s=>` {
754
- path: '${s.path}',
755
- component: () => import('${s.importPath}'),
756
- auth: ${JSON.stringify(s.auth,null,2).replace(/\n/g,`
791
+ `;let t=o.routes.map(n=>` {
792
+ path: '${n.path}',
793
+ component: () => import('${n.importPath}'),
794
+ auth: ${JSON.stringify(n.auth,null,2).replace(/\n/g,`
757
795
  `)},
758
- meta: ${JSON.stringify(s.meta,null,2).replace(/\n/g,`
796
+ meta: ${JSON.stringify(n.meta,null,2).replace(/\n/g,`
759
797
  `)}
760
798
  }`).join(`,
761
799
  `);return`/**
762
800
  * Generated Route Discovery Results
763
801
  * Source: ${o.source}
764
802
  * Generated at: ${new Date().toISOString()}
765
- * Import from '${z.routes}'
803
+ * Import from '${V.routes}'
766
804
  */
767
805
 
768
806
  export const discoveredRoutes = [
@@ -776,48 +814,10 @@ export const routeManifest = {
776
814
  };
777
815
 
778
816
  export default discoveredRoutes;
779
- `},generateManifest:o=>({routes:o?.routes?.length||0,source:o?.source||"unknown",timestamp:Date.now(),errors:o?.errors?.length||0}),logConfig:o=>{},logStats:(o,e,t)=>{let s=o.routes||[],r=s.filter(a=>a.auth&&a.auth.required).length,n=s.length;t&&t.info(`${e} Routes: ${n} found${r>0?`, ${r} are authguarded`:""}`)}},Do=[o=>o.endsWith("Page.tsx")];function Fs(o={}){return he({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:z.routes,DiscoveryClass:Qe,discoveryMethod:"discoverRoutes",filePatterns:Do,templates:ko,manifestFileName:de.manifests.route,configKey:"routes"})({...o,disableHmr:o?.hmr===!1,hmrSmartDetection:!1})}import{loadEnv as Mo}from"vite";G();function Ue(o){return o.replace(/\s+/g," ").trim()}function Is(o){let e=[`# ${Ue(o.name)}`,""];o.summary&&e.push(`> ${Ue(o.summary)}`,"");for(let t of o.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(`
780
- `)}G();var Ao="dndev",Oo="crud",No="entity-";function Ms(o,e,t){return e?o?.[e]?.[t]:void 0}function re(o){return typeof o=="string"&&o.trim()!==""?o.trim():void 0}function To(o,e,t){let s=o.metaExport||o.meta||{},r=s.seo||{},n=Ms(e,s.namespace,t),a=re(n?.title)??re(r.title)??re(n?.meta?.fullTitle)??re(r.fullTitle),i=r.description===null?void 0:re(r.description)??re(n?.description);return{...a&&{title:a},...i&&{description:i}}}function Ls(o){let{siteName:e,description:t,baseUrl:s,sitemapRoutes:r,routes:n,blogPosts:a=[],blogPath:i="/blog",translations:l,language:u}=o,c=Ms(l,Ao,u)?.seo,p=re(c?.llmsPages),g=re(c?.llmsBlog);if(!p||!g)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${u}".`);let f=new Map(n.map(b=>[b.path,b])),m=new Map(a.map(b=>[`${i}/${b.slug}`,b])),R=r.map(({path:b,collection:D})=>{let S=m.get(b);if(S)return{path:b,title:S.title,...re(S.description)&&{description:re(S.description)},section:g};if(D)return{path:b,collection:D};let k=v(b);if(b===i&&!k.title)return{path:b,...k,title:g};if(!k.title){let N=f.get(b),h=(N?.metaExport||N?.meta)?.namespace;throw new Error(`[dndev] llms.txt: page "${b}" has no title in "${u}". Add "title" to `+(h?`${h}_${u}.json`:"its translations")+" or `seo: { title }` to its PageMeta.")}return{path:b,...k}});function v(b){let D=f.get(b);return D?To(D,l,u):{}}let x={},P={};for(let[b,D]of Object.entries(l||{})){if(b===Oo&&D?.[u]&&(P[b]=D[u]),!b.startsWith(No))continue;D?.[u]&&(P[b]=D[u]);let S=re(D?.[u]?.namePlural);S&&(x[b]=S)}return{name:e,...re(t)&&{summary:re(t)},baseUrl:s,pagesHeading:p,routes:R,entityHeadings:x,language:u,translations:P}}function js(o){let e=new Map([[o.pagesHeading,[]]]);for(let t of o.routes){if(t.collection||t.path.includes(":"))continue;let s=t.section??o.pagesHeading;e.has(s)||e.set(s,[]),e.get(s).push({title:t.title,url:`${o.baseUrl}${t.path}`,...t.description&&{description:t.description}})}return Is({name:o.name,...o.summary&&{summary:o.summary},sections:[...e].map(([t,s])=>({heading:t,links:s}))})}function zs(o={}){let{siteName:e,baseUrl:t,blogPosts:s=[],blogPath:r="/blog",appRoot:n,logger:a}=o;if(!e||!t)return null;if(s.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=E.getInstance(),l=n?i.resolvePath("src/content/blog",n):null;if(!l||!i.pathExists(l))return null;let u=[`# ${e}
781
- `];o.description&&u.push(`> ${o.description}
782
- `);for(let c of s){let p=i.resolvePath(`${c.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}/${c.slug}`;u.push(`## ${c.title}
783
- `),u.push(`Source: ${m}
784
- `),c.date&&u.push(`Date: ${c.date}
785
- `),u.push(f.trim()),u.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${c.slug}`)}}return u.join(`
786
- `)}B();G();function J(o){return o?o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function Us(o){return o?o.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Co=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function Gs(o,e){let t;try{let s=new URL(o);if(s.protocol!=="https:"&&s.protocol!=="http:")throw new Error;t=s.hostname}catch{throw new Error(`[dndev] SEO: base URL "${o}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(Co.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: production build with base URL "${o}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}var Ws=new Set(["/404","/not-found","/500","/error"]);function wt(o){return o.auth&&o.auth!==!1||Ws.has(o.path)||Ws.has(o.meta?.route)?!1:o.meta?.seo?.noindex!==!0}function Fo(o){if(!(typeof o.path!="string"||!o.path.includes(":"))&&wt(o))return o.meta?.entity||void 0}var et=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:n,siteName:a,crawlDelay:i=1,aiCrawlers:l="recommended",routes:u={},...c}=e;if(!n||!a)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:n,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=T("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},n=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:n.length};return this.options.generateRobotsTxt&&(a.robotsTxt=await this.generateRobotsTxt(r,t)),this.options.generateSitemap&&(a.sitemap=await this.generateSitemap(r,t,n)),n.length>0&&(a.rss=await this.generateRSSFeed(n,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(n=>{if(n.auth&&n.auth.required){let a=n.path.startsWith("/")?n.path:`/${n.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 n=(e.routes||[]).filter(i=>!(!wt(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){n.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)n.push({url:`${this.options.blogPath}/${i.slug}`,lastmod:i.date,changefreq:"monthly",priority:"0.6",image:i.image||null})}let a=this.generateSitemapContent(n);return await t("sitemap.xml",a),{fileName:"sitemap.xml",content:a,publicRoutes:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:s}=this.options,r=[];for(let n of e||[]){if(!wt(n)||typeof n.path!="string")continue;let a=n.path===s||n.path.startsWith(`${s}/`);if(!(t.length>0&&a))if(n.path.includes(":")){if(a)continue;let i=Fo(n);r.push({path:n.path,...i&&{collection:i}})}else r.push({path:n.path})}if(t.length>0){r.push({path:s,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let n of t)r.push({path:`${s}/${n.slug}`,priority:.6,changeFrequency:"monthly",...n.date&&{lastModified:n.date}})}return r}async generateManifest(e,t){let s={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,protectedRoutes:e.routes?.filter(n=>n.auth&&n.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:n}=e,a=u=>u?u==="*"?"*":u.startsWith("/")?u:`/${u}`:"/",i=["User-agent: *",...s.map(u=>`Disallow: ${a(u)}`),...t.map(u=>`Allow: ${a(u)}`)];n&&i.push(`Crawl-delay: ${n}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Io(l))),i.join(`
787
- `)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:n,changefreq:a,priority:i,image:l})=>{let u=[` <loc>${J(this.options.baseUrl)}${J(r)}</loc>`];return n&&u.push(` <lastmod>${n}</lastmod>`),a&&u.push(` <changefreq>${a}</changefreq>`),i&&u.push(` <priority>${i}</priority>`),l&&u.push(` <image:image>
788
- <image:loc>${J(this.options.baseUrl)}${J(l)}</image:loc>
789
- </image:image>`),` <url>
790
- ${u.join(`
791
- `)}
792
- </url>`}).join(`
793
- `);return`<?xml version="1.0" encoding="UTF-8"?>
794
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
795
- xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
796
- ${s}
797
- </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 n=t.path.split("/").filter(Boolean);n.length>0&&(s=`${n[n.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 n=t.path.split("/").filter(Boolean);n.length>0&&(r=`Explore ${n[n.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=E.getInstance(),t=e.resolvePath("src/content/blog",this.appRoot);try{if(!e.pathExists(t))return[];let s=e.readdirSync(t).filter(n=>n.endsWith("_en.md"));if(s.length===0)return[];let r=[];for(let n of s){let a=e.resolvePath(n,t),i=e.readSync(a,{format:"text"}),l=n.replace(/_en\.md$/,""),u=i.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(u)for(let g of u[1].split(`
798
- `)){let f=g.indexOf(":");f!==-1&&(c[g.slice(0,f).trim()]=g.slice(f+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(g=>g.trim()):[],image:c.image||null})}return r.sort((n,a)=>a.date.localeCompare(n.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(n=>` <item>
799
- <title><![CDATA[${Us(n.title)}]]></title>
800
- <link>${J(this.options.baseUrl)}${J(this.options.blogPath)}/${J(n.slug)}</link>
801
- <guid>${J(this.options.baseUrl)}${J(this.options.blogPath)}/${J(n.slug)}</guid>
802
- <description><![CDATA[${Us(n.description)}]]></description>
803
- <pubDate>${n.date?new Date(n.date).toUTCString():""}</pubDate>${n.tags.length?`
804
- <category>${J(n.tags.join(", "))}</category>`:""}${n.image?`
805
- <enclosure url="${J(this.options.baseUrl)}${J(n.image)}" type="image/png" length="0"/>`:""}
806
- </item>`).join(`
807
- `),r=`<?xml version="1.0" encoding="UTF-8"?>
808
- <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
809
- <channel>
810
- <title>${J(this.options.siteName)}</title>
811
- <link>${J(this.options.baseUrl)}${J(this.options.blogPath)}</link>
812
- <description>${J(this.options.siteName)} Blog</description>
813
- <language>en</language>
814
- <atom:link href="${J(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
815
- ${s}
816
- </channel>
817
- </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(n=>!n.auth||n.auth===!1).length||0,r=e.routes?.filter(n=>n.auth&&n.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()}}},yt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],bt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Io(o){let e=["# AI Crawler Management"];if(o==="block-all"){for(let t of[...yt,...bt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(o==="allow-all"){for(let t of[...yt,...bt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of yt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of bt)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Bs(o={}){let{disabled:e=!1,debug:t,generateRobotsTxt:s,generateSitemap:r,routes:n={},baseUrl:a,siteName:i,siteDescription:l,crawlDelay:u,aiCrawlers:c,llmsTxt:p=!0,redirects:g,isDev:f,i18n:m={},...R}=o;if(e)return{name:"seo-disabled"};let v=T("SEO Plugin",t,!0),x=E.getInstance(),P=null,b=null,D=!1;return{name:"vite-seo-plugin",enforce:"pre",configResolved(S){let k=x.getAppRoot(),N=S.mode||"production",F=Mo(N,k,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;F&&t&&v.debug(`Using app URL from VITE_APP_URL: ${F}`),P=i||null;let C=a||F||null;b=C?C.trim().replace(/\/+$/,""):null,v.verbose(`Name: ${P||"Not found"}`),v.verbose(`URL: ${b||"Not found"}
818
- `),P&&v.debug(` - Site name from appConfig: "${P}"`);let d=[];if(b||d.push("baseUrl (VITE_APP_URL in .env)"),P||d.push("siteName (APP_NAME in src/config/app.ts)"),d.length>0){D=!0,v.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),d.forEach(L=>v.warn(` - ${L}`)),v.warn(""),v.warn(" To fix:"),b||v.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),P||(v.warn(" 2. Add APP_NAME export to src/config/app.ts:"),v.warn(' export const APP_NAME = "Your App Name";')),v.warn(""),v.warn(" robots.txt and sitemap.xml will NOT be generated."),v.warn("");return}v.debug(`Generate robots.txt: ${s}`),v.debug(`Generate sitemap: ${r}`)},async generateBundle(){if(!D){f||Gs(b,"VITE_APP_URL");try{let S=new et({debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:b,siteName:P,crawlDelay:u,aiCrawlers:c,routes:n,appRoot:x.getAppRoot(),...R}),k=Te({appRoot:x.getAppRoot(),logger:v}),N=async(F,C)=>{this.emitFile({type:"asset",fileName:F,source:C})},h=await S.generateSEOFiles(k,N);if(h.robotsTxt&&!h.robotsTxt.skipped&&v.info(`\u{1F916} robots.txt: ${h.robotsTxt.disallowedPaths||0} disallowed paths`),h.sitemap&&!h.sitemap.skipped&&v.info(`\u{1F5FA}\uFE0F sitemap.xml: ${h.sitemap.publicRoutes||0} routes`),h.rss&&!h.rss.skipped&&v.info(`\u{1F4E1} rss.xml: ${h.rss.postCount||0} blog posts`),h.manifest&&!h.manifest.skipped&&v.info("\u{1F4C4} seo-manifest.json"),p){let F=x.getAppRoot(),C=S.discoverBlogPosts(),d=await ht(m).discoverTranslations(),L=Ls({siteName:P,description:l,baseUrl:b,sitemapRoutes:S.getSitemapRoutes(k.routes||[],C),routes:k.routes||[],blogPosts:C,blogPath:S.options.blogPath,translations:d.content,language:d.fallbackLanguage});if(await N("llms.txt",js(L)),v.info("\u{1F4C4} llms.txt"),C.length>0){let j=zs({siteName:P,baseUrl:b,description:l,appRoot:F,blogPosts:C,logger:v});j&&(await N("llms-full.txt",j),v.info("\u{1F4C4} llms-full.txt"))}}if(g?.length>0){let F=new Set,C=[];for(let{from:d,to:L,permanent:j}of g){let I=d.replace(/\/+$/,"")||"/",V=L.replace(/\/+$/,"")||"/";if(I===V){v.warn(`Redirect loop detected: ${d} \u2192 ${L} (skipped)`);continue}if(!d.startsWith("/")){v.warn(`Redirect source must start with /: "${d}" (skipped)`);continue}if(F.has(I)){v.warn(`Duplicate redirect source: "${d}" (skipped)`);continue}F.add(I),C.push(`${d} ${L} ${j===!1?302:301}`)}C.length>0&&(await N("_redirects",C.join(`
817
+ `},generateManifest:o=>({routes:o?.routes?.length||0,source:o?.source||"unknown",timestamp:Date.now(),errors:o?.errors?.length||0}),logConfig:o=>{},logStats:(o,e,t)=>{let n=o.routes||[],r=n.filter(a=>a.auth&&a.auth.required).length,s=n.length;t&&t.info(`${e} Routes: ${s} found${r>0?`, ${r} are authguarded`:""}`)}},Vi=[o=>o.endsWith("Page.tsx")];function Fr(o={}){return we({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:V.routes,DiscoveryClass:Rt,discoveryMethod:"discoverRoutes",filePatterns:Vi,templates:Hi,manifestFileName:ve.manifests.route,configKey:"routes"})({...o,disableHmr:o?.hmr===!1,hmrSmartDetection:!1})}q();import{loadEnv as Ji}from"vite";Y();var qi=`/${rt.replace(/\.html$/,"")}`;function Mr(o={}){let{disabled:e=!1,debug:t,generateRobotsTxt:n,generateSitemap:r,routes:s={},baseUrl:a,siteName:i,siteDescription:l,crawlDelay:c,aiCrawlers:u,llmsTxt:p=!0,redirects:d,isDev:f,routeManifest:g,...v}=o;if(e)return{name:"seo-disabled"};if(!g)throw new Error("[dndev] createViteSEOPlugin: options.routeManifest is required (createVitePlugins passes the route plugin's, createRouteManifestStore).");let h=G("SEO Plugin",t,!0),y=O.getInstance(),C=null,$=null,S=!1;return{name:"vite-seo-plugin",enforce:"pre",applyToEnvironment(x){return x.name==="client"},configResolved(x){let N=y.getAppRoot(),D=x.mode||"production",k=Ji(D,N,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;k&&t&&h.debug(`Using app URL from VITE_APP_URL: ${k}`),C=i||null;let _=bt(a,k)||null;if($=f?_:Qe(_,"VITE_APP_URL",h),!f&&!$){S=!0;return}h.verbose(`Name: ${C||"Not found"}`),h.verbose(`URL: ${$||"Not found"}
818
+ `),C&&h.debug(` - Site name from appConfig: "${C}"`);let m=[];if($||m.push("baseUrl (VITE_APP_URL in .env)"),C||m.push("siteName (APP_NAME in src/config/app.ts)"),m.length>0){S=!0,h.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),m.forEach(A=>h.warn(` - ${A}`)),h.warn(""),h.warn(" To fix:"),$||h.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),C||(h.warn(" 2. Add APP_NAME export to src/config/app.ts:"),h.warn(' export const APP_NAME = "Your App Name";')),h.warn(""),h.warn(" robots.txt and sitemap.xml will NOT be generated."),h.warn("");return}h.debug(`Generate robots.txt: ${n}`),h.debug(`Generate sitemap: ${r}`)},async generateBundle(){if(S)return;let x=new We({debug:t,generateRobotsTxt:n,shellPath:qi,baseUrl:$,siteName:C,crawlDelay:c,aiCrawlers:u,routes:s,appRoot:y.getAppRoot(),...v}),N=g.get(),{blogPosts:D}=N,P=async(k,_)=>{this.emitFile({type:"asset",fileName:k,source:_})};await wt(["robots.txt","rss.xml","seo-manifest.json"],async()=>{let k=await x.generateSEOFiles(N,P,D);k.robotsTxt&&!k.robotsTxt.skipped&&h.info(`\u{1F916} robots.txt: ${k.robotsTxt.disallowedPaths||0} disallowed paths`),k.rss&&!k.rss.skipped&&h.info(`\u{1F4E1} rss.xml: ${k.rss.postCount||0} blog posts`),k.manifest&&!k.manifest.skipped&&h.info("\u{1F4C4} seo-manifest.json")},h),p&&D.length>0&&await wt(["llms-full.txt"],async()=>{let k=or({siteName:C,baseUrl:$,description:l,appRoot:y.getAppRoot(),blogPosts:D,logger:h});k&&(await P("llms-full.txt",k),h.info("\u{1F4C4} llms-full.txt"))},h),d?.length>0&&await wt(["_redirects"],async()=>{let k=new Set,_=[];for(let{from:m,to:A,permanent:B}of d){let w=m.replace(/\/+$/,"")||"/",M=A.replace(/\/+$/,"")||"/";if(w===M){h.warn(`Redirect loop detected: ${m} \u2192 ${A} (skipped)`);continue}if(!m.startsWith("/")){h.warn(`Redirect source must start with /: "${m}" (skipped)`);continue}if(k.has(w)){h.warn(`Duplicate redirect source: "${m}" (skipped)`);continue}k.add(w),_.push(`${m} ${A} ${B===!1?302:301}`)}_.length>0&&(await P("_redirects",_.join(`
819
819
  `)+`
820
- `),v.info(`\u{1F4CE} _redirects: ${C.length} redirect${C.length>1?"s":""}`))}}catch(S){v.error(`SEO plugin failed to generate files (robots.txt/sitemap.xml): ${S.message}`),v.error(`Stack: ${S.stack||"No stack trace available"}`)}}}}}B();function Vs(o={}){let{debug:e}=o;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,s){return t.startsWith("node:")?(T("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):at.includes(t)||at.some(r=>t.startsWith(`${r}/`))?(T("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):Nt.includes(t)?(T("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"?`
820
+ `),h.info(`\u{1F4CE} _redirects: ${_.length} redirect${_.length>1?"s":""}`))},h)}}}q();function Lr(o={}){let{debug:e}=o;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,n){return t.startsWith("node:")?(G("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${n?` from ${n}`:""}`),"\0virtual:empty-server-module"):Dt.includes(t)||Dt.some(r=>t.startsWith(`${r}/`))?(G("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${n?` from ${n}`:""}`),"\0virtual:empty-server-module"):hn.includes(t)?(G("server-shim",e,!0).warn(`Blocking server-only import: ${t}${n?` from ${n}`:""}`),"\0virtual:empty-server-module"):null},load(t){return t==="\0virtual:empty-server-module"?`
821
821
  // Node.js built-in modules shims for browser compatibility
822
822
  export const URL = globalThis.URL;
823
823
  export const URLSearchParams = globalThis.URLSearchParams;
@@ -1096,15 +1096,15 @@ ${s}
1096
1096
  // Google Logging Utils shims
1097
1097
  export const LoggingWinston = class LoggingWinston {};
1098
1098
  export const LoggingBunyan = class LoggingBunyan {};
1099
- `:null}}}B();import{createRequire as Lo}from"node:module";var jo=Lo(import.meta.url),Js="ThemeIcon_",Hs;function zo(){return Hs??=new Set(Object.keys(jo("lucide-react"))),Hs}function xt(o,e){let t=zo(),s=new Set;for(let r of o){let n=r.meta?.icon;if(!n)continue;let a=String(n).replace(/['"]/g,"").trim();/^[A-Za-z][A-Za-z0-9]*$/.test(a)&&t.has(a)?s.add(a):e.warn(`\u{1F3A8} Theme "${r.name}": --theme-icon '${a}' is not a lucide-react icon name (theme toggle shows the Palette icon)`)}return[...s].sort()}function St(o){return o.length===0?"":`import { ${o.map(t=>`${t} as ${Js}${t}`).join(", ")} } from 'lucide-react';
1100
- `}function Rt(o){return`{ ${o.map(t=>`${JSON.stringify(t)}: ${Js}${t}`).join(", ")} }`}var qs=T("theme-plugin"),Ys={isEmpty:o=>!o.themes||o.themes.length===0,generateModule:(o,e,t="themes")=>{let{themes:s}=o;if(!s||s.length===0)return Ys.generateEmpty(o,e,void 0,t);let r=s.find(i=>i.essential&&i.name==="light")||s[0],n={totalThemes:s.length,defaultTheme:r?.name||"light",hasCustomThemes:s.some(i=>!i.essential),timestamp:new Date().toISOString()},a=xt(s,qs);return`// Virtual module: ${z.themes}
1099
+ `:null}}}q();import{createRequire as Ki}from"node:module";var Yi=Ki(import.meta.url),zr="ThemeIcon_",jr;function Zi(){return jr??=new Set(Object.keys(Yi("lucide-react"))),jr}function rn(o,e){let t=Zi(),n=new Set;for(let r of o){let s=r.meta?.icon;if(!s)continue;let a=String(s).replace(/['"]/g,"").trim();/^[A-Za-z][A-Za-z0-9]*$/.test(a)&&t.has(a)?n.add(a):e.warn(`\u{1F3A8} Theme "${r.name}": --theme-icon '${a}' is not a lucide-react icon name (theme toggle shows the Palette icon)`)}return[...n].sort()}function sn(o){return o.length===0?"":`import { ${o.map(t=>`${t} as ${zr}${t}`).join(", ")} } from 'lucide-react';
1100
+ `}function an(o){return`{ ${o.map(t=>`${JSON.stringify(t)}: ${zr}${t}`).join(", ")} }`}var Br=G("theme-plugin"),Ur={isEmpty:o=>!o.themes||o.themes.length===0,generateModule:(o,e,t="themes")=>{let{themes:n}=o;if(!n||n.length===0)return Ur.generateEmpty(o,e,void 0,t);let r=n.find(i=>i.essential&&i.name==="light")||n[0],s={totalThemes:n.length,defaultTheme:r?.name||"light",hasCustomThemes:n.some(i=>!i.essential),timestamp:new Date().toISOString()},a=rn(n,Br);return`// Virtual module: ${V.themes}
1101
1101
  // \u{1F680} STATIC INJECTION PATTERN - Zero Runtime Loading
1102
1102
  // Generated by @donotdev/config at ${new Date().toISOString()}
1103
- ${St(a)}
1103
+ ${sn(a)}
1104
1104
  // ===== STATIC EXPORTS - IMMEDIATE AVAILABILITY =====
1105
- export const THEMES = ${JSON.stringify(s,null,2)};
1106
- export const THEME_MANIFEST = ${JSON.stringify(n,null,2)};
1107
- export const THEME_COUNT = ${s.length};
1105
+ export const THEMES = ${JSON.stringify(n,null,2)};
1106
+ export const THEME_MANIFEST = ${JSON.stringify(s,null,2)};
1107
+ export const THEME_COUNT = ${n.length};
1108
1108
  export const DEFAULT_THEME = '${r?.name||"light"}';
1109
1109
 
1110
1110
  const themeData = THEMES;
@@ -1125,17 +1125,17 @@ if (typeof globalThis !== 'undefined') {
1125
1125
  }
1126
1126
 
1127
1127
  // Populate themes configuration
1128
- globalThis._DNDEV_CONFIG_.${K[t]} = {
1128
+ globalThis._DNDEV_CONFIG_.${oe[t]} = {
1129
1129
  discovered: themeData,
1130
1130
  mapping: themeData.reduce((acc, theme) => {
1131
1131
  acc[theme.name] = theme;
1132
1132
  return acc;
1133
1133
  }, {}),
1134
1134
  // Theme icons (--theme-icon), imported by name: rendered without the lucide namespace
1135
- icons: ${Rt(a)},
1135
+ icons: ${an(a)},
1136
1136
  variables: {},
1137
1137
  manifest: {
1138
- totalThemes: ${s.length},
1138
+ totalThemes: ${n.length},
1139
1139
  totalVariables: 0,
1140
1140
  generatedAt: new Date().toISOString(),
1141
1141
  },
@@ -1174,13 +1174,13 @@ export default {
1174
1174
  getAllThemes,
1175
1175
  getThemeNames
1176
1176
  };
1177
- `},generateEmpty:(o,e,t,s="themes")=>{let r=o.themes&&o.themes.length>0?o.themes:[{name:"light",displayName:"Light",meta:{icon:"Sun",category:"light"},essential:!0,isDark:!1,source:"built-in",variableCount:0}],n=r.find(l=>l.essential&&l.name==="light")||r[0],a={totalThemes:r.length,defaultTheme:n?.name||"light",hasCustomThemes:r.some(l=>!l.essential),timestamp:new Date().toISOString()},i=xt(r,qs);return`// ${z.themes} - Using framework essential themes (fallback)
1177
+ `},generateEmpty:(o,e,t,n="themes")=>{let r=o.themes&&o.themes.length>0?o.themes:[{name:"light",displayName:"Light",meta:{icon:"Sun",category:"light"},essential:!0,isDark:!1,source:"built-in",variableCount:0}],s=r.find(l=>l.essential&&l.name==="light")||r[0],a={totalThemes:r.length,defaultTheme:s?.name||"light",hasCustomThemes:r.some(l=>!l.essential),timestamp:new Date().toISOString()},i=rn(r,Br);return`// ${V.themes} - Using framework essential themes (fallback)
1178
1178
  // Generated by @donotdev/config at ${new Date().toISOString()}
1179
- ${St(i)}
1179
+ ${sn(i)}
1180
1180
  export const THEMES = ${JSON.stringify(r,null,2)};
1181
1181
  export const THEME_MANIFEST = ${JSON.stringify(a,null,2)};
1182
1182
  export const THEME_COUNT = ${r.length};
1183
- export const DEFAULT_THEME = '${n?.name||"light"}';
1183
+ export const DEFAULT_THEME = '${s?.name||"light"}';
1184
1184
 
1185
1185
  const themeData = THEMES;
1186
1186
  const defaultTheme = DEFAULT_THEME;
@@ -1198,13 +1198,13 @@ if (typeof globalThis !== 'undefined') {
1198
1198
  };
1199
1199
  }
1200
1200
 
1201
- globalThis._DNDEV_CONFIG_.${K[s]} = {
1201
+ globalThis._DNDEV_CONFIG_.${oe[n]} = {
1202
1202
  discovered: themeData,
1203
1203
  mapping: themeData.reduce((acc, theme) => {
1204
1204
  acc[theme.name] = theme;
1205
1205
  return acc;
1206
1206
  }, {}),
1207
- icons: ${Rt(i)},
1207
+ icons: ${an(i)},
1208
1208
  variables: {},
1209
1209
  manifest: {
1210
1210
  totalThemes: ${r.length},
@@ -1258,15 +1258,15 @@ export const themeManifest = {
1258
1258
  };
1259
1259
 
1260
1260
  export default discoveredThemes;
1261
- `;let s=t.find(r=>r.essential&&r.name==="light")||t[0];return`/**
1261
+ `;let n=t.find(r=>r.essential&&r.name==="light")||t[0];return`/**
1262
1262
  * Generated Theme Discovery Results
1263
1263
  * Generated at: ${new Date().toISOString()}
1264
- * Import from '${z.themes}'
1264
+ * Import from '${V.themes}'
1265
1265
  */
1266
1266
 
1267
1267
  export const discoveredThemes = ${JSON.stringify(t,null,2)};
1268
1268
 
1269
- export const defaultTheme = '${s?.name||"light"}';
1269
+ export const defaultTheme = '${n?.name||"light"}';
1270
1270
 
1271
1271
  export const themeFiles = ${JSON.stringify(o.files?.map(r=>({name:r.name,path:r.relativePath,size:r.size}))||[],null,2)};
1272
1272
 
@@ -1276,9 +1276,9 @@ export const themeManifest = {
1276
1276
  };
1277
1277
 
1278
1278
  export default discoveredThemes;
1279
- `},generateManifest:o=>({themes:o.themes?.length||0,timestamp:Date.now(),hasCustomThemes:o.themes?.some(e=>!e.essential)||!1}),logConfig:o=>{},logStats:(o,e,t)=>{let s=o.themes||[],r=s.filter(a=>!a.essential).length,n=s.length;t&&(n===0?t.warn(`${e} No themes discovered - using framework essential themes fallback`):t.info(`${e} Themes: ${n} discovered${r>0?` (${r} custom)`:""}`))}};function Ks(o={}){let e=Date.now();return T("theme-plugin",o.debug,o.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),he({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:z.themes,DiscoveryClass:$e,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:Ys,manifestFileName:de.manifests.theme,configKey:"themes",createDiscovery:(r,n)=>{let a=new Fe(r,{debug:n.debug,logger:T("css-extractor",n.debug,n.verbose)});return new $e(a,r,n)}})(o)}B();G();var tt=new Set(["@donotdev/functions"]);function Zs(){try{let o=E.getInstance(),e=o.resolveAppPath("package.json"),t=o.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=>!tt.has(r)).sort()}catch{return[]}}G();function Xs(o={}){let e=T("vite-plugins",o.debug,o.verbose);try{let{mode:t,debug:s,verbose:r,isDev:n,isPreview:a=!1,server:i={},routes:l={},themes:u={},i18n:c={},assets:p={},seo:g={},prerender:f={},pwa:m={},serverShim:R={},pluginFactory:v={},reactCompiler:x=!1,appConfig:P}=o,b=l.debug??s,D=u.debug??s,S=c.debug??s,k=p.debug??s,N=R.debug??s,h=[];h.push(Vs({...R,debug:N}));let F;try{F=E.getInstance()}catch(d){throw new Error(`Failed to initialize PathResolver: ${d.message||d}`)}h.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(d){if(s){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let I={root:d.root,mode:d.mode,envDir:d.envDir,base:d.base,build:d.build?{outDir:d.build.outDir,minify:d.build.minify}:void 0,server:d.server?{port:d.server.port,host:d.server.host}:void 0,plugins:d.plugins?{count:d.plugins.length,names:d.plugins.map(V=>V?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(I,null,2))}F.setAppRoot(d.root);let L=F.getAppRoot(),j=Zs();if(j.length>0){let I=d.optimizeDeps?.include||[];d.optimizeDeps.include=[...new Set([...I,...j])],e.verbose(`optimizeDeps: added ${j.length} @donotdev packages`)}if(tt.size>0){let I=d.optimizeDeps?.exclude||[],V=[...tt];d.optimizeDeps.exclude=[...new Set([...I,...V])],e.verbose(`optimizeDeps: excluded ${V.length} server-only packages`)}if(n&&d.server?.port){let I=d.server.https?"https":"http";process.env.VITE_APP_URL=`${I}://localhost:${d.server.port}`,(s||r)&&e.debug(`VITE_APP_URL set: ${process.env.VITE_APP_URL}`)}else n&&e.warn("VITE_APP_URL not set in dev mode. Server port not available.");try{let I=F.getRepoRoot();e.verbose(`Repo: ${I}`),e.verbose(`App: ${L}`)}catch(I){e.debug(`Could not log PathResolver values: ${I.message}`)}if(d.server&&!a){let I=te=>{let Y=te.replace(/\\/g,"/"),ue=L.replace(/\\/g,"/");return!Y.startsWith(ue)};d.server.watch||(d.server.watch={});let V=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];d.server.watch={...d.server.watch,ignored:[...d.server.watch.ignored||[],...V,I]},e.verbose(`Fixed file watcher to use app root: ${L}`)}}}),h.push(Ss({appConfig:P,pwa:m.enabled,debug:s,verbose:r})),h.push(Ds({debug:s,verbose:r})),h.push(_s({debug:s})),h.push(Wo({fastRefresh:!0,jsxRuntime:"automatic",...x?{babel:{plugins:[["babel-plugin-react-compiler",{target:"19"}]]}}:{}})),h.push(Go({ignoreConfigErrors:!0})),i.https===!0&&h.push(Uo()),h.push(Fs({...v,...l,debug:b})),h.push(Ks({...v,...u,debug:D})),h.push(...Es({...v,...c,debug:S})),h.push(Zt({...v,...p,debug:k})),h.push(ss({...v,mode:t,debug:s,verbose:r})),h.push(Bs({...g,debug:s,isDev:n,i18n:{...v,...c,debug:S}})),m.enabled&&h.push(Os({...m,debug:s})),h.push(cs({debug:s,i18nOptions:c})),h.push(es());let C=!1;return h.push({name:"dndev-build-summary",enforce:"post",configResolved(d){C=d.command==="build"},closeBundle(){if(!C)return;let d=F,L=d.resolveAppPath("dist/assets");if(d.pathExists(L))try{let j=d.readdirSync(L),I=j.filter(Y=>Y.endsWith(".js")),V=j.filter(Y=>Y.endsWith(".css")),te=j.length-I.length-V.length;e.info(`
1280
- Build output: ${I.length} JS, ${V.length} CSS, ${te} other \u2014 ${j.length} files total`)}catch{}}}),h.push(As({...f,debug:s,verbose:r})),h}catch(t){throw T("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}B();function Bo(o){if(!o)return{};let e={};return Array.isArray(o)?o.forEach(({find:t,replacement:s})=>{typeof t=="string"&&(e[t]=s)}):typeof o=="object"&&Object.assign(e,o),e}function Qs(o={}){let{alias:e,...t}=o,{conditions:s,...r}=t;return{alias:{"@":"/src",...Bo(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...s||[]],...r}}function er(o={}){let{include:e=[],exclude:t=[],esbuildOptions:s={},...r}=o,n=[...e,...ye.optionalFeatures],a=[...new Set(n)],i=[...new Set(t)];return{include:a,exclude:i,esbuildOptions:s,...r}}function xn(o={}){return o==null&&(o={}),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,n=e.isPreview??!1,{appConfig:a,dndev:i,...l}=o;if(!a)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
1281
- 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:g,...f}=l,m=a?.app?{name:a.app.name,shortName:a.app.shortName,description:a.app.description}:void 0,{pwa:R={},...v}=f,x={...R,app:R.app||m},P={...u?{features:u}:{},...c?{seo:c}:{},...Object.keys(x).length>0?{pwa:x}:{},...v,mode:r},b;try{b=Vt(P)}catch(Q){throw new Error(`mergeOptions failed: ${Q?.message||Q||"Unknown error"}`)}let D;try{D=Ht(b)}catch(Q){throw new Error(`normalizeOptions failed: ${Q?.message||Q||"Unknown error"}`)}if(!D)throw new Error("normalizeOptions returned undefined");let{mode:S,debug:k,verbose:N,isDev:h,isDebug:F,shouldAnalyze:C,serverOptions:d,previewOptions:L,buildOverrides:j,resolveOptions:I,routeOptions:V,themeOptions:te,i18nOptions:Y,assetOptions:ue,featureOptions:W,seoOptions:Re,prerenderOptions:$,pwaOptions:A,serverShimOptions:M,chunkingOptions:U,pluginFactoryOptions:pe,reactCompiler:_e,base:w,defineOptions:_,optimizeDepsOptions:q,pluginsOptions:ge,cssOptions:X,envDir:ke,restOptions:cr}=D,We=T("vite-config",k,N);We.debug(`Mode: ${S}, Dev: ${h}`);let $t=process.env.DNDEV_BUILD_ID,Me;s==="build"?Me=`Building for ${S}`:n?Me=`Preview server (serving ${S} build)`:s==="serve"?Me=`Development server (${S})`:Me=`Running ${s} (${S})`,We.info(`
1282
- \u{1F3D7}\uFE0F DnDev Framework - ${Me}${$t?` [build:${$t}]`:""}`),We.info(` Platform: Vite | Command: ${s} | Mode: ${S}
1283
- `);let Ge=Xs({appConfig:a,mode:S,debug:k,verbose:N,isDev:h,isPreview:n,routes:V,themes:te,i18n:Y,assets:ue,features:W,seo:Re,prerender:$,pwa:A,serverShim:M,chunkingOptions:U,pluginFactory:pe,reactCompiler:_e});if(!Array.isArray(Ge))throw new Error(`createVitePlugins returned ${typeof Ge}, expected array. Value: ${Ge}`);let ur=zt({mode:S,chunkingOptions:U,debug:k,isDev:h,isDebug:F,shouldAnalyze:C}),pr=n?void 0:Ut(d.port||3e3,d,We),fr=n?Wt(L):void 0;if(i)try{let{createDndevPlugin:Q}=await Promise.resolve().then(()=>(lr(),ir));ge.push(Q(typeof i=="object"?i:{}))}catch{}return{...w&&{base:w},plugins:[...Ge,...ge],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...S==="production"&&{build:ur},...s==="serve"&&!n&&{server:pr},...n&&{preview:fr},...ke&&{envDir:ke},customLogger:S==="production"&&!k?(()=>{let Q={hasWarned:!1,_shouldSuppress(ne){return ne.includes("dist/")||ne.includes("kB")||ne.includes("\u2502")||ne.includes("gzip:")||ne.includes("\u2713 built in")||ne.match(/built in \d+\.\d+s/)},info(ne){Q._shouldSuppress(ne)},warn(ne){Q._shouldSuppress(ne)},error(ne){},warnOnce(ne){Q.hasWarned||(Q.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return Q})():void 0,css:{postcss:qt(X),...X},optimizeDeps:er(q),resolve:Qs(I),define:{..._,"process.env.NODE_ENV":JSON.stringify(r),__DEV__:JSON.stringify(h),__PROD__:JSON.stringify(!h)},...cr}}catch(t){let s=t||new Error("Unknown error occurred"),r=s?.message||s?.toString()||String(s)||"Unknown error",n=s?.stack||"",a=new Error(`Failed to create Vite config: ${r}${n?`
1284
- ${n}`:""}`);throw a.stack=n||a.stack,a}}}export{xn as defineViteConfig};
1279
+ `},generateManifest:o=>({themes:o.themes?.length||0,timestamp:Date.now(),hasCustomThemes:o.themes?.some(e=>!e.essential)||!1}),logConfig:o=>{},logStats:(o,e,t)=>{let n=o.themes||[],r=n.filter(a=>!a.essential).length,s=n.length;t&&(s===0?t.warn(`${e} No themes discovered - using framework essential themes fallback`):t.info(`${e} Themes: ${s} discovered${r>0?` (${r} custom)`:""}`))}};function Wr(o={}){let e=Date.now();return G("theme-plugin",o.debug,o.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),we({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:V.themes,DiscoveryClass:Oe,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:Ur,manifestFileName:ve.manifests.theme,configKey:"themes",createDiscovery:(r,s)=>{let a=new Be(r,{debug:s.debug,logger:G("css-extractor",s.debug,s.verbose)});return new Oe(a,r,s)}})(o)}q();Y();var Ct=new Set(["@donotdev/functions"]);function Gr(){try{let o=O.getInstance(),e=o.resolveAppPath("package.json"),t=o.readSync(e,{format:"json"});if(!t)return[];let n={...t.dependencies,...t.devDependencies};return Object.keys(n).filter(r=>r.startsWith("@donotdev/")).filter(r=>!Pe.buildTimePackages.includes(r)).filter(r=>!Ct.has(r)).sort()}catch{return[]}}Y();function Hr(o={}){let e=G("vite-plugins",o.debug,o.verbose);try{let{mode:t,debug:n,verbose:r,isDev:s,isPreview:a=!1,server:i={},routes:l={},themes:c={},i18n:u={},assets:p={},seo:d={},prerender:f={},pwa:g={},serverShim:v={},pluginFactory:h={},reactCompiler:y=!1,appConfig:C}=o,$=l.debug??n,S=c.debug??n,x=u.debug??n,N=p.debug??n,D=v.debug??n,P=[];P.push(Lr({...v,debug:D}));let k;try{k=O.getInstance()}catch(w){throw new Error(`Failed to initialize PathResolver: ${w.message||w}`)}P.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(w){if(n){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let z={root:w.root,mode:w.mode,envDir:w.envDir,base:w.base,build:w.build?{outDir:w.build.outDir,minify:w.build.minify}:void 0,server:w.server?{port:w.server.port,host:w.server.host}:void 0,plugins:w.plugins?{count:w.plugins.length,names:w.plugins.map(K=>K?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(z,null,2))}k.setAppRoot(w.root);let M=k.getAppRoot(),L=Gr();if(L.length>0){let z=w.optimizeDeps?.include||[];w.optimizeDeps.include=[...new Set([...z,...L])],e.verbose(`optimizeDeps: added ${L.length} @donotdev packages`)}if(Ct.size>0){let z=w.optimizeDeps?.exclude||[],K=[...Ct];w.optimizeDeps.exclude=[...new Set([...z,...K])],e.verbose(`optimizeDeps: excluded ${K.length} server-only packages`)}if(s&&w.server?.port){let z=w.server.https?"https":"http";process.env.VITE_APP_URL=`${z}://localhost:${w.server.port}`,(n||r)&&e.debug(`VITE_APP_URL set: ${process.env.VITE_APP_URL}`)}else s&&e.warn("VITE_APP_URL not set in dev mode. Server port not available.");try{let z=k.getRepoRoot();e.verbose(`Repo: ${z}`),e.verbose(`App: ${M}`)}catch(z){e.debug(`Could not log PathResolver values: ${z.message}`)}if(w.server&&!a){let z=U=>{let Z=U.replace(/\\/g,"/"),R=M.replace(/\\/g,"/");return!Z.startsWith(R)};w.server.watch||(w.server.watch={});let K=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];w.server.watch={...w.server.watch,ignored:[...w.server.watch.ignored||[],...K,z]},e.verbose(`Fixed file watcher to use app root: ${M}`)}}}),P.push(Lo({appConfig:C,pwa:g.enabled,debug:n,verbose:r})),P.push(Ho({debug:n,verbose:r})),P.push(Wo({debug:n})),P.push(Qi({fastRefresh:!0,jsxRuntime:"automatic",...y?{babel:{plugins:[["babel-plugin-react-compiler",{target:"19"}]]}}:{}})),P.push(el({ignoreConfigErrors:!0})),i.https===!0&&P.push(Xi());let _=Mn(),m=zo(),A=$o();P.push(Fr({...h,...l,debug:$,routeManifest:_})),P.push(Wr({...h,...c,debug:S})),P.push(...Bo({...h,...u,debug:x,i18nStore:m})),P.push(Bn({...h,...p,debug:N,i18nStore:m,routeManifest:_})),P.push(Xn({appConfig:C})),P.push(Vn({...h,mode:t,debug:n,verbose:r})),P.push(Mr({...d,routeManifest:_,debug:n,isDev:s})),g.enabled&&P.push(Er({...g,debug:n})),P.push(Po({appConfig:C,debug:n,i18nStore:m,fontPlan:A})),P.push(Gn());let B=!1;return P.push({name:"dndev-build-summary",enforce:"post",configResolved(w){B=w.command==="build"},closeBundle(){if(!B)return;let w=k,M=w.resolveAppPath("dist/assets");if(w.pathExists(M))try{let L=w.readdirSync(M),z=L.filter(Z=>Z.endsWith(".js")),K=L.filter(Z=>Z.endsWith(".css")),U=L.length-z.length-K.length;e.info(`
1280
+ Build output: ${z.length} JS, ${K.length} CSS, ${U} other \u2014 ${L.length} files total`)}catch{}}}),P.push(wr({...f,routeManifest:_,prerenderRecords:C?.prerenderRecords,seo:d,i18nStore:m,fontPlan:A,debug:n,verbose:r})),P}catch(t){throw G("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}q();function tl(o){if(!o)return{};let e={};return Array.isArray(o)?o.forEach(({find:t,replacement:n})=>{typeof t=="string"&&(e[t]=n)}):typeof o=="object"&&Object.assign(e,o),e}function Vr(o={}){let{alias:e,...t}=o,{conditions:n,...r}=t;return{alias:{"@":"/src",...tl(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...n||[]],...r}}function Jr(o={}){let{include:e=[],exclude:t=[],esbuildOptions:n={},...r}=o,s=[...e,...Pe.optionalFeatures],a=[...new Set(s)],i=[...new Set(t)];return{include:a,exclude:i,esbuildOptions:n,...r}}function kl(o={}){return o==null&&(o={}),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 n=e.command,r=e.mode,s=e.isPreview??!1,{appConfig:a,dndev:i,...l}=o;if(!a)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
1281
+ 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===!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:d,...f}=l,g=a?.app?{name:a.app.name,shortName:a.app.shortName,description:a.app.description}:void 0,{pwa:v={},...h}=f,y={...v,app:v.app||g},C={...c?{features:c}:{},...u?{seo:u}:{},...Object.keys(y).length>0?{pwa:y}:{},...h,mode:r},$;try{$=An(C)}catch(se){throw new Error(`mergeOptions failed: ${se?.message||se||"Unknown error"}`)}let S;try{S=Nn($)}catch(se){throw new Error(`normalizeOptions failed: ${se?.message||se||"Unknown error"}`)}if(!S)throw new Error("normalizeOptions returned undefined");let{mode:x,debug:N,verbose:D,isDev:P,isDebug:k,shouldAnalyze:_,serverOptions:m,previewOptions:A,buildOverrides:B,resolveOptions:w,routeOptions:M,themeOptions:L,i18nOptions:z,assetOptions:K,featureOptions:U,seoOptions:Z,prerenderOptions:R,pwaOptions:I,serverShimOptions:F,chunkingOptions:W,pluginFactoryOptions:Q,reactCompiler:X,base:te,defineOptions:xe,optimizeDepsOptions:E,pluginsOptions:T,cssOptions:J,envDir:he,restOptions:ne}=S,nt=G("vite-config",N,D);nt.debug(`Mode: ${x}, Dev: ${P}`);let un=process.env.DNDEV_BUILD_ID,Je;n==="build"?Je=`Building for ${x}`:s?Je=`Preview server (serving ${x} build)`:n==="serve"?Je=`Development server (${x})`:Je=`Running ${n} (${x})`,nt.info(`
1282
+ \u{1F3D7}\uFE0F DnDev Framework - ${Je}${un?` [build:${un}]`:""}`),nt.info(` Platform: Vite | Command: ${n} | Mode: ${x}
1283
+ `);let ot=Hr({appConfig:a,mode:x,debug:N,verbose:D,isDev:P,isPreview:s,routes:M,themes:L,i18n:z,assets:K,features:U,seo:Z,prerender:R,pwa:I,serverShim:F,chunkingOptions:W,pluginFactory:Q,reactCompiler:X});if(!Array.isArray(ot))throw new Error(`createVitePlugins returned ${typeof ot}, expected array. Value: ${ot}`);let ns=$n({mode:x,chunkingOptions:W,debug:N,isDev:P,isDebug:k,shouldAnalyze:_}),os=s?void 0:Pn(m.port||3e3,m,nt),rs=s?Rn(A):void 0;if(i)try{let{createDndevPlugin:se}=await Promise.resolve().then(()=>(ts(),es));T.push(se(typeof i=="object"?i:{}))}catch{}return{...te&&{base:te},plugins:[...ot,...T],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...x==="production"&&{build:ns},...n==="serve"&&!s&&{server:os},...s&&{preview:rs},...he&&{envDir:he},customLogger:x==="production"&&!N?(()=>{let se={hasWarned:!1,_shouldSuppress(ue){return ue.includes("dist/")||ue.includes("kB")||ue.includes("\u2502")||ue.includes("gzip:")||ue.includes("\u2713 built in")||ue.match(/built in \d+\.\d+s/)},info(ue){se._shouldSuppress(ue)},warn(ue){se._shouldSuppress(ue)},error(ue){},warnOnce(ue){se.hasWarned||(se.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return se})():void 0,css:{postcss:Dn(J),...J},optimizeDeps:Jr(E),resolve:Vr(w),define:{...xe,"process.env.NODE_ENV":JSON.stringify(r),__DEV__:JSON.stringify(P),__PROD__:JSON.stringify(!P)},...ne}}catch(t){let n=t||new Error("Unknown error occurred"),r=n?.message||n?.toString()||String(n)||"Unknown error",s=n?.stack||"",a=new Error(`Failed to create Vite config: ${r}${s?`
1284
+ ${s}`:""}`);throw a.stack=s||a.stack,a}}}export{kl as defineViteConfig};