@donotdev/core 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/functions/index.js +2 -2
- package/i18n/locales/eager/dndev_ar.json +9 -0
- package/i18n/locales/eager/dndev_da.json +9 -0
- package/i18n/locales/eager/dndev_de.json +9 -0
- package/i18n/locales/eager/dndev_en.json +9 -0
- package/i18n/locales/eager/dndev_es.json +9 -0
- package/i18n/locales/eager/dndev_fr.json +9 -0
- package/i18n/locales/eager/dndev_it.json +9 -0
- package/i18n/locales/eager/dndev_ja.json +9 -0
- package/i18n/locales/eager/dndev_ko.json +9 -0
- package/i18n/locales/eager/dndev_nl.json +9 -0
- package/i18n/locales/eager/dndev_pl.json +9 -0
- package/i18n/locales/eager/dndev_pt.json +9 -0
- package/i18n/locales/eager/dndev_zh.json +9 -0
- package/i18n/locales/lazy/crud_ar.json +51 -2
- package/i18n/locales/lazy/crud_da.json +50 -2
- package/i18n/locales/lazy/crud_de.json +51 -2
- package/i18n/locales/lazy/crud_en.json +50 -2
- package/i18n/locales/lazy/crud_es.json +53 -3
- package/i18n/locales/lazy/crud_fr.json +53 -3
- package/i18n/locales/lazy/crud_it.json +53 -3
- package/i18n/locales/lazy/crud_ja.json +51 -2
- package/i18n/locales/lazy/crud_ko.json +51 -2
- package/i18n/locales/lazy/crud_nl.json +50 -2
- package/i18n/locales/lazy/crud_pl.json +52 -2
- package/i18n/locales/lazy/crud_pt.json +52 -3
- package/i18n/locales/lazy/crud_zh.json +50 -2
- package/index.d.ts +4823 -2947
- package/index.js +5 -5
- package/next/index.d.ts +10 -0
- package/next/index.js +138 -131
- package/package.json +2 -2
- package/server.d.ts +4659 -2895
- package/server.js +1 -1
- package/symbol-index.json +1 -1
- package/vite/index.d.ts +10 -0
- package/vite/index.js +44 -43
package/next/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import*as $ from"node:fs";import"node:fs";import{createRequire as zs}from"node:module";import{resolve as Se,join as oe,dirname as ae,relative as bt,normalize as Bs,sep as wt,extname as Ws}from"node:path";import{fileURLToPath as Hs}from"node:url";import qs from"fast-glob";var be={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var Ge={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},X={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},B={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},T={next:{proxy:"src/proxy.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},pe="/og-image.png",ze={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},we={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Ae={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"},J={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:[`${Ae.SOURCE_EAGER}/*_*.json`],lazy:[`${Ae.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/**"]},_e={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"]},vt=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var Be={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)/}};var ge={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]},ke={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin"],cs:["latin"],sk:["latin"],hr:["latin"],sl:["latin"],hu:["latin"],ro:["latin"],et:["latin"],lv:["latin"],lt:["latin"],mt:["latin"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},We=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],mt={base:{absolute:!0,onlyFiles:!0,ignore:J.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...J.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...J.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:J.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:J.globalIgnore}};function yt(o,e=null){let t=J[o];if(!t)throw new Error(`Unknown pattern type: ${o}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Ne(o){return mt[o]||mt.base}var he={getGlobOptionsFor:Ne||void 0,SCAN_PATTERNS:J||void 0,getPatternsFor:yt||void 0,I18N_PATHS:Ae||void 0},I={error:(o,e)=>{},warn:(o,e)=>{},info:o=>{}};function de(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EEXIST"}function St(o,e){return o().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var $t={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"},R=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 Bs(e).split(wt).join("/")}catch{return String(e).split(wt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=bt(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(ae(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),n=zs(oe(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/",""),l=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(l))return l;if(["auth","billing","crud","oauth"].includes(a)){let i=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(i))return i}if(a==="firebase"){let i=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(i))return i}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let 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=Se(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Se(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),n=Se(s,r);return this.normalizePath(n)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=$.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:Ws(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 $.promises.readFile(e);let a=await $.promises.readFile(e,r),l=this.stripBom(a);return n==="json"?JSON.parse(l):l}catch(a){return this.options.debug&&I.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 $.readFileSync(e);let a=$.readFileSync(e,r),l=this.stripBom(a);return n==="json"?JSON.parse(l):l}catch(a){return this.options.debug&&I.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:a=!1,verbose:l=!1}=s,i=this.normalizePath(e),c=this.normalizePath(ae(i)),p=this.pathExists(i);if(p&&!n)return l&&I.info(`Skipping existing file: ${i}`),!1;if(a)return I.info(`[DRY RUN] Would write file: ${i}`),!0;try{await $.promises.mkdir(c,{recursive:!0})}catch(d){if(!de(d))throw d}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
|
|
2
|
-
`:g=String(t);try{return await
|
|
3
|
-
`:g=String(t);try{return Buffer.isBuffer(g)
|
|
4
|
-
`;
|
|
5
|
-
`;a.appendFile(l,w)}},c=(p,u)=>{if(u.length===0)return p;let g=u.map(d=>typeof d=="object"?JSON.stringify(d,null,2):String(d)).join(" ");return`${p} ${g}`};return{debug:(p,...u)=>{e&&(n?i("DEBUG",p,u):W.log.message(Q(c(p,u),Z.gray)))},verbose:(p,...u)=>{t&&(n?i("VERBOSE",p,u):W.log.message(c(p,u)))},info:(p,...u)=>{n?i("INFO",p,u):W.log.info(Q(c(p,u),Z.brightCyan))},warn:(p,...u)=>{e&&n?i("WARN",p,u):W.log.warn(Q(c(p,u),Z.brightYellow))},error:(p,...u)=>{e&&n?i("ERROR",p,u):W.log.error(Q(c(p,u),Z.brightRed))},success:(p,...u)=>{e&&n?i("SUCCESS",p,u):W.log.success(Q(c(p,u),Z.brightGreen))},when:(p,u="debug")=>(g,...d)=>{if(p){let h=c(g,d);switch(u){case"verbose":t&&(W.log.message(h),i("VERBOSE",g,d));break;case"info":W.log.info(Q(h,Z.brightCyan)),i("INFO",g,d);break;case"warn":W.log.warn(Q(h,Z.brightYellow)),i("WARN",g,d);break;case"error":W.log.error(Q(h,Z.brightRed)),i("ERROR",g,d);break;case"success":W.log.success(Q(h,Z.brightGreen)),i("SUCCESS",g,d);break;default:e&&(W.log.message(Q(h,Z.gray)),i("DEBUG",g,d))}}},getLogFilePath:()=>l}}var K=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=M(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}};function Js(o){if(!o)return[];let e=R.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 l=e.resolvePath(`${a}/package.json`,r),i=e.readSync(l,{format:"json"});if(!i?.peerDependenciesMeta)continue;for(let[c,p]of Object.entries(i.peerDependenciesMeta))p?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function Xs(o){if(!o)return[];let e=R.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 Ks(o){let e=_e.optionalFeatures||[],t=Js(o),s=Xs(o);return[...new Set([...e,...t,...s])]}function Ys(o){let e=R.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 Zs(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 l=t.getDirname(r);if(l===r)break;r=l}return!1}function Ce(o){let e=Ks(o),t=[],s=[],r=R.getInstance(),n=Ys(o);for(let a of e)a.startsWith("@donotdev/")?n.has(a)?s.push(a):t.push(a):n.has(a)&&Zs(a,o,r)?s.push(a):t.push(a);return{missing:t,installed:s}}var fe=class o extends K{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=Ne("i18n"),a=r.eager||[],l=r.lazy||[],i=(this.options.additionalPaths||[]).map(S=>{let P=S.endsWith(".json")?S:`${S}/*_*.json`;return this.pathResolver.resolveAppPath(P)});i.length>0&&this.logger.debug(`Additional i18n paths configured: ${i.join(", ")}`);let c=r.framework?.eager||[],p=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${l.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${p.join(", ")}`),c.length===0&&p.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),d=(S,P)=>{let A=this.pathResolver.normalizePath(S),C=this.pathResolver.normalizePath(P);return A.startsWith(C)?A.slice(C.length+1):A},h=a.map(S=>d(S,t)),m=[...l,...i].map(S=>d(S,t)),b=c.map(S=>d(S,s)),f=p.map(S=>d(S,s)),y={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},x=await this.pathResolver._globWithNormalization(h,y),D=await this.pathResolver._globWithNormalization(m,y),O={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:n.ignore?.filter(S=>S!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(O.ignore)}`);let _=await this.pathResolver._globWithNormalization(b,O),G=await this.pathResolver._globWithNormalization(f,O);this.logger.debug(`Found ${x.length} eager, ${D.length} lazy, ${_.length} framework eager, ${G.length} framework lazy files`),_.length>0?this.logger.debug(`Framework eager files (first 3): ${_.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),G.length>0?this.logger.debug(`Framework lazy files (first 3): ${G.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${p.join(", ")}`);let re=[...new Set([...x,...D,..._,...G])],ee=new Set([...x,..._]),v={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:ne}=Ce(t),E=new Set(ne.filter(S=>S.startsWith("@donotdev/")).map(S=>S.replace("@donotdev/","")));E.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...E].join(", ")}] (packages not installed)`);let Y=new Map,z=[..._,...G];for(let S of z){let P=this._processTranslationFile(S,_.includes(S),t);if(P){if(E.has(P.namespace))continue;let A=`${P.namespace}_${P.language}`;Y.set(A,P),v.allNamespaces.add(P.namespace),v.supportedLanguages.add(P.language),_.includes(S)&&v.eagerNamespaces.add(P.namespace)}}let U=new Set;for(let S of re){if(z.includes(S))continue;let P=this._processTranslationFile(S,ee.has(S),t);if(P){let{namespace:A,language:C,importPath:V,content:le}=P,Ee=`${P.namespace}_${P.language}`;if(Y.has(Ee)){let je=Y.get(Ee);P.content=this._mergeTranslations(je.content,le)}v.allNamespaces.add(A),v.supportedLanguages.add(C),U.add(C),ee.has(S)&&v.eagerNamespaces.add(A),v.mapping[A]||(v.mapping[A]={}),v.mapping[A][C]=V,P.content&&(v.content[A]||(v.content[A]={}),v.content[A][C]=P.content),v.files.push({path:S,relativePath:this.pathResolver.getRelativePath(S),namespace:A,language:C,eager:ee.has(S),size:P.content?JSON.stringify(P.content).length:0})}}for(let[S,P]of Y){let A=S.lastIndexOf("_"),C=S.slice(0,A),V=S.slice(A+1);U.size>0&&!U.has(V)||(!v.mapping[C]||!v.mapping[C][V])&&(v.mapping[C]||(v.mapping[C]={}),v.mapping[C][V]=P.importPath,v.content[C]||(v.content[C]={}),v.content[C][V]=P.content,v.files.push({path:P.absolutePath,relativePath:this.pathResolver.getRelativePath(P.absolutePath),namespace:C,language:V,eager:v.eagerNamespaces.has(C),size:P.content?JSON.stringify(P.content).length:0}))}let q=U.size>0?[...U].sort():[this.options.fallbackLanguage],k=this._getLanguageAllowlist(),N=q;if(k){let S=q.filter(A=>k.includes(A));N=S.length>0?S:[this.options.fallbackLanguage],this._restrictByLanguage(v.mapping,N),this._restrictByLanguage(v.content,N),v.files=v.files.filter(A=>N.includes(A.language));let P=new Set(Object.keys(v.mapping));v.allNamespaces=new Set([...v.allNamespaces].filter(A=>P.has(A))),v.eagerNamespaces=new Set([...v.eagerNamespaces].filter(A=>P.has(A))),this.logger.debug(`I18n restricted by i18n.only [${k.join(", ")}]: languages [${N.join(", ")}], namespaces ${P.size}`)}let te=[...new Set(N.map(S=>o.LANGUAGE_FLAG_OVERRIDES[S]||S))];return{mapping:v.mapping,content:v.content,eagerNamespaces:[...v.eagerNamespaces].sort(),allNamespaces:[...v.allNamespaces].sort(),supportedLanguages:N,fallbackLanguage:this.options.fallbackLanguage,flagCodes:te,files:v.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,l=r.match(/^(.+)_([^_.]+)\.json$/);if(!l)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,n,a]=l,!n||!a)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),p;try{if(p=this.pathResolver.readSync(e,{format:"json"}),!p)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:n,language:a,importPath:c,absolutePath:e,content:p}}_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}};var Qs=3,xt="dndev-font-preloads.json";function Et({pathResolver:o,debug:e=!1,languages:t=[]}){let s=M("font-preload-next",e,!1);return{apply(r){r.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(n,a)=>{if(n.compiler.isChild()||n.compiler.name?.includes("server"))return a();try{if(!o.getAppRoot())return a();let c=t.length?t:["en"];if(!t.length)try{let b=await new fe(o,{fallbackLanguage:"en"}).discoverTranslations();b?.supportedLanguages?.length&&(c=b.supportedLanguages)}catch{}let u=Rt(c).stems,g=n.outputOptions.publicPath&&String(n.outputOptions.publicPath)!=="auto"?n.outputOptions.publicPath.replace(/\/$/,""):"",d=[];for(let[m]of Object.entries(n.assets)){if(!m.endsWith(".woff2"))continue;let b=m.toLowerCase();if(Array.from(u).some(f=>b.includes(f))){let f=g?`${g}/${m}`:`/${m}`;if(d.push({href:f,type:"font/woff2"}),d.length>=Qs)break}}let h=o.resolveAppPath("public");if(!o.pathExists(h))try{o.ensureDirSync(h)}catch(m){return s.debug(`Font preload: could not create public dir: ${m?.message}`),a()}let w=o.resolvePath(xt,h);o.writeSync(w,JSON.stringify(d,null,0),{overwrite:!0}),s.debug(`Font preload: wrote ${d.length} entries to ${xt}`)}catch(i){s.debug(`Font preload manifest: ${i?.message}`)}a()})}}}import{createRequire as er}from"node:module";var At=er(import.meta.url),qe;function tr(){return qe===void 0&&(qe=[[At.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],At.resolve("@babel/plugin-transform-parameters")]),qe}function _t({logger:o=M("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:n}=s,{RawSource:a}=n;t.hooks.thisCompilation.tap("DndevLowerDestructuring",l=>{l.compiler.isChild()||l.compiler.name?.includes("server")||l.options.mode==="production"&&l.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async i=>{let c,p;try{c=(await import("@babel/core")).default,p=tr()}catch(g){o.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${g?.message}`);return}let u=0;for(let g of Object.keys(i)){if(!g.endsWith(".js"))continue;let d=l.getAsset(g).source.source(),h=typeof d=="string"?d:d.toString("utf8"),w;try{w=c.transformSync(h,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:p})}catch(m){throw new Error(`[lower-destructuring] failed to transform ${g}: ${m.message}`)}w?.code&&w.code!==h&&(l.updateAsset(g,new a(w.code)),u++)}e&&o.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function kt({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"})]}}var Nt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function sr(o){return(e,t)=>{Nt[e]&&(e=Nt[e]);let s=o.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],n=e.split("/").slice(2).join("/"),a=o.resolveFrameworkPackage(r,t);if(a){if(n){let i=o.resolvePath(n,a);if(o.pathExists(i))return i;let c=i+".css";if(o.pathExists(c))return c}let l=o.resolvePath("index.css",a);if(o.pathExists(l))return l}}return o.resolvePath(e,t)}}async function rr(){let[o,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=R.getInstance();return kt({postcssImport:o,postcssNesting:e,autoprefixer:t,resolve:sr(s)})}import{renameSync as nr}from"node:fs";import{basename as Ct,dirname as or,join as Je,relative as ar}from"node:path";var ie="next",ir=["tsx","ts","jsx","js"],Dt=ir.map(o=>`${ie}.${o}`);function F(o,e){return`${o}.${ie}.${e}`}var lr=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],cr=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],pr=["proxy","middleware","instrumentation"],ur="// Generated by @donotdev/config";function Ve(o,e){let t=o.match(new RegExp(`^(.+?)(\\.${ie})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,s,r,n]=t;return e.includes(s)?{name:s,extension:n,marked:!!r}:null}function gr(o){let e=[],t=o.resolveAppPath("src/app"),s=r=>{for(let n of o.readdirSync(r,{withFileTypes:!0})){let a=Je(r,n.name);if(n.isDirectory()){s(a);continue}if(!n.isFile())continue;let l=Ve(n.name,lr);l&&e.push({file:a,...l,metadata:!1});let i=Ve(n.name,cr);i&&e.push({file:a,...i,metadata:!0})}};o.pathExists(t)&&s(t);for(let r of[o.resolveAppPath("src"),o.getAppRoot()])if(o.pathExists(r))for(let n of o.readdirSync(r,{withFileTypes:!0})){let a=n.isFile()&&Ve(n.name,pr);a&&e.push({file:Je(r,n.name),...a,metadata:!1})}return e}function Ft({pathResolver:o,logger:e,isCI:t}){let s=o.getAppRoot(),r=c=>ar(s,c),n=[],a=[],l=[],i=[];for(let c of gr(o)){let p=o.readSync(c.file,{format:"text"})||"";if(!c.marked&&p.startsWith(ur)){o.removeSync(c.file),a.push(r(c.file));continue}c.metadata?i.push(r(c.file)):c.marked||l.push(c)}if(i.length>0)throw new Error(`[dndev] Next ignores code metadata files with the framework's file marker: ${i.join(", ")}. Serve each as a route handler (e.g. src/app/robots.txt/${F("route","ts")}) or a static file (icon.png, opengraph-image.png). The sitemap and llms.txt are generated by the framework.`);if(t&&l.length>0)throw new Error(`[dndev] Next files must carry the .${ie}. marker (src/pages is never a Next route). Rename: `+l.map(({file:c,name:p,extension:u})=>`${r(c)} \u2192 ${F(p,u)}`).join(", ")+". Running the app once in development renames them.");for(let{file:c,name:p,extension:u}of l){let g=Je(or(c),F(p,u));if(o.pathExists(g))throw new Error(`[dndev] Both ${r(c)} and ${r(g)} exist. Next only reads *.${ie}.* files: merge ${Ct(c)} into ${Ct(g)} and delete it.`);nr(c,g),n.push(r(c))}return n.length>0&&e.warn(`Next files renamed to *.${ie}.* (src/pages is never a Next route): ${n.join(", ")}. Commit the renames.`),a.length>0&&e.debug(`Removed generated Next files without marker: ${a.join(", ")}`),{renamed:n,removed:a}}function se(o){return o&&typeof o=="object"&&!Array.isArray(o)}var Ot={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function It({originalWebpack:o,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],languages:n=[],logger:a,debug:l}){return(i,c)=>{let{dev:p,isServer:u,webpack:g}=c;p&&!u&&(i.infrastructureLogging={level:"error"},i.stats={...i.stats,logging:"error",loggingTrace:!1},i.ignoreWarnings=[...i.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let d=i.module?.rules?.find(h=>h.test?.test?.(".svg"));d&&(d.exclude=/\.svg$/i),i.module=i.module||{},i.module.rules=i.module.rules||[],i.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),i.module.rules.push({test:/\.md$/,type:"asset/source"}),i.resolve=i.resolve||{},i.resolve.alias=i.resolve.alias||{};try{let h=R.getInstance(),w=h.resolveAppPath(T.next.blogContent);i.resolve.alias[Ge.blog]=Tt.existsSync(w)?w:h.getEmptyCjsModulePath()}catch(h){a.debug(`Blog content alias fallback to empty stub: ${h?.message}`)}i.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...Ot},g?.IgnorePlugin&&i.plugins.push(new g.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=R.getInstance();i.plugins.push(Et({pathResolver:h,debug:l,languages:n}))}catch(h){a.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(!u)try{i.plugins.push(_t({logger:a,debug:l}))}catch(h){a.debug(`Lower-destructuring webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(a.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),a.info(`\u2705 Including features: ${t.join(", ")}`),i.externals=i.externals||[],Array.isArray(i.externals))i.externals.push(...e);else{let h=i.externals;i.externals=(w,m,b)=>e.includes(m)?b(null,"commonjs "+m):typeof h=="function"?h(w,m,b):b()}if(s.length>0&&g?.NormalModuleReplacementPlugin){let w=R.getInstance().getEmptyCjsModulePath(),m=s.map(f=>f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),b=new RegExp(`^(${m.join("|")})(\\/|$)`);i.plugins.push(new g.NormalModuleReplacementPlugin(b,w)),l&&a.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&g?.NormalModuleReplacementPlugin){let w=R.getInstance().getEmptyFlagModulePath(),m=new Set(r.map(b=>b.toUpperCase()));i.plugins.push(new g.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,b=>{let f=b.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);f&&f[1].toUpperCase()!=="BASE"&&!m.has(f[1].toUpperCase())&&(b.request=w)})),l&&a.debug(`Flag filter: allowing ${m.size} flags, aliasing rest to empty component`)}return o?o(i,c):i}}function Lt({originalRewrites:o,handlers:e,logger:t}){return async function(){try{let s=o?await o():[],n=e.filter(l=>l?.getAPIRewrites).map(l=>l.getAPIRewrites()).reduce((l,i)=>(i?.beforeFiles&&l.beforeFiles.push(...i.beforeFiles),i?.afterFiles&&l.afterFiles.push(...i.afterFiles),i?.fallback&&l.fallback.push(...i.fallback),l),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...n.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...n.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...n.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function Ut({originalRedirects:o,seoRedirects:e,logger:t}){return async function(){try{let s=o?await o():[],r=(e||[]).map(({from:i,to:c,permanent:p})=>({source:i,destination:c,permanent:p!==!1})),n=[],a=new Set;for(let i of r){let c=i.source.replace(/\/+$/,"")||"/",p=i.destination.replace(/\/+$/,"")||"/";if(c===p){t.warn(`Redirect loop detected: ${i.source} \u2192 ${i.destination} (skipped)`);continue}if(!i.source.startsWith("/")){t.warn(`Redirect source must start with /: "${i.source}" (skipped)`);continue}if(a.has(c)){t.warn(`Duplicate redirect source: "${i.source}" (skipped)`);continue}a.add(c),n.push(i)}let l=[...Array.isArray(s)?s:[],...n];return l.length===0?[]:(t.info(` \u{1F4CE} ${l.length} redirect${l.length>1?"s":""} configured`),l)}catch(s){return t.error(`Failed to merge redirects: ${s.message}`),[]}}}function Mt({routeResult:o,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:n,serverShimResult:a,restNextConfig:l,discoveredPackages:i,reactCompiler:c=!1,routingMode:p,webpackConfig:u,rewritesConfig:g,redirectsConfig:d,missingOptionalDeps:h,flagCodes:w=[],pathResolver:m,env:b,logger:f}){let y=l?.output==="export";if(p==="app"&&l?.pageExtensions)throw new Error("[dndev] pageExtensions is set by the framework (Next files carry the .next. marker so src/pages is never a route). Remove it from next.config.");let D=l?.distDir||".next";return{transpilePackages:[...i,...h||[]],...c?{reactCompiler:c}:{},...se(l)?l:(f.warn("restNextConfig is not a plain object:",l),{}),...p==="app"&&{pageExtensions:Dt},...p==="app"&&{experimental:{...l?.experimental,globalNotFound:!0}},serverExternalPackages:(l?.serverExternalPackages||l?.serverComponentsExternalPackages||[]).filter(_=>!_.startsWith("@donotdev/")&&!h?.includes(_)),turbopack:{...l?.turbopack||{},root:l?.turbopack?.root||m.getRepoRoot(),resolveAlias:{...l?.turbopack?.resolveAlias||{},...Ot,[Ge.blog]:(()=>{try{let _=m.resolveAppPath(T.next.blogContent);if(Tt.existsSync(_))return"./"+T.next.blogContent}catch{}return"@donotdev/core/empty"})(),...h?.length>0?Object.fromEntries(h.flatMap(_=>[[_,"@donotdev/core/empty"],[`${_}/*`,"@donotdev/core/empty"]])):{}}},distDir:D,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...se(o)?o:(f.error(`Route handler config invalid (got ${typeof o}):`,o),{}),...se(e)?e:(f.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...se(t)?t:(f.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...se(s)?s:(f.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...se(r)?r:(f.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...se(n)?n:(f.error(`PWA handler config invalid (got ${typeof n}):`,n),{}),...se(a)?a:(f.warn("serverShimConfig returned non-object:",a),{}),webpack:u,...y?{}:{rewrites:g,...d?{redirects:d}:{}},env:b,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var De="fonts",Xe="dndev-fonts.css",hr=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,Gt=/url\(\.\/files\/([^)]+)\)/g;function dr(o){let e=new Set(["latin"]);for(let t of o){let s=ke[t];if(s)for(let r of s)e.add(r)}return e}function fr(o,e){let t=o.resolvePath("src/dndev.css",e),s=o.readSync(t,{format:"text"});if(!s)return[];let r=[],n;for(;(n=hr.exec(s))!==null;)r.push([n[1],n[2]]);return r}function mr(o,e,t,s,r){let n=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
6
|
-
`
|
|
7
|
-
|
|
8
|
-
`)),
|
|
1
|
+
import*as S from"node:fs";import"node:fs";import{createRequire as Bs}from"node:module";import{resolve as Se,join as oe,dirname as ae,relative as wt,normalize as Hs,sep as St,extname as Ws}from"node:path";import{fileURLToPath as qs}from"node:url";import Vs from"fast-glob";var ye={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var je={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},J={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},Z={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},O={next:{proxy:"src/proxy.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},pe="/og-image.png",Ge={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},be={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Ae={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"},V={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:[`${Ae.SOURCE_EAGER}/*_*.json`],lazy:[`${Ae.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/**"]},_e={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"]},mt=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var ze={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}},vt={Inter:"inter","Space Grotesk":"space-grotesk","Playfair Display":"playfair-display","Press Start 2P":"press-start-2p",Roboto:"roboto"},we={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]},yt={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:[]},Be=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],dt={base:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...V.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...V.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore}};function bt(a,e=null){let t=V[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function ke(a){return dt[a]||dt.base}var ge={getGlobOptionsFor:ke||void 0,SCAN_PATTERNS:V||void 0,getPatternsFor:bt||void 0,I18N_PATHS:Ae||void 0},I={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function he(a){return typeof a=="object"&&a!==null&&"code"in a&&a.code==="EEXIST"}function $t(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Rt={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"},R=class a{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._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,a._instance=this}normalizePath(e){if(!e)return"";try{return Hs(e).split(St).join("/")}catch{return String(e).split(St).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=wt(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(ae(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),n=Bs(oe(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 o=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${o}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(o)){let l=this.resolveRepoPath(`packages/features/${o}`);if(this.pathExists(l))return l}if(o==="firebase"){let l=this.resolveRepoPath(`packages/providers/${o}`);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=Se(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Se(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),n=Se(s,r);return this.normalizePath(n)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=S.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:Ws(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 S.promises.readFile(e);let o=await S.promises.readFile(e,r),i=this.stripBom(o);return n==="json"?JSON.parse(i):i}catch(o){return this.options.debug&&I.warn(`Failed to read file: ${e}`,o),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return S.readFileSync(e);let o=S.readFileSync(e,r),i=this.stripBom(o);return n==="json"?JSON.parse(i):i}catch(o){return this.options.debug&&I.warn(`Failed to read file: ${e}`,o),null}}async write(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:o=!1,verbose:i=!1}=s,l=this.normalizePath(e),c=this.normalizePath(ae(l)),p=this.pathExists(l);if(p&&!n)return i&&I.info(`Skipping existing file: ${l}`),!1;if(o)return I.info(`[DRY RUN] Would write file: ${l}`),!0;try{await S.promises.mkdir(c,{recursive:!0})}catch(h){if(!he(h))throw h}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`:g=String(t);try{return await $t(async()=>(Buffer.isBuffer(g)?await S.promises.writeFile(l,g):await S.promises.writeFile(l,g,"utf8"),i&&I.info(`${p?"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:o=!1,verbose:i=!1}=s,l=this.normalizePath(e),c=this.normalizePath(ae(l)),p=this.pathExists(l);if(p&&!n)return i&&I.info(`Skipping existing file: ${l}`),!1;if(o)return I.info(`[DRY RUN] Would write file: ${l}`),!0;try{S.mkdirSync(c,{recursive:!0})}catch(h){if(!he(h))throw h}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
|
|
3
|
+
`:g=String(t);try{return Buffer.isBuffer(g)?S.writeFileSync(l,g):S.writeFileSync(l,g,"utf8"),this._writtenPaths?.add(l),i&&I.info(`${p?"Updated":"Created"} file: ${l}`),!0}catch(h){throw new Error(`Failed to write file: ${l}: ${h instanceof Error?h.message:String(h)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:n=!1,verbose:o=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return o&&I.info(`Skipping existing file: ${i}`),!1;if(n)return I.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(ae(i));try{await S.promises.mkdir(c,{recursive:!0})}catch(p){if(!he(p))throw p}try{return await $t(async()=>(await S.promises.copyFile(e,i),o&&I.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:o=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return o&&I.info(`Skipping existing file: ${i}`),!1;if(n)return I.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(ae(i));try{S.mkdirSync(c,{recursive:!0})}catch(p){if(!he(p))throw p}try{return S.copyFileSync(e,i),this._writtenPaths?.add(i),o&&I.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return S.existsSync(e)}catch(s){return t||I.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 S.existsSync(t)||S.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return S.readdirSync(e,t)}catch(s){return this.options.debug&&I.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return S.statSync(e)}catch(t){return this.options.debug&&I.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return S.realpathSync(e)}watch(e,t,s){return S.watch(e,t,s)}lstatSync(e){try{return S.lstatSync(e)}catch(t){return this.options.debug&&I.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await S.promises.mkdir(e,{recursive:!0})}catch(t){if(!he(t))throw t}}ensureDirSync(e){try{S.mkdirSync(e,{recursive:!0})}catch(t){if(!he(t))throw t}}async remove(e){await S.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){S.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return S.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=oe(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Se(e)),s=this.getAppRoot(),r=wt(s,t),n=this.normalizePath(r);return!n.startsWith("../")&&!n.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(oe(e,t)),n=this.getAppRoot(),o=this.normalizePath(n),i=r.startsWith(o)?r.slice(o.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:ge.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ge.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(oe(r,t.PUBLISHED_ROOT,s)),o=n.replace(/\/[^/]*\*.*$/,"");return this.pathExists(o),n}async _globWithNormalization(e,t){return(await Vs(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 p of s)if(typeof p!="string"||p.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),n=ge.getGlobOptionsFor?ge.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},o=this.normalizePath(r),i=e.framework.map(p=>{let u=this.normalizePath(p);return u.startsWith(o)?u.slice(o.length+1):u}),l=e.consumer.map(p=>{let u=this.normalizePath(p);return u.startsWith(o)?u.slice(o.length+1):u}),c={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let p=i.length>0?await this._globWithNormalization(i,c):[],u=await this._globWithNormalization(l,c);return{frameworkFiles:p,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ge.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=ge.getPatternsFor(e),n=this.isMonorepo();if(e==="i18n"){let l=r,c={eager:l.eager.map(p=>p.startsWith("!")?"!"+this.resolveAppPath(p.slice(1)):this.resolveAppPath(p)),lazy:l.lazy.map(p=>p.startsWith("!")?"!"+this.resolveAppPath(p.slice(1)):this.resolveAppPath(p)),framework:{eager:n?(l.framework?.eager||[]).map(p=>this.resolveRepoPath(p)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(p=>this._resolveFrameworkI18nPattern(p))).then(p=>p.filter(Boolean)),lazy:n?(l.framework?.lazy||[]).map(p=>this.resolveRepoPath(p)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(p=>this._resolveFrameworkI18nPattern(p))).then(p=>p.filter(Boolean))},all:[]};return c.all=[...c.eager,...c.lazy,...c.framework.eager,...c.framework.lazy],c}let o=r,i={framework:n?(o.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(o.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=ae(qs(import.meta.url));return this.normalizePath(Se(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(oe(t,Rt.TOOLING)),o=this.normalizePath(oe(t,Rt.CORE));if(this.pathExists(n)&&this.pathExists(o))return t;let i=oe(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(oe(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(ae(t))===t)return t;let c=this.normalizePath(ae(t));if(c===t)break;t=c,s++}return this.normalizePath(e)}};function Pt({logger:a,debug:e=!1}={}){let t=R.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):a&&a.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&a&&a.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let o=t.resolveRepoPath("apps");if(t.pathExists(o))try{let i=process.cwd(),l=t.normalizePath(i);if(l.includes("/apps/")){let c=l.indexOf("/apps/"),u=l.substring(c+6).split("/")[0];if(u){let g=t.resolveRepoPath(`apps/${u}`),h=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(h)&&(r=g,t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}import Dt from"node:fs";import{createRequire as Xs}from"node:module";import*as B from"@clack/prompts";var Y={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 Js(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function Q(a,e){return Js()?`${e}${a}${Y.reset}`:a}function G(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:n=!1}=s,o=R.getInstance(),i=null;if(n){let p=o.resolveAppPath(r);o.pathExists(p)||o.mkdir(p),i=o.resolveAppPath(`${r}/${a.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${a} Log Started at ${new Date().toISOString()} ===
|
|
4
|
+
`;o.writeSync(i,u)}let l=(p,u,g)=>{if(i){let h=new Date().toISOString(),f=g.length>0?" "+g.map(y=>typeof y=="object"?JSON.stringify(y,null,2):String(y)).join(" "):"",w=`${h} [${p}] ${u}${f}
|
|
5
|
+
`;o.appendFile(i,w)}},c=(p,u)=>{if(u.length===0)return p;let g=u.map(h=>typeof h=="object"?JSON.stringify(h,null,2):String(h)).join(" ");return`${p} ${g}`};return{debug:(p,...u)=>{e&&(n?l("DEBUG",p,u):B.log.message(Q(c(p,u),Y.gray)))},verbose:(p,...u)=>{t&&(n?l("VERBOSE",p,u):B.log.message(c(p,u)))},info:(p,...u)=>{n?l("INFO",p,u):B.log.info(Q(c(p,u),Y.brightCyan))},warn:(p,...u)=>{e&&n?l("WARN",p,u):B.log.warn(Q(c(p,u),Y.brightYellow))},error:(p,...u)=>{e&&n?l("ERROR",p,u):B.log.error(Q(c(p,u),Y.brightRed))},success:(p,...u)=>{e&&n?l("SUCCESS",p,u):B.log.success(Q(c(p,u),Y.brightGreen))},when:(p,u="debug")=>(g,...h)=>{if(p){let f=c(g,h);switch(u){case"verbose":t&&(B.log.message(f),l("VERBOSE",g,h));break;case"info":B.log.info(Q(f,Y.brightCyan)),l("INFO",g,h);break;case"warn":B.log.warn(Q(f,Y.brightYellow)),l("WARN",g,h);break;case"error":B.log.error(Q(f,Y.brightRed)),l("ERROR",g,h);break;case"success":B.log.success(Q(f,Y.brightGreen)),l("SUCCESS",g,h);break;default:e&&(B.log.message(Q(f,Y.gray)),l("DEBUG",g,h))}}},getLogFilePath:()=>i}}var xt=Xs(import.meta.url),He;function Ks(){return He===void 0&&(He=[[xt.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],xt.resolve("@babel/plugin-transform-parameters")]),He}function Et({logger:a=G("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:n}=s,{RawSource:o}=n;t.hooks.thisCompilation.tap("DndevLowerDestructuring",i=>{i.compiler.isChild()||i.compiler.name?.includes("server")||i.options.mode==="production"&&i.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async l=>{let c,p;try{c=(await import("@babel/core")).default,p=Ks()}catch(g){a.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${g?.message}`);return}let u=0;for(let g of Object.keys(l)){if(!g.endsWith(".js"))continue;let h=i.getAsset(g).source.source(),f=typeof h=="string"?h:h.toString("utf8"),w;try{w=c.transformSync(f,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:p})}catch(y){throw new Error(`[lower-destructuring] failed to transform ${g}: ${y.message}`)}w?.code&&w.code!==f&&(i.updateAsset(g,new o(w.code)),u++)}e&&a.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function At({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?a({resolve:s}):a,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var _t={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Ys(a){return(e,t)=>{_t[e]&&(e=_t[e]);let s=a.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],n=e.split("/").slice(2).join("/"),o=a.resolveFrameworkPackage(r,t);if(o){if(n){let l=a.resolvePath(n,o);if(a.pathExists(l))return l;let c=l+".css";if(a.pathExists(c))return c}let i=a.resolvePath("index.css",o);if(a.pathExists(i))return i}}return a.resolvePath(e,t)}}async function Zs(){let[a,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=R.getInstance();return At({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:Ys(s)})}import{renameSync as Qs}from"node:fs";import{basename as kt,dirname as er,join as qe,relative as tr}from"node:path";var ie="next",sr=["tsx","ts","jsx","js"],Nt=sr.map(a=>`${ie}.${a}`);function F(a,e){return`${a}.${ie}.${e}`}var rr=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],nr=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],or=["proxy","middleware","instrumentation"],ar="// Generated by @donotdev/config";function We(a,e){let t=a.match(new RegExp(`^(.+?)(\\.${ie})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,s,r,n]=t;return e.includes(s)?{name:s,extension:n,marked:!!r}:null}function ir(a){let e=[],t=a.resolveAppPath("src/app"),s=r=>{for(let n of a.readdirSync(r,{withFileTypes:!0})){let o=qe(r,n.name);if(n.isDirectory()){s(o);continue}if(!n.isFile())continue;let i=We(n.name,rr);i&&e.push({file:o,...i,metadata:!1});let l=We(n.name,nr);l&&e.push({file:o,...l,metadata:!0})}};a.pathExists(t)&&s(t);for(let r of[a.resolveAppPath("src"),a.getAppRoot()])if(a.pathExists(r))for(let n of a.readdirSync(r,{withFileTypes:!0})){let o=n.isFile()&&We(n.name,or);o&&e.push({file:qe(r,n.name),...o,metadata:!1})}return e}function Ct({pathResolver:a,logger:e,isCI:t}){let s=a.getAppRoot(),r=c=>tr(s,c),n=[],o=[],i=[],l=[];for(let c of ir(a)){let p=a.readSync(c.file,{format:"text"})||"";if(!c.marked&&p.startsWith(ar)){a.removeSync(c.file),o.push(r(c.file));continue}c.metadata?l.push(r(c.file)):c.marked||i.push(c)}if(l.length>0)throw new Error(`[dndev] Next ignores code metadata files with the framework's file marker: ${l.join(", ")}. Serve each as a route handler (e.g. src/app/robots.txt/${F("route","ts")}) or a static file (icon.png, opengraph-image.png). The sitemap and llms.txt are generated by the framework.`);if(t&&i.length>0)throw new Error(`[dndev] Next files must carry the .${ie}. marker (src/pages is never a Next route). Rename: `+i.map(({file:c,name:p,extension:u})=>`${r(c)} \u2192 ${F(p,u)}`).join(", ")+". Running the app once in development renames them.");for(let{file:c,name:p,extension:u}of i){let g=qe(er(c),F(p,u));if(a.pathExists(g))throw new Error(`[dndev] Both ${r(c)} and ${r(g)} exist. Next only reads *.${ie}.* files: merge ${kt(c)} into ${kt(g)} and delete it.`);Qs(c,g),n.push(r(c))}return n.length>0&&e.warn(`Next files renamed to *.${ie}.* (src/pages is never a Next route): ${n.join(", ")}. Commit the renames.`),o.length>0&&e.debug(`Removed generated Next files without marker: ${o.join(", ")}`),{renamed:n,removed:o}}function se(a){return a&&typeof a=="object"&&!Array.isArray(a)}var Tt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Ft({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],logger:n,debug:o}){return(i,l)=>{let{dev:c,isServer:p,webpack:u}=l;c&&!p&&(i.infrastructureLogging={level:"error"},i.stats={...i.stats,logging:"error",loggingTrace:!1},i.ignoreWarnings=[...i.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let g=i.module?.rules?.find(h=>h.test?.test?.(".svg"));g&&(g.exclude=/\.svg$/i),i.module=i.module||{},i.module.rules=i.module.rules||[],i.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),i.module.rules.push({test:/\.md$/,type:"asset/source"}),i.resolve=i.resolve||{},i.resolve.alias=i.resolve.alias||{};try{let h=R.getInstance(),f=h.resolveAppPath(O.next.blogContent);i.resolve.alias[je.blog]=Dt.existsSync(f)?f:h.getEmptyCjsModulePath()}catch(h){n.debug(`Blog content alias fallback to empty stub: ${h?.message}`)}if(i.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...Tt},u?.IgnorePlugin&&i.plugins.push(new u.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/})),!p)try{i.plugins.push(Et({logger:n,debug:o}))}catch(h){n.debug(`Lower-destructuring webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(n.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),n.info(`\u2705 Including features: ${t.join(", ")}`),i.externals=i.externals||[],Array.isArray(i.externals))i.externals.push(...e);else{let h=i.externals;i.externals=(f,w,y)=>e.includes(w)?y(null,"commonjs "+w):typeof h=="function"?h(f,w,y):y()}if(s.length>0&&u?.NormalModuleReplacementPlugin){let f=R.getInstance().getEmptyCjsModulePath(),w=s.map(v=>v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),y=new RegExp(`^(${w.join("|")})(\\/|$)`);i.plugins.push(new u.NormalModuleReplacementPlugin(y,f)),o&&n.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&u?.NormalModuleReplacementPlugin){let f=R.getInstance().getEmptyFlagModulePath(),w=new Set(r.map(y=>y.toUpperCase()));i.plugins.push(new u.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,y=>{let v=y.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);v&&v[1].toUpperCase()!=="BASE"&&!w.has(v[1].toUpperCase())&&(y.request=f)})),o&&n.debug(`Flag filter: allowing ${w.size} flags, aliasing rest to empty component`)}return a?a(i,l):i}}function Ot({originalRewrites:a,handlers:e,logger:t}){return async function(){try{let s=a?await a():[],n=e.filter(i=>i?.getAPIRewrites).map(i=>i.getAPIRewrites()).reduce((i,l)=>(l?.beforeFiles&&i.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&i.afterFiles.push(...l.afterFiles),l?.fallback&&i.fallback.push(...l.fallback),i),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...n.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...n.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...n.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function It({originalRedirects:a,seoRedirects:e,logger:t}){return async function(){try{let s=a?await a():[],r=(e||[]).map(({from:l,to:c,permanent:p})=>({source:l,destination:c,permanent:p!==!1})),n=[],o=new Set;for(let l of r){let c=l.source.replace(/\/+$/,"")||"/",p=l.destination.replace(/\/+$/,"")||"/";if(c===p){t.warn(`Redirect loop detected: ${l.source} \u2192 ${l.destination} (skipped)`);continue}if(!l.source.startsWith("/")){t.warn(`Redirect source must start with /: "${l.source}" (skipped)`);continue}if(o.has(c)){t.warn(`Duplicate redirect source: "${l.source}" (skipped)`);continue}o.add(c),n.push(l)}let i=[...Array.isArray(s)?s:[],...n];return i.length===0?[]:(t.info(` \u{1F4CE} ${i.length} redirect${i.length>1?"s":""} configured`),i)}catch(s){return t.error(`Failed to merge redirects: ${s.message}`),[]}}}function Lt({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:n,serverShimResult:o,restNextConfig:i,discoveredPackages:l,reactCompiler:c=!1,routingMode:p,webpackConfig:u,rewritesConfig:g,redirectsConfig:h,missingOptionalDeps:f,flagCodes:w=[],pathResolver:y,env:v,logger:P}){let b=i?.output==="export";if(p==="app"&&i?.pageExtensions)throw new Error("[dndev] pageExtensions is set by the framework (Next files carry the .next. marker so src/pages is never a route). Remove it from next.config.");let T=i?.distDir||".next";return{transpilePackages:[...l,...f||[]],...c?{reactCompiler:c}:{},...se(i)?i:(P.warn("restNextConfig is not a plain object:",i),{}),...p==="app"&&{pageExtensions:Nt},...p==="app"&&{experimental:{...i?.experimental,globalNotFound:!0}},serverExternalPackages:(i?.serverExternalPackages||i?.serverComponentsExternalPackages||[]).filter(_=>!_.startsWith("@donotdev/")&&!f?.includes(_)),turbopack:{...i?.turbopack||{},root:i?.turbopack?.root||y.getRepoRoot(),resolveAlias:{...i?.turbopack?.resolveAlias||{},...Tt,[je.blog]:(()=>{try{let _=y.resolveAppPath(O.next.blogContent);if(Dt.existsSync(_))return"./"+O.next.blogContent}catch{}return"@donotdev/core/empty"})(),...f?.length>0?Object.fromEntries(f.flatMap(_=>[[_,"@donotdev/core/empty"],[`${_}/*`,"@donotdev/core/empty"]])):{}}},distDir:T,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...se(a)?a:(P.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...se(e)?e:(P.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...se(t)?t:(P.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...se(s)?s:(P.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...se(r)?r:(P.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...se(n)?n:(P.error(`PWA handler config invalid (got ${typeof n}):`,n),{}),...se(o)?o:(P.warn("serverShimConfig returned non-object:",o),{}),webpack:u,...b?{}:{rewrites:g,...h?{redirects:h}:{}},env:v,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var lr=["--font-family","--font-headline","--font-mono"],fe=":root",cr=/\/\*[\s\S]*?\*\//g,pr=/([^{}]+)\{([^{}]*)\}/g,ur=/^(?::root|html|:where\(:root\))$/,gr=/^(?::root|html)?\.([a-z][\w-]*)$/i,hr=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/;function Mt(a){let e=[],t=0,s="",r=0;for(let n=0;n<a.length;n++){let o=a[n];s?o===s&&(s=""):o==='"'||o==="'"?s=o:o==="("?t++:o===")"?t--:o===","&&t===0&&(e.push(a.slice(r,n)),r=n+1)}return e.push(a.slice(r)),e.map(n=>n.trim())}function fr(a){if(ur.test(a))return fe;let e=gr.exec(a);return e?e[1]:null}function Ut(a){let e=new Map,t=a.replace(cr,"");for(let[,s,r]of t.matchAll(pr)){let n=s.split(";").pop(),o=Mt(n).map(fr).filter(i=>i!==null);if(o.length!==0)for(let i of r.split(";")){let l=i.indexOf(":");if(l===-1)continue;let c=i.slice(0,l).trim();if(!c.startsWith("--"))continue;let p=i.slice(l+1).replace(/!important\s*$/,"").trim();for(let u of o)e.has(u)||e.set(u,new Map),e.get(u).set(c,p)}}return e}function Ve(a,e,t){let s=Mt(a)[0];if(!s)return null;let r=hr.exec(s);if(r){let[,n,o]=r;return e.has(n)&&!t.has(n)?Ve(e.get(n),e,new Set([...t,n])):o===void 0?null:Ve(o,e,t)}return s.replace(/^['"]|['"]$/g,"").trim()}function jt({frameworkCss:a,appCss:e}){let t=Ut(a),s=Ut(e.join(`
|
|
6
|
+
`)),r=new Set([fe,...t.keys(),...s.keys()]),n=new Set;for(let o of r){let i=new Map([...t.get(fe)??[],...s.get(fe)??[],...o===fe?[]:t.get(o)??[],...o===fe?[]:s.get(o)??[]]);for(let l of lr){if(!i.has(l))continue;let c=Ve(i.get(l),i,new Set([l]));c&&n.add(c)}}return[...n]}var dr=new Map(Object.entries(vt).map(([a,e])=>[a.toLowerCase(),e]));function Gt({families:a,locales:e=[]}){if(!Array.isArray(a))throw new Error("resolveFontManifest: families is required (ThemeDiscovery fontFamilies)");let t=new Set;for(let n of a){let o=dr.get(n.toLowerCase());o&&t.add(o)}let s=new Set(["latin"]);for(let n of e)for(let o of yt[n]??[])s.add(o);let r=new Set;for(let n of t)for(let o of s)for(let i of we[n])r.add(`${n}-${o}-${i}-normal`);return{fontStems:t,subsets:s,stems:r}}function zt(a){let e=a.split(/[/\\]/).pop().toLowerCase();for(let t of Object.keys(we)){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 Bt(a){return a.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}var Je="fonts",Xe="dndev-fonts.css",mr=/@font-face\s*\{[^}]*\}/g,vr=/url\(\.\/files\/([^)]+)\)/g,yr=/url\(\.\/files\/([^)]+)\)/;function Ht({families:a,languages:e,debug:t=!1,force:s=!1}){let r=G("font-copy",t,!1),n=R.getInstance(),o=Gt({families:a,locales:e});if(o.fontStems.size===0){r.debug(`No framework font used by the theme (families: ${a.join(", ")||"none"})`);return}let i=n.resolveAppPath(`public/${Xe}`);if(!s&&n.pathExists(i)){r.debug("dndev-fonts.css already exists, skipping font copy");return}let l=n.resolveFrameworkPackage("@donotdev/ui");if(!l)throw new Error("Font copy: @donotdev/ui not found");let c=n.resolveAppPath(`public/${Je}`);n.ensureDirSync(c);let p=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
7
|
+
`],u=new Set;for(let g of o.fontStems)for(let h of we[g]){let f=`@fontsource/${g}/${h}.css`,w=n.resolvePackage(f,l);if(!w)throw new Error(`Font copy: cannot resolve ${f}`);let y=n.readSync(w,{format:"text"}),v=n.resolvePath("files",n.getDirname(w));for(let P of y.match(mr)??[]){let b=zt(yr.exec(P)?.[1]??"");if(!b||!o.stems.has(b))continue;let x=Bt(P).replace(vr,(T,C)=>{let _=n.resolvePath(C,v);if(!n.pathExists(_))throw new Error(`Font copy: font file missing: ${_}`);return u.has(C)||(n.copySync(_,n.resolvePath(C,c),{overwrite:!0}),u.add(C)),`url(/${Je}/${C})`});p.push(x)}}n.writeSync(i,p.join(`
|
|
8
|
+
`)),r.debug(`Font copy: wrote ${Xe} (${u.size} font files: ${[...o.fontStems].join(", ")})`)}function Wt(){let a=R.getInstance(),e=a.resolveAppPath(`public/${Xe}`),t=a.resolveAppPath(`public/${Je}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var br=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json","public/dndev-fonts.css","public/robots.txt","public/sitemap.xml","public/rss.xml","public/llms.txt","public/llms-full.txt"],wr="dndev-config-",qt=".dndev-build";function Ke(a){if(!a)return!1;let e=R.getInstance(),t=e.resolveAppPath(qt),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function Sr(a){if(!a)return;let e=R.getInstance(),t=e.resolveAppPath(qt),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s,{overwrite:!0})}catch{}}function $r(a,e,t){if(!a)return;let s=R.getInstance(),r=(o,i)=>{let l=s.normalizePath(o);if(!(t.has(l)||!s.pathExists(l)))try{s.removeSync(o),e.debug(`Removed stale: ${i}`)}catch{}};for(let o of br)r(s.resolveAppPath(o),o);let n=s.resolveAppPath("src/config");for(let o of s.readdirSync(n))o.startsWith(wr)&&o.endsWith(".js")&&r(s.resolvePath(o,n),`src/config/${o}`)}async function Vt({routeHandler:a,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:n,blogContentHandler:o},i){let l=a?.pathResolver;if(!l)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let c=l.getAppRoot(),p=l.getRepoRoot();if(!c||c===p){i.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(w=>setTimeout(w,0));let f=l.getAppRoot();if(!f||f===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Ke(c)){i.debug("Discoveries already completed this build, skipping");return}Sr(c);let u=Date.now();l.startWriteRecording();let g;try{Wt();let f=await t.getDiscoveryData(),w={languages:f.supportedLanguages,defaultLanguage:f.fallbackLanguage};if(r.useLanguages(w),r.useTranslations(f.content),a)try{a.useLanguages(w),i.info("\u{1F50D} Starting route discovery...");let P=(await a.generateFiles())?.routes?.length||0;i.info(`\u2705 Routes generated: ${P} routes found`),P===0&&i.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(v){throw i.error(`\u274C Route generation failed: ${v.message}`),v.stack&&i.error(`Stack: ${v.stack}`),v}else i.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let y=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:n},{name:"BlogContent",handler:o}];for(let{name:v,handler:P}of y)try{await P.generateFiles()}catch(b){i.debug(`${v} generation failed: ${b.message}`)}try{Rr(l,i)}catch(v){i.debug(`Env config generation failed (non-critical): ${v.message}`)}if(e){let{fontFamilies:v}=await e.getDiscoveryData();Ht({families:v,languages:f.supportedLanguages})}}finally{g=l.stopWriteRecording()}$r(c,i,g);let h=Date.now()-u;i.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`)}function Rr(a,e){let t={};for(let[o,i]of Object.entries(process.env))o.startsWith("NEXT_PUBLIC_")&&i!==void 0&&(t[o]=i);let s=`// Auto-generated DnDev env config by @donotdev/config
|
|
9
9
|
// Generated at: ${new Date().toISOString()}
|
|
10
10
|
// Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
|
|
11
11
|
|
|
@@ -22,12 +22,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
22
22
|
timestamp: Date.now(),
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
-
globalThis._DNDEV_CONFIG_.${
|
|
25
|
+
globalThis._DNDEV_CONFIG_.${J.env} = envConfig;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
// Export for compatibility
|
|
29
29
|
export default envConfig;
|
|
30
|
-
`,r=
|
|
30
|
+
`,r=a.resolveAppPath(O.next.configEnv);a.writeSync(r,s,{overwrite:!0});let n=Object.keys(t).length;e.debug(`Generated env config: ${n} NEXT_PUBLIC_* vars`)}async function Jt(a,e,t){if(t)return!1;try{let s=await a.getDiscoveryData();return s?.copiedAssets?.length>0&&e.info(`\u{1F4E6} Copied ${s.copiedAssets.length} assets from framework`),!0}catch(s){return e.debug(`Asset discovery failed (non-critical): ${s.message}`),!1}}var Xt={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 $e={...Xt,generateManifest:!0,reactCompiler:!1,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function Kt(a,e){let t={...a};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=Kt(a[s]||{},e[s]):t[s]=e[s]}),t}function Yt(a={}){return Kt($e,a)}function Zt(a){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:n={},pwa:o={},seo:i={},serverShim:l={},discovery:c={},generateManifest:p,debug:u,verbose:g,...h}=a,f=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:p,debug:u,verbose:g,mode:f,isDev:f==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:n,featureOptions:e,pwaOptions:o,seoOptions:i,serverShimOptions:l,discoveryOptions:c,nextConfigOptions:h}}var M=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=G(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=R.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}revalidate(){let e=this.options.revalidate??Z.revalidateSeconds;if(e===!1||Number.isInteger(e)&&e>0)return e;throw new Error(`appConfig.revalidate must be a whole number of seconds above 0, or false (kept until the next deploy). Got ${JSON.stringify(e)}.`)}revalidateLabel(){let e=this.revalidate();return e===!1?"kept until the next deploy":`re-rendered at most every ${e}s`}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...$e.discovery,...this.options};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}createNextConfig(){return(e={})=>(this.options.debug&&this.logger.debug(`${this.getHandlerName()} handler initialized`),{...e,webpack:(t,s)=>{let{dev:r,isServer:n,webpack:o}=s;return this.applyViteIgnorePlugin(t,o),this._generateFiles(),e.webpack?e.webpack(t,s):t},rewrites:async function(){try{let t=e.rewrites?await e.rewrites():[],s=this.getAPIRewrites();return this.mergeRewrites(t,s)}catch(t){return this.logger.error(`${this.getHandlerName()} handler failed to merge rewrites: ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`),[]}}.bind(this)})}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let t=this.getHandlerName().toLowerCase(),s=O.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!s)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let r=this.generateConfigContent(e);this.writeGeneratedFile(s,r,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),s=J[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
31
31
|
// Generated at: ${new Date().toISOString()}
|
|
32
32
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
33
33
|
|
|
@@ -49,7 +49,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
49
49
|
|
|
50
50
|
// Export for compatibility
|
|
51
51
|
export default ${t}Config;
|
|
52
|
-
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t,{overwrite:!0}),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var ue={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Fe=class extends K{constructor(e,t={}){super(e,{assets:J.assets.fallback,assetPatterns:J.assets.patterns,frameworkPackage:ze.package,assetsPath:ze.assetsPath,modernFormats:J.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=[],l=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(l)&&this.options.generateAssets!==!1&&(a=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:i}=e,c=await this._processAssetFiles(i),p=this._buildAssetManifest(c),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:c,manifest:{...p,logoSvgContent:u},copiedAssets:s,generatedAssets:a,pwaIcons:this._extractPWAIcons(c)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(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(we.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(`${we.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(`${we.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(we.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(ue.logoWidth/s,ue.logoHeight/r),a=await e(t,{density:Math.ceil(72*n)}).resize(ue.logoWidth,ue.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:ue.width,height:ue.height,channels:4,background:ue.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=[],l=[];try{let i=await this.pathResolver.read(t,{format:"text"});if(!i)return{generated:[],skipped:[...n,...r].map(p=>p.name),error:"Failed to read logo.svg"};for(let p of n){let u=`${s}/${p.name}`;if(this.pathResolver.pathExists(u)){l.push(p.name);continue}try{await this.pathResolver.write(`public/${p.name}`,i),a.push(p.name)}catch(g){this.logger.debug(`Failed to copy ${p.name}: ${g.message}`),l.push(p.name)}}let c=await import("sharp").catch(()=>null);if(!c)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),l.push(...r.map(p=>p.name));else{for(let u of r){let g=`${s}/${u.name}`;if(this.pathResolver.pathExists(g)){l.push(u.name);continue}try{let d=c.default(t).resize(u.size,u.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;u.format==="ico"?h=await d.toFormat("png").toBuffer():h=await d.toFormat(u.format).toBuffer(),await this.pathResolver.write(`public/${u.name}`,h),a.push(u.name)}catch(d){this.logger.debug(`Failed to generate ${u.name}: ${d.message}`),l.push(u.name)}}let p=pe.slice(1);if(this.pathResolver.pathExists(`${s}/${p}`))l.push(p);else try{let u=await this._renderOgImage(c.default,t);await this.pathResolver.write(`public/${p}`,u),a.push(p)}catch(u){this.logger.debug(`Failed to generate ${p}: ${u.message}`),l.push(p)}}return{generated:a,skipped:l,error:null}}catch(i){return this.logger.debug(`Asset generation failed: ${i.message}`),{generated:[],skipped:requiredAssets.map(c=>c.name),error:i.message}}}};var Ze={data:null},Ye=class extends j{constructor(e={}){super(Fe,e)}getHandlerDefaults(){return{manifestPath:T.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
52
|
+
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t,{overwrite:!0}),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var X=class a{constructor(e,t={}){if(this.constructor===a)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 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 o=Date.now()-t;return this.logger.debug(`Discovery completed in ${o}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}};var ue={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Ne=class extends X{constructor(e,t={}){super(e,{assets:V.assets.fallback,assetPatterns:V.assets.patterns,frameworkPackage:Ge.package,assetsPath:Ge.assetsPath,modernFormats:V.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 o=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(o=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,c=await this._processAssetFiles(l),p=this._buildAssetManifest(c),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:c,manifest:{...p,logoSvgContent:u},copiedAssets:s,generatedAssets:o,pwaIcons:this._extractPWAIcons(c)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(n=>n.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",n=r.match(/(\d+)x(\d+)/),o=n?{width:parseInt(n[1]),height:parseInt(n[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:o,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 o=`/${e}.${n}`;if(s.includes(o))return o}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(be.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(`${be.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(),o=this._analyzeAsset(n,r.size);o&&t.push(o)}}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(o=>this._matchesPattern(e,o))?{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(`${be.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(be.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(ue.logoWidth/s,ue.logoHeight/r),o=await e(t,{density:Math.ceil(72*n)}).resize(ue.logoWidth,ue.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:ue.width,height:ue.height,channels:4,background:ue.background}}).composite([{input:o}]).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"}],o=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...n,...r].map(p=>p.name),error:"Failed to read logo.svg"};for(let p of n){let u=`${s}/${p.name}`;if(this.pathResolver.pathExists(u)){i.push(p.name);continue}try{await this.pathResolver.write(`public/${p.name}`,l),o.push(p.name)}catch(g){this.logger.debug(`Failed to copy ${p.name}: ${g.message}`),i.push(p.name)}}let c=await import("sharp").catch(()=>null);if(!c)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(p=>p.name));else{for(let u of r){let g=`${s}/${u.name}`;if(this.pathResolver.pathExists(g)){i.push(u.name);continue}try{let h=c.default(t).resize(u.size,u.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),f;u.format==="ico"?f=await h.toFormat("png").toBuffer():f=await h.toFormat(u.format).toBuffer(),await this.pathResolver.write(`public/${u.name}`,f),o.push(u.name)}catch(h){this.logger.debug(`Failed to generate ${u.name}: ${h.message}`),i.push(u.name)}}let p=pe.slice(1);if(this.pathResolver.pathExists(`${s}/${p}`))i.push(p);else try{let u=await this._renderOgImage(c.default,t);await this.pathResolver.write(`public/${p}`,u),o.push(p)}catch(u){this.logger.debug(`Failed to generate ${p}: ${u.message}`),i.push(p)}}return{generated:o,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(c=>c.name),error:l.message}}}};var Ze={data:null},Ye=class extends M{constructor(e={}){super(Ne,e)}getHandlerDefaults(){return{manifestPath:O.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
53
53
|
// Generated at: ${new Date().toISOString()}
|
|
54
54
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
55
55
|
|
|
@@ -66,7 +66,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
66
66
|
timestamp: Date.now(),
|
|
67
67
|
};
|
|
68
68
|
}
|
|
69
|
-
globalThis._DNDEV_CONFIG_.${
|
|
69
|
+
globalThis._DNDEV_CONFIG_.${J.assets} = {
|
|
70
70
|
mapping: assetConfig.manifest,
|
|
71
71
|
logoSvgContent: ${JSON.stringify(t)},
|
|
72
72
|
manifest: {
|
|
@@ -85,7 +85,7 @@ export default assetConfig;
|
|
|
85
85
|
size: ${n.size},
|
|
86
86
|
optimized: ${n.optimized||!1}
|
|
87
87
|
}`).join(`,
|
|
88
|
-
`),s=Object.entries(e.manifest).map(([n,
|
|
88
|
+
`),s=Object.entries(e.manifest).map(([n,o])=>` ${n}: ${JSON.stringify(o)}`).join(`,
|
|
89
89
|
`),r=e.manifest.logoSvgContent||null;return`// Auto-generated asset manifest by @donotdev/config
|
|
90
90
|
// Generated at ${new Date().toISOString()}
|
|
91
91
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
@@ -125,16 +125,16 @@ ${t}
|
|
|
125
125
|
export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
|
|
126
126
|
|
|
127
127
|
export default imageConfigs;
|
|
128
|
-
`}};function
|
|
128
|
+
`}};function Qt(a={}){return new Ye(a)}import Qe from"node:fs";import Pr from"node:path";var et=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!Qe.existsSync(e))return{blogDir:e,files:[]};let t;try{t=Qe.readdirSync(e)}catch{return{blogDir:e,files:[]}}let s=t.filter(r=>r.endsWith(".md")&&!r.startsWith(".")).sort();return{blogDir:e,files:s}}},tt=class extends M{constructor(e={}){super(et,e)}getHandlerDefaults(){return{outputPath:O.next.blogContent}}getHandlerName(){return"BlogContent"}createDiscovery(e){return new e(this.pathResolver)}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateSpecificFiles(e),this.logger.debug(`Generated BlogContent: ${this.getGenerationSummary(e)}`),e}catch(e){return this.logger.debug(`BlogContent generation failed (non-critical): ${e.message}`),{blogDir:"",files:[]}}}async getDiscoveryData(){return this.discovery.discoverBlogFiles()}logDiscoveryResults(e){this.logger.info(`\u{1F4DD} Blog: ${e.files.length} .md file(s) found`)}getGenerationSummary(e){return`${e.files.length} blog file(s)`}async generateSpecificFiles(e){let{blogDir:t,files:s}=e;if(s.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let r=this._buildGeneratedContent(t,s);this.writeGeneratedFile(this.options.outputPath,r,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
129
129
|
// Regenerated when src/content/blog/*.md files change
|
|
130
130
|
|
|
131
131
|
const blogContent: Record<string, string> = {
|
|
132
|
-
${t.map(r=>{let n=Qe.readFileSync(
|
|
132
|
+
${t.map(r=>{let n=Qe.readFileSync(Pr.join(e,r),"utf8");return` './${r}': ${JSON.stringify(n)},`}).join(`
|
|
133
133
|
`)}
|
|
134
134
|
};
|
|
135
135
|
|
|
136
136
|
export default blogContent;
|
|
137
|
-
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function Zt(o={}){return new tt(o)}var st=class extends j{constructor(e={}){super(fe,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...$e.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:n,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
137
|
+
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function es(a={}){return new tt(a)}function xr(a){if(!a)return[];let e=R.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",a);if(!s)return[];let r=e.getDirname(e.getDirname(s)),n;try{n=e.readdirSync(r)}catch{return[]}for(let o of n)try{let i=e.resolvePath(`${o}/package.json`,r),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[c,p]of Object.entries(l.peerDependenciesMeta))p?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function Er(a){if(!a)return[];let e=R.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[n,o]of Object.entries(s.peerDependenciesMeta))o?.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 Ar(a){let e=_e.optionalFeatures||[],t=xr(a),s=Er(a);return[...new Set([...e,...t,...s])]}function _r(a){let e=R.getInstance();try{let t=e.resolvePath("package.json",a),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 kr(a,e,t){if(t.resolvePackage(a,e||void 0))return!0;let s=a.startsWith("@")?a.split("/").slice(0,2).join("/"):a.split("/")[0],r=e;for(let n=0;n<10;n++){let o=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(o))return!0;let i=t.getDirname(r);if(i===r)break;r=i}return!1}function Ce(a){let e=Ar(a),t=[],s=[],r=R.getInstance(),n=_r(a);for(let o of e)o.startsWith("@donotdev/")?n.has(o)?s.push(o):t.push(o):n.has(o)&&kr(o,a,r)?s.push(o):t.push(o);return{missing:t,installed:s}}var De=class a extends X{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=ke("i18n"),o=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(m=>{let $=m.endsWith(".json")?m:`${m}/*_*.json`;return this.pathResolver.resolveAppPath($)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let c=r.framework?.eager||[],p=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${o.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${p.join(", ")}`),c.length===0&&p.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),h=(m,$)=>{let A=this.pathResolver.normalizePath(m),D=this.pathResolver.normalizePath($);return A.startsWith(D)?A.slice(D.length+1):A},f=o.map(m=>h(m,t)),y=[...i,...l].map(m=>h(m,t)),v=c.map(m=>h(m,s)),P=p.map(m=>h(m,s)),b={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},x=await this.pathResolver._globWithNormalization(f,b),T=await this.pathResolver._globWithNormalization(y,b),C={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:n.ignore?.filter(m=>m!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(C.ignore)}`);let _=await this.pathResolver._globWithNormalization(v,C),j=await this.pathResolver._globWithNormalization(P,C);this.logger.debug(`Found ${x.length} eager, ${T.length} lazy, ${_.length} framework eager, ${j.length} framework lazy files`),_.length>0?this.logger.debug(`Framework eager files (first 3): ${_.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),j.length>0?this.logger.debug(`Framework lazy files (first 3): ${j.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${p.join(", ")}`);let re=[...new Set([...x,...T,..._,...j])],ee=new Set([...x,..._]),d={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:ne}=Ce(t),E=new Set(ne.filter(m=>m.startsWith("@donotdev/")).map(m=>m.replace("@donotdev/","")));E.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...E].join(", ")}] (packages not installed)`);let K=new Map,z=[..._,...j];for(let m of z){let $=this._processTranslationFile(m,_.includes(m),t);if($){if(E.has($.namespace))continue;let A=`${$.namespace}_${$.language}`;K.set(A,$),d.allNamespaces.add($.namespace),d.supportedLanguages.add($.language),_.includes(m)&&d.eagerNamespaces.add($.namespace)}}let U=new Set;for(let m of re){if(z.includes(m))continue;let $=this._processTranslationFile(m,ee.has(m),t);if($){let{namespace:A,language:D,importPath:q,content:le}=$,Ee=`${$.namespace}_${$.language}`;if(K.has(Ee)){let Me=K.get(Ee);$.content=this._mergeTranslations(Me.content,le)}d.allNamespaces.add(A),d.supportedLanguages.add(D),U.add(D),ee.has(m)&&d.eagerNamespaces.add(A),d.mapping[A]||(d.mapping[A]={}),d.mapping[A][D]=q,$.content&&(d.content[A]||(d.content[A]={}),d.content[A][D]=$.content),d.files.push({path:m,relativePath:this.pathResolver.getRelativePath(m),namespace:A,language:D,eager:ee.has(m),size:$.content?JSON.stringify($.content).length:0})}}for(let[m,$]of K){let A=m.lastIndexOf("_"),D=m.slice(0,A),q=m.slice(A+1);U.size>0&&!U.has(q)||(!d.mapping[D]||!d.mapping[D][q])&&(d.mapping[D]||(d.mapping[D]={}),d.mapping[D][q]=$.importPath,d.content[D]||(d.content[D]={}),d.content[D][q]=$.content,d.files.push({path:$.absolutePath,relativePath:this.pathResolver.getRelativePath($.absolutePath),namespace:D,language:q,eager:d.eagerNamespaces.has(D),size:$.content?JSON.stringify($.content).length:0}))}let W=U.size>0?[...U].sort():[this.options.fallbackLanguage],N=this._getLanguageAllowlist(),k=W;if(N){let m=W.filter(A=>N.includes(A));k=m.length>0?m:[this.options.fallbackLanguage],this._restrictByLanguage(d.mapping,k),this._restrictByLanguage(d.content,k),d.files=d.files.filter(A=>k.includes(A.language));let $=new Set(Object.keys(d.mapping));d.allNamespaces=new Set([...d.allNamespaces].filter(A=>$.has(A))),d.eagerNamespaces=new Set([...d.eagerNamespaces].filter(A=>$.has(A))),this.logger.debug(`I18n restricted by i18n.only [${N.join(", ")}]: languages [${k.join(", ")}], namespaces ${$.size}`)}let te=[...new Set(k.map(m=>a.LANGUAGE_FLAG_OVERRIDES[m]||m))];return{mapping:d.mapping,content:d.content,eagerNamespaces:[...d.eagerNamespaces].sort(),allNamespaces:[...d.allNamespaces].sort(),supportedLanguages:k,fallbackLanguage:this.options.fallbackLanguage,flagCodes:te,files:d.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[a.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,o,i=r.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,n,o]=i,!n||!o)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),p;try{if(p=this.pathResolver.readSync(e,{format:"json"}),!p)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:n,language:o,importPath:c,absolutePath:e,content:p}}_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}};var st=class extends M{constructor(e={}){super(De,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...$e.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:n,content:o}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
138
138
|
// Generated at: ${new Date().toISOString()}
|
|
139
139
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
140
140
|
|
|
@@ -143,7 +143,7 @@ const i18nConfig = {
|
|
|
143
143
|
languages: ${JSON.stringify(s,null,2)},
|
|
144
144
|
eager: ${JSON.stringify(r,null,2)},
|
|
145
145
|
fallback: '${n}',
|
|
146
|
-
content: ${JSON.stringify(
|
|
146
|
+
content: ${JSON.stringify(o||{},null,2)},
|
|
147
147
|
storage: {
|
|
148
148
|
type: 'localStorage',
|
|
149
149
|
prefix: 'dndev_i18n_',
|
|
@@ -176,12 +176,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
176
176
|
timestamp: Date.now(),
|
|
177
177
|
};
|
|
178
178
|
}
|
|
179
|
-
globalThis._DNDEV_CONFIG_.${
|
|
179
|
+
globalThis._DNDEV_CONFIG_.${J.i18n} = i18nConfig;
|
|
180
180
|
}
|
|
181
181
|
|
|
182
182
|
// Export for compatibility
|
|
183
183
|
export default i18nConfig;
|
|
184
|
-
`}};function
|
|
184
|
+
`}};function ts(a={}){return new st(a)}var Te=class extends X{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 o=await this._analyzePWAFiles(r),i=o.filter(g=>g.type==="manifest"||g.type==="service-worker");n.push(...i);let l=o.filter(g=>g.type==="icon"),c=new Set(n.filter(g=>g.type==="icon").map(g=>g.path)),p=l.filter(g=>!c.has(g.path));n.push(...p);let u=this._generatePWAManifest(n);return{assets:n,manifest:u,totalFiles:r.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let s of e){let r=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,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||[],o=JSON.stringify(n,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
185
185
|
// Generated at ${new Date().toISOString()}
|
|
186
186
|
|
|
187
187
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -197,7 +197,7 @@ ${r?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
|
|
|
197
197
|
cleanupOutdatedPrecaches();
|
|
198
198
|
|
|
199
199
|
// Precache static assets
|
|
200
|
-
const precacheManifest = ${
|
|
200
|
+
const precacheManifest = ${o.length>2?o:"self.__WB_MANIFEST || []"};
|
|
201
201
|
precacheAndRoute(precacheManifest);
|
|
202
202
|
|
|
203
203
|
// Runtime caching strategies
|
|
@@ -215,23 +215,23 @@ self.addEventListener('message', (event) => {
|
|
|
215
215
|
self.addEventListener('activate', (event) => {
|
|
216
216
|
event.waitUntil(self.clients.claim());
|
|
217
217
|
});
|
|
218
|
-
`}_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:
|
|
219
|
-
maxEntries: ${
|
|
220
|
-
maxAgeSeconds: ${
|
|
221
|
-
})`),
|
|
222
|
-
statuses: ${JSON.stringify(
|
|
223
|
-
})`),
|
|
224
|
-
maxRetentionTime: ${
|
|
225
|
-
})`);let u="";return
|
|
226
|
-
cacheName: '${
|
|
218
|
+
`}_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:o,options:i={}}=s,l=o==="CacheFirst"?"CacheFirst":o==="NetworkFirst"?"NetworkFirst":o==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",c;typeof n=="function"?c="({ request }) => request.destination === 'document'":n instanceof RegExp?c=n.toString():c=JSON.stringify(n);let p=[];i.expiration&&p.push(`new ExpirationPlugin({
|
|
219
|
+
maxEntries: ${i.expiration.maxEntries||50},
|
|
220
|
+
maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
|
|
221
|
+
})`),i.cacheableResponse&&p.push(`new CacheableResponsePlugin({
|
|
222
|
+
statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
|
|
223
|
+
})`),i.backgroundSync&&p.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
|
|
224
|
+
maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
|
|
225
|
+
})`);let u="";return i.cacheName&&(u+=`
|
|
226
|
+
cacheName: '${i.cacheName}',`),p.length>0&&(u+=`
|
|
227
227
|
plugins: [
|
|
228
228
|
${p.join(`,
|
|
229
229
|
`)}
|
|
230
|
-
],`),
|
|
231
|
-
networkTimeoutSeconds: ${
|
|
230
|
+
],`),i.networkTimeoutSeconds&&(u+=`
|
|
231
|
+
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${i.cacheName||"cache-"+r}
|
|
232
232
|
registerRoute(
|
|
233
233
|
${c},
|
|
234
|
-
new ${
|
|
234
|
+
new ${l}({${u}
|
|
235
235
|
})
|
|
236
236
|
);`}).join(`
|
|
237
237
|
|
|
@@ -249,7 +249,7 @@ registerRoute(
|
|
|
249
249
|
}),
|
|
250
250
|
'POST'
|
|
251
251
|
);
|
|
252
|
-
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),n=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let l of a){let i=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),l.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let c of i){let p=this.pathResolver.getRelativePath(c);if(p.startsWith(`${e}/static/`)){let u=`/_next/${p.replace(`${e}/static/`,"")}`;n.push({url:u,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()}};var rt=class extends j{constructor(e={}){super(Te,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/pwa-manifest.json",webManifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Ze.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(this.options.generateManifest&&await this.generatePWAManifest(e),!this.options.enabled){this.logger.debug("PWA disabled, skipping service worker generation");return}this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.webManifestPath,t,"web app manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let n=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(n,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:n,webpack:a}=s;return this.applyViteIgnorePlugin(t,a),!r&&!n&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function es(o={}){return new rt(o)}import{createRequire as _r}from"node:module";function ts(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,(i,c)=>`icon: '${c}'`);let n=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...o.matchAll(n)].forEach(i=>{let c=i[1],p=i[2];r=r.replace(new RegExp(`\\b${c}\\b`,"g"),`'${p}'`)}),Function(`return ${r}`)()}catch{return null}}var Pe=null,ss=null;function xr(o){let t=(o.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Er(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 me=class extends K{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(Pe&&ss===s)return this.logger.debug("Using cached route discovery results"),this.routes=Pe.routes,this.errors=Pe.errors,this.source=Pe.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/"),Pe={routes:this.routes,errors:this.errors,source:this.source},ss=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,c=>this._analyzePageFile(c,t)),n=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(n,c=>this._analyzePageFile(c,t)),l=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${n.length} additional files`),this.routes=l.filter(c=>c.path==="home"||c.path==="/home"?(this.logger.debug(`Filtered reserved route: ${c.path} - Use root "/" instead (${c.file})`),!1):!0);let i=new Map;for(let c of this.routes){let p=c.path;if(i.has(p)){let u=i.get(p);throw new Error(`Route conflict: Multiple routes found for path '${p}'. Routes: ${u.file} and ${c.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}i.set(p,c),Er(c)}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),l=xr(n),c=l===be.HOMEPAGE_COMPONENT?be.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),p=this._extractPageMeta(r,s),{entity:u,action:g,...d}=a||{};return{path:c,component:l,importPath:n,auth:a?.auth||!1,meta:{...p,...d,entity:p.entity,action:p.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=ts(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(l=>`:${l}`).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,l=null;return n.length>1&&(a=n[n.length-2],s.includes("List")?l="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?l="form":(s.includes("Detail")||s.includes("View"))&&(l="detail")),{title:r,entity:a,action:l,file:e}}};function Ar(o,e,t="configuration-error",s={}){let r=`[${o}] ${e}`,n=new Error(r);return n.code=t,n.pluginName=o,n.context=s,n}function rs(o,e,t,s={}){return Ar(o,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function nt(o,e,t,s){try{if(t?.content?.[o]?.[e])return t.content[o][e];let r=t?.mapping?.[o]?.[e];if(!r)return null;let n=s.resolveAppPath(r),a=s.readSync(n,{format:"text"});return a?JSON.parse(a):null}catch{return null}}function Oe(o,e){if(!o||!e)return;let t=e.split("."),s=o;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function ot(o){return o?.languages||o?.supportedLanguages||["en"]}function at(o){return o?.fallback||o?.fallbackLanguage||"en"}var it=class extends j{constructor(e={}){super(me,e),this.rendersSessionTree=!1,this.appRouteSegments=[]}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,proxyPath:T.next.proxy,manifestPath:T.next.routeManifest,languages:[],defaultLanguage:null}}useLanguages({languages:e,defaultLanguage:t}){if(e.length>1&&!e.includes(t))throw new Error(`i18n fallbackLanguage "${t}" has no translations among [${e.join(", ")}]: it is the language served at the root URL. Add its locale files or set i18n.fallbackLanguage to one of them.`);this.options.languages=e,this.options.defaultLanguage=t}isMultilingual(){return this.options.languages.length>1}rootDir(){return this.isMultilingual()?"/[lang]":""}treeDir(e="site"){return`${this.rootDir()}/${e==="session"?B.sessionSegment:B.siteGroup}`}appDirFor(e,t="site"){return`${this.treeDir(t)}${this.convertRouteToAppPath(e)}`}appImport(e,t){let s=e.split("/").filter(Boolean).length;return s===0?`./${t}`:`${"../".repeat(s)}${t}`}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(n=>n.auth&&n.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
252
|
+
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),n=[];try{let o=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let i of o){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let c of l){let p=this.pathResolver.getRelativePath(c);if(p.startsWith(`${e}/static/`)){let u=`/_next/${p.replace(`${e}/static/`,"")}`;n.push({url:u,revision:null})}}}}catch(o){this.logger?.warn(`Failed to discover Next.js build assets: ${o.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()}};var rt=class extends M{constructor(e={}){super(Te,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/pwa-manifest.json",webManifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Ze.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(this.options.generateManifest&&await this.generatePWAManifest(e),!this.options.enabled){this.logger.debug("PWA disabled, skipping service worker generation");return}this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.webManifestPath,t,"web app manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let n=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(n,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:n,webpack:o}=s;return this.applyViteIgnorePlugin(t,o),!r&&!n&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function ss(a={}){return new rt(a)}import{createRequire as Tr}from"node:module";function rs(a,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=a.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,c)=>`icon: '${c}'`);let n=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(n)].forEach(l=>{let c=l[1],p=l[2];r=r.replace(new RegExp(`\\b${c}\\b`,"g"),`'${p}'`)}),Function(`return ${r}`)()}catch{return null}}var Re=null,ns=null;function Nr(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Cr(a){let e=a.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw new Error(`PageMeta signedInRedirect in ${a.file} must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`);if(e.split(/[?#]/)[0]===a.path)throw new Error(`PageMeta signedInRedirect in ${a.file} points at the page itself (${e}): signed-in visitors would loop. Use another page.`)}}var de=class extends X{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(Re&&ns===s)return this.logger.debug("Using cached route discovery results"),this.routes=Re.routes,this.errors=Re.errors,this.source=Re.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/"),Re={routes:this.routes,errors:this.errors,source:this.source},ns=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,c=>this._analyzePageFile(c,t)),n=await this._scanAdditionalPatterns(t),o=await this._batchProcessFiles(n,c=>this._analyzePageFile(c,t)),i=[...r,...o];this.logger.debug(`Auto-discovering from ${s.length} app + ${n.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 p=c.path;if(l.has(p)){let u=l.get(p);throw new Error(`Route conflict: Multiple routes found for path '${p}'. Routes: ${u.file} and ${c.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}l.set(p,c),Cr(c)}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 o=this._extractMetaExport(s,e.absolutePath),i=Nr(n),c=i===ye.HOMEPAGE_COMPONENT?ye.HOMEPAGE_PATH:this._resolveRoutePath(o,r,e.absolutePath),p=this._extractPageMeta(r,s),{entity:u,action:g,...h}=o||{};return{path:c,component:i,importPath:n,auth:o?.auth||!1,meta:{...p,...h,entity:p.entity,action:p.action},metaExport:o,file:r}}_extractMetaExport(e,t){try{let s=rs(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 o=n.map(i=>`:${i}`).join("/");return`${r}/${o}`}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("/"),o=null,i=null;return n.length>1&&(o=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:o,action:i,file:e}}};function Dr(a,e,t="configuration-error",s={}){let r=`[${a}] ${e}`,n=new Error(r);return n.code=t,n.pluginName=a,n.context=s,n}function os(a,e,t,s={}){return Dr(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function nt(a,e,t,s){try{if(t?.content?.[a]?.[e])return t.content[a][e];let r=t?.mapping?.[a]?.[e];if(!r)return null;let n=s.resolveAppPath(r),o=s.readSync(n,{format:"text"});return o?JSON.parse(o):null}catch{return null}}function Fe(a,e){if(!a||!e)return;let t=e.split("."),s=a;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function ot(a){return a?.languages||a?.supportedLanguages||["en"]}function at(a){return a?.fallback||a?.fallbackLanguage||"en"}var it=class extends M{constructor(e={}){super(de,e),this.rendersSessionTree=!1,this.appRouteSegments=[]}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,proxyPath:O.next.proxy,manifestPath:O.next.routeManifest,languages:[],defaultLanguage:null}}useLanguages({languages:e,defaultLanguage:t}){if(e.length>1&&!e.includes(t))throw new Error(`i18n fallbackLanguage "${t}" has no translations among [${e.join(", ")}]: it is the language served at the root URL. Add its locale files or set i18n.fallbackLanguage to one of them.`);this.options.languages=e,this.options.defaultLanguage=t}isMultilingual(){return this.options.languages.length>1}rootDir(){return this.isMultilingual()?"/[lang]":""}treeDir(e="site"){return`${this.rootDir()}/${e==="session"?Z.sessionSegment:Z.siteGroup}`}appDirFor(e,t="site"){return`${this.treeDir(t)}${this.convertRouteToAppPath(e)}`}appImport(e,t){let s=e.split("/").filter(Boolean).length;return s===0?`./${t}`:`${"../".repeat(s)}${t}`}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(n=>n.auth&&n.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
253
253
|
// Generated at: ${new Date().toISOString()}
|
|
254
254
|
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
255
255
|
|
|
@@ -268,7 +268,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
268
268
|
timestamp: Date.now(),
|
|
269
269
|
};
|
|
270
270
|
}
|
|
271
|
-
globalThis._DNDEV_CONFIG_.${
|
|
271
|
+
globalThis._DNDEV_CONFIG_.${J.routes} = {
|
|
272
272
|
mapping: routeMapping,
|
|
273
273
|
manifest: routeManifest,
|
|
274
274
|
};
|
|
@@ -278,21 +278,20 @@ if (typeof globalThis !== 'undefined') {
|
|
|
278
278
|
export const routes = routeMapping;
|
|
279
279
|
export const manifest = routeManifest;
|
|
280
280
|
export default { routes: routeMapping, manifest: routeManifest };
|
|
281
|
-
`}async generateSpecificFiles(e){await this.assertAppDocument(),this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=ot(t),r=at(t),n=process.env.NEXT_PUBLIC_SITE_NAME||"";if(!n)try{let
|
|
281
|
+
`}async generateSpecificFiles(e){await this.assertAppDocument(),this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=ot(t),r=at(t),n=process.env.NEXT_PUBLIC_SITE_NAME||"";if(!n)try{let l=this.pathResolver.resolveAppPath("public/seo-manifest.json");this.pathResolver.pathExists(l)&&(n=this.pathResolver.readSync(l,{format:"json"})?.siteName||"")}catch{}let o={};for(let l of e.routes){let c=l.metaExport?.namespace,p=l.metaExport?.seo||{},u={};for(let g of s){let h=c&&t&&nt(c,g,t,this.pathResolver)||nt(c,r,t,this.pathResolver),f=Fe(h,"meta")||{},w=Fe(h,"title"),y=Fe(h,"description"),v;f.fullTitle?v=f.fullTitle:p.fullTitle?v=p.fullTitle:w?v=n?`${w} | ${n}`:w:p.title?v=n?`${p.title} | ${n}`:p.title:p.title===null?v=n:v=n||"";let P;p.description===null?P=void 0:p.description?P=p.description:y&&(P=y);let b=p.image||f.image||pe,x=p.type||f.type||"website",T=p.keywords||f.keywords,C=p.noindex||!1;u[g]={title:v,...P&&{description:P},image:b,type:x,...T&&{keywords:T},...C&&{noindex:C}}}o[l.path]={locales:u,defaultLocale:r}}let i=JSON.stringify(o,null,2);this.writeGeneratedFile("public/metadata-manifest.json",i,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(o).length} routes`)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles(),this.generateRootLayout(),this.generateNotFoundPages();let t=this.rendersSessionTree?["site","session"]:["site"];for(let r of t)await this.generateTreeLayout(r);let s=0;for(let r of e.routes){let n=this.isSessionOnlyRoute(r)?"session":"site",o=await this.generateSingleAppPage(r,n);o&&s++,o&&n==="site"&&this.rendersSessionTree&&this.generateSessionPage(r)}this.logger.debug(`Successfully generated ${s}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}requestDocumentParts(e){return[[/<ClientLayout\b/,"renders <ClientLayout>"],[/from\s+['"]next\/headers['"]/,"imports next/headers"],[/export\s+const\s+dynamic\b/,"exports `dynamic`"]].filter(([t])=>t.test(e)).map(([,t])=>t)}async assertAppDocument(){let e=O.next.appDocument,t=`${e} exports \`metadata\` (site-level: metadataBase) and \`AppDocument({ lang, children })\`, which renders <html lang={lang}>, the <head> links (favicon, <FontPreloadLinks />), imports the global CSS and puts {children} in <body> (see the @donotdev/cli app-next template)`,s=[];for(let o of this.frameworkRootFiles()){let i=this.pathResolver.resolveAppPath(o);this.pathResolver.pathExists(i)&&!await this.hasGenerationMarker(i)&&s.push(o)}if(s.length>0)throw new Error(`[dndev] ${s.join(", ")}: the framework generates the root layout and the 404 pages, so every page's HTML carries its language (<html lang>). Move the HTML shell into ${e}: ${t}. Then delete ${s.join(", ")}.`);let r=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(r))throw new Error(`[dndev] ${e} is missing: ${t}.`);let n=this.requestDocumentParts(await this.pathResolver.read(r,{format:"text"}));if(n.length!==0)throw new Error(`[dndev] ${e} ${n.join(", ")}. It must be the HTML shell: render {children} in <body>, drop the ClientLayout / headers() wrapper and \`export const dynamic\`. The generated layouts render ClientLayout: cached pages for guests, per-request pages for visitors with an auth cookie.`)}frameworkRootFiles(){let e=F("layout","tsx"),t=F("not-found","tsx");return[O.next.appLayout,`src/app/[lang]/${e}`,`src/app/${t}`,`src/app/[lang]/${t}`,`src/app/${F("global-not-found","tsx")}`]}async generateTreeLayout(e){let t=`src/app${this.treeDir(e)}/${F("layout","tsx")}`,s=this.pathResolver.resolveAppPath(t);if(this.pathResolver.pathExists(s)&&!await this.hasGenerationMarker(s)){this.logger.debug(`Skipping ${t} - user-created file detected`);return}this.writeGeneratedFile(t,e==="session"?this.generateSessionLayoutContent():this.generateSiteLayoutContent(),`${e} layout`)}generateSiteLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
282
282
|
// Cached pages: rendered without request data (no cookies, no headers), served from the
|
|
283
|
-
// cache and
|
|
283
|
+
// cache and ${this.revalidateLabel()} (appConfig.revalidate). One entry per URL (page and language).
|
|
284
284
|
|
|
285
|
-
import { Suspense } from 'react';
|
|
286
285
|
import type { ReactNode } from 'react';
|
|
287
286
|
|
|
288
287
|
import { ClientLayout } from '${this.appImport(this.treeDir("site"),"ClientLayout")}';
|
|
289
288
|
|
|
290
|
-
export const revalidate = ${
|
|
289
|
+
export const revalidate = ${this.revalidate()};
|
|
291
290
|
|
|
292
291
|
export default function SiteLayout({ children }: { children: ReactNode }) {
|
|
293
292
|
return (
|
|
294
293
|
<ClientLayout serverCookies="" acceptLanguage={null}>
|
|
295
|
-
|
|
294
|
+
{children}
|
|
296
295
|
</ClientLayout>
|
|
297
296
|
);
|
|
298
297
|
}
|
|
@@ -360,6 +359,7 @@ export default function RootLayout({ children }: { children: ReactNode }) {
|
|
|
360
359
|
}
|
|
361
360
|
`}generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${F("not-found","tsx")}`,this.generateNotFoundContent(),"404 page"),this.writeGeneratedFile(`src/app/${F("global-not-found","tsx")}`,this.generateGlobalNotFoundContent(),"global 404 page")}generateNotFoundContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
362
361
|
// 404 page: the app's providers without request data (static, like every cached page).
|
|
362
|
+
// Shared fallback content must not expose the pathname captured during prerendering.
|
|
363
363
|
// The Suspense boundary keeps a query-string read (useSearchParams) to the 404 content.
|
|
364
364
|
|
|
365
365
|
import { Suspense } from 'react';
|
|
@@ -372,7 +372,7 @@ export default function NotFound() {
|
|
|
372
372
|
return (
|
|
373
373
|
<ClientLayout serverCookies="" acceptLanguage={null}>
|
|
374
374
|
<Suspense fallback={null}>
|
|
375
|
-
<NotFoundPage />
|
|
375
|
+
<NotFoundPage showRequestedPath={false} />
|
|
376
376
|
</Suspense>
|
|
377
377
|
</ClientLayout>
|
|
378
378
|
);
|
|
@@ -381,12 +381,12 @@ export default function NotFound() {
|
|
|
381
381
|
<AppDocument lang={lang}>
|
|
382
382
|
<ClientLayout serverCookies="" acceptLanguage={null}>
|
|
383
383
|
<Suspense fallback={null}>
|
|
384
|
-
<NotFoundPage />
|
|
384
|
+
<NotFoundPage showRequestedPath={false} />
|
|
385
385
|
</Suspense>
|
|
386
386
|
</ClientLayout>
|
|
387
387
|
</AppDocument>`;return this.isMultilingual()?`// Generated by @donotdev/config - DO NOT EDIT
|
|
388
388
|
// 404 of an unknown URL (no root layout above [lang]): the app's AppDocument in the URL's
|
|
389
|
-
// language, which the proxy sets on the request (${
|
|
389
|
+
// language, which the proxy sets on the request (${Z.languageHeader}); a request the proxy
|
|
390
390
|
// does not see (API route, file) gets the default language (${this.options.defaultLanguage}).
|
|
391
391
|
|
|
392
392
|
import { headers } from 'next/headers';
|
|
@@ -402,7 +402,7 @@ export { metadata } from './AppDocument';
|
|
|
402
402
|
const LANGUAGES: readonly string[] = ${JSON.stringify(this.options.languages)};
|
|
403
403
|
|
|
404
404
|
export default async function GlobalNotFound() {
|
|
405
|
-
const requested = (await headers()).get(${JSON.stringify(
|
|
405
|
+
const requested = (await headers()).get(${JSON.stringify(Z.languageHeader)});
|
|
406
406
|
const lang =
|
|
407
407
|
requested && LANGUAGES.includes(requested) ? requested : ${JSON.stringify(this.options.defaultLanguage)};
|
|
408
408
|
return (${e}
|
|
@@ -426,37 +426,37 @@ export default function GlobalNotFound() {
|
|
|
426
426
|
return (${e}
|
|
427
427
|
);
|
|
428
428
|
}
|
|
429
|
-
`}generateSessionPage(e){let t=this.appDirFor(e.path,"session"),r=`${"../".repeat(t.split("/").filter(Boolean).length)}${this.appDirFor(e.path).slice(1)}/${F("page","tsx").replace(/\.tsx$/,"")}`,n=["default"];e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path)&&n.push("generateMetadata"),this.writeGeneratedFile(`src/app${t}/${F("page","tsx")}`,`// Generated by @donotdev/config - DO NOT EDIT
|
|
429
|
+
`}isSessionOnlyRoute(e){return this.rendersSessionTree&&!!this.normalizeAuth(e.auth)}generateSessionPage(e){let t=this.appDirFor(e.path,"session"),r=`${"../".repeat(t.split("/").filter(Boolean).length)}${this.appDirFor(e.path).slice(1)}/${F("page","tsx").replace(/\.tsx$/,"")}`,n=["default"];e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path)&&n.push("generateMetadata"),this.writeGeneratedFile(`src/app${t}/${F("page","tsx")}`,`// Generated by @donotdev/config - DO NOT EDIT
|
|
430
430
|
// Per-request render of ${e.path} (visitors with an auth cookie): same page as the cached one.
|
|
431
431
|
|
|
432
432
|
export { ${n.join(", ")} } from '${r}';
|
|
433
|
-
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${F("page","tsx")}`,`src/app/**/${F("layout","tsx")}`,`src/app/**/${F("not-found","tsx")}`,`src/app/${F("global-not-found","tsx")}`,"src/app/**/*PageClient.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let n of s)if(await this.hasGenerationMarker(n))try{await this.pathResolver.remove(n),r++,this.logger.debug(`Cleaned generated file: ${n}`)}catch(
|
|
434
|
-
`:"",
|
|
433
|
+
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${F("page","tsx")}`,`src/app/**/${F("layout","tsx")}`,`src/app/**/${F("not-found","tsx")}`,`src/app/${F("global-not-found","tsx")}`,"src/app/**/*PageClient.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let n of s)if(await this.hasGenerationMarker(n))try{await this.pathResolver.remove(n),r++,this.logger.debug(`Cleaned generated file: ${n}`)}catch(o){this.logger.debug(`Could not clean file ${n}: ${o.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e,t="site"){try{let s=this.appDirFor(e.path,t),r=`src/app${s}/${F("page","tsx")}`,n=this.pathResolver.resolveAppPath(r);if(this.pathResolver.pathExists(n)&&!await this.hasGenerationMarker(n))return this.logger.debug(`Skipping ${r} - user-created file detected (no generation marker)`),!1;let o={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},i=this.generatePageFileContent(o,t);this.writeGeneratedFile(r,i,`app page: ${s}`);let l=this.extractComponentName(o.filePath),c=this.calculateRelativeImportPath(o.relativePath,o.path);return o.metaExport?.namespace==="blog"&&this.hasDynamicSegment(o.path)?this.writeGeneratedFile(`src/app${s}/BlogPostClient.tsx`,this.generateBlogPostClientContent(l,c),`app blog client: ${s}`):this.isClientComponent(o.filePath)&&this.writeGeneratedFile(`src/app${s}/${l}Client.tsx`,this.generateMountedClientContent(l,c),`app client wrapper: ${s}`),!0}catch(s){return this.logger.debug(`Error generating page for route ${e.path}: ${s.message}`),!1}}convertRouteToAppPath(e){if(e===ye.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(s=>s.startsWith(":")?`[${s.slice(1)}]`:s==="*"?"[...slug]":s).join("/")}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=Tr(t),r=s.resolve(e);delete s.cache[r];let n=s(r);return n.default||n.i18nConfig||n}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e,t="site"){let s=this.extractComponentName(e.filePath),r=e.relativePath||e.file,n=this.calculateRelativeImportPath(r,e.path);if(e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path))return this.generateBlogPostRSCContent(e,s,n);let o=this.isClientComponent(e.filePath),i=this.normalizeAuth(e.auth)?e.auth:null,l=e.meta?.signedInRedirect??null,c=[...i?["AuthGuard"]:[],...l?["SignedInRedirect"]:[]],p=c.length?`import { ${c.join(", ")} } from '@donotdev/ui';
|
|
434
|
+
`:"",u=g=>{let h=l?`<SignedInRedirect to={${JSON.stringify(l)}}>${g}</SignedInRedirect>`:g;return i?`<AuthGuard auth={${JSON.stringify(i===!0?{required:!0}:i)}}>${h}</AuthGuard>`:h};return o?`// Generated by @donotdev/config - DO NOT EDIT
|
|
435
435
|
// This file will be regenerated when src/pages changes
|
|
436
436
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
437
437
|
|
|
438
|
-
${
|
|
439
|
-
${this.onDemandParamsExport(e)}
|
|
440
|
-
export default function ${
|
|
441
|
-
return ${
|
|
438
|
+
${p}import ${s}Client from './${s}Client';
|
|
439
|
+
${t==="site"?this.onDemandParamsExport(e):""}
|
|
440
|
+
export default function ${s}Route() {
|
|
441
|
+
return ${u(`<${s}Client />`)};
|
|
442
442
|
}
|
|
443
|
-
`:
|
|
443
|
+
`:c.length?`// Generated by @donotdev/config - DO NOT EDIT
|
|
444
444
|
// This file will be regenerated when src/pages changes
|
|
445
445
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
446
446
|
|
|
447
|
-
${
|
|
448
|
-
${this.onDemandParamsExport(e)}
|
|
449
|
-
export default function ${
|
|
450
|
-
return ${
|
|
447
|
+
${p}import ${s} from '${n}';
|
|
448
|
+
${t==="site"?this.onDemandParamsExport(e):""}
|
|
449
|
+
export default function ${s}Route(props: Record<string, unknown>) {
|
|
450
|
+
return ${u(`<${s} {...props} />`)};
|
|
451
451
|
}
|
|
452
452
|
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
453
453
|
// This file will be regenerated when src/pages changes
|
|
454
454
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
455
455
|
|
|
456
|
-
import ${
|
|
457
|
-
${this.onDemandParamsExport(e)}
|
|
458
|
-
export default ${
|
|
459
|
-
`}generateMetadataFunction(e,t,s){let r=ot(s),n=at(s),
|
|
456
|
+
import ${s} from '${n}';
|
|
457
|
+
${t==="site"?this.onDemandParamsExport(e):""}
|
|
458
|
+
export default ${s};
|
|
459
|
+
`}generateMetadataFunction(e,t,s){let r=ot(s),n=at(s),o="`",i=r.map(l=>` '${l}': { href: ${o}\${baseUrl}\${currentPath}${o} }`).join(`,
|
|
460
460
|
`);return`
|
|
461
461
|
import type { Metadata } from 'next';
|
|
462
462
|
import { readFileSync } from 'node:fs';
|
|
@@ -506,7 +506,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
506
506
|
// Get base URL from environment or construct from request
|
|
507
507
|
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
|
|
508
508
|
(typeof process !== 'undefined' && process.env.VERCEL_URL
|
|
509
|
-
? ${
|
|
509
|
+
? ${o}https://\${process.env.VERCEL_URL}${o}
|
|
510
510
|
: '');
|
|
511
511
|
const currentPath = '${e.path}';
|
|
512
512
|
|
|
@@ -531,7 +531,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
531
531
|
}
|
|
532
532
|
}
|
|
533
533
|
|
|
534
|
-
const pageTitle = title ? ${
|
|
534
|
+
const pageTitle = title ? ${o}\${title} | \${siteName}${o} : siteName;
|
|
535
535
|
const pageDescription = description || '';
|
|
536
536
|
const pageImage = metaObject?.image || '${pe}';
|
|
537
537
|
const pageType = metaObject?.type || 'website';
|
|
@@ -550,7 +550,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
550
550
|
title: pageTitle,
|
|
551
551
|
...(pageDescription && { description: pageDescription }),
|
|
552
552
|
type: pageType,
|
|
553
|
-
url: ${
|
|
553
|
+
url: ${o}\${baseUrl}\${currentPath}${o},
|
|
554
554
|
...(pageImage && { images: [pageImage] }),
|
|
555
555
|
siteName: siteName,
|
|
556
556
|
},
|
|
@@ -562,36 +562,37 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
562
562
|
},
|
|
563
563
|
alternates: {
|
|
564
564
|
languages: {
|
|
565
|
-
${
|
|
565
|
+
${i}
|
|
566
566
|
},
|
|
567
567
|
},
|
|
568
568
|
};
|
|
569
569
|
|
|
570
570
|
return metadata;
|
|
571
571
|
}
|
|
572
|
-
`}generateMetadataObject(e){let t={};return e.title&&(t.title=e.title),e.description&&(t.description=e.description),(e.title||e.description)&&(t.openGraph={},e.title&&(t.openGraph.title=e.title),e.description&&(t.openGraph.description=e.description),t.openGraph.type="website"),(e.title||e.description)&&(t.twitter={card:"summary_large_image"},e.title&&(t.twitter.title=e.title),e.description&&(t.twitter.description=e.description)),Object.keys(e).forEach(s=>{["title","description"].includes(s)||(t[s]=e[s])}),JSON.stringify(t,null,2)}extractComponentName(e){let s=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return s.charAt(0).toUpperCase()+s.slice(1)}async hasGenerationMarker(e){try{let t=await this.pathResolver.read(e,{format:"text"});return t&&t.includes("// Generated by @donotdev/config")}catch{return!1}}async generateMiddleware(e){this.removeLegacyMiddleware(),this.rendersSessionTree=!1;let t=e.routes.filter(c=>!!this.normalizeAuth(c.auth)),s=e.routes.filter(c=>c.meta?.signedInRedirect),r=this.usesCookieSession();(t.length>0||s.length>0)&&!r&&this.logger.debug("Auth session not in cookies (no Supabase createBrowserClient): pages use the client AuthGuard / SignedInRedirect only, no proxy auth redirects");let n=r?t:[],
|
|
573
|
-
`),g=s.map(
|
|
574
|
-
`),
|
|
575
|
-
`),
|
|
576
|
-
session: SupabaseProxySession['session']`:"",
|
|
577
|
-
language: string`:"",
|
|
572
|
+
`}generateMetadataObject(e){let t={};return e.title&&(t.title=e.title),e.description&&(t.description=e.description),(e.title||e.description)&&(t.openGraph={},e.title&&(t.openGraph.title=e.title),e.description&&(t.openGraph.description=e.description),t.openGraph.type="website"),(e.title||e.description)&&(t.twitter={card:"summary_large_image"},e.title&&(t.twitter.title=e.title),e.description&&(t.twitter.description=e.description)),Object.keys(e).forEach(s=>{["title","description"].includes(s)||(t[s]=e[s])}),JSON.stringify(t,null,2)}extractComponentName(e){let s=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return s.charAt(0).toUpperCase()+s.slice(1)}async hasGenerationMarker(e){try{let t=await this.pathResolver.read(e,{format:"text"});return t&&t.includes("// Generated by @donotdev/config")}catch{return!1}}async generateMiddleware(e){this.removeLegacyMiddleware(),this.rendersSessionTree=!1;let t=e.routes.filter(c=>!!this.normalizeAuth(c.auth)),s=e.routes.filter(c=>c.meta?.signedInRedirect),r=this.usesCookieSession();(t.length>0||s.length>0)&&!r&&this.logger.debug("Auth session not in cookies (no Supabase createBrowserClient): pages use the client AuthGuard / SignedInRedirect only, no proxy auth redirects");let n=r?t:[],o=r?s:[],i=this.pathResolver.resolveAppPath(this.options.proxyPath),l=this.pathResolver.pathExists(i)&&!await this.hasGenerationMarker(i);if(!this.isMultilingual()&&!r){this.logger.debug("One language and no cookie session: no proxy.next.ts"),this.pathResolver.pathExists(i)&&!l&&await this.pathResolver.remove(i);return}if(l){this.logger.warn(`${this.options.proxyPath} is hand-written: not generating language routing / session refresh / auth redirects / per-request pages (add them to your proxy; every visitor gets the cached pages)`);return}this.isMultilingual()&&(this.appRouteSegments=await this.findAppRouteSegments()),this.writeGeneratedFile(this.options.proxyPath,this.generateMiddlewareContent(n,e.routes,o,r),"proxy"),this.rendersSessionTree=r}async findAppRouteSegments(){let e=this.pathResolver.getAppRoot(),t=this.pathResolver.resolveAppPath(O.next.appPages),s=await this.pathResolver._globWithNormalization([`${O.next.appPages}/**/{route,page}.${ie}.{ts,tsx,js,jsx}`],{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0}),r=new Set;for(let n of s){if(await this.hasGenerationMarker(n))continue;let[o]=n.slice(t.length+1).split("/").slice(0,-1).filter(i=>!/^\(.*\)$/.test(i));o&&o!=="[lang]"&&r.add(o)}return[...r].sort()}routePattern(e){return"^"+e.split("/").map(t=>t==="*"?".*":t.startsWith(":")?"[^/]+":t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("/")+"$"}generateMiddlewareContent(e,t=[],s=[],r=!1){let n=this.isMultilingual(),o=e.length>0,i=s.length>0,l=o||i,c=r||l,p=this.options.auth??{},u=e.map(N=>{let{role:k}=this.normalizeAuth(N.auth);return` { pattern: new RegExp(${JSON.stringify(this.routePattern(N.path))})${k?`, role: ${JSON.stringify(k)}`:""} },`}).join(`
|
|
573
|
+
`),g=s.map(N=>` { pattern: new RegExp(${JSON.stringify(this.routePattern(N.path))}), to: ${JSON.stringify(N.meta.signedInRedirect)} },`).join(`
|
|
574
|
+
`),h=[...new Set(t.map(N=>N.path))].map(N=>` new RegExp(${JSON.stringify(this.routePattern(N))}),`).join(`
|
|
575
|
+
`),f=` ${JSON.stringify("/((?!api|_next|.*\\..*).*)")},`,w=[...o?["hasRoleAccess"]:[],...n?["LANGUAGE_COOKIE",...l?["localizePath"]:[],"parseAcceptLanguage","readCookieValue","resolveLanguageRoute","splitLanguagePath"]:[]],y=["hasSupabaseSessionCookie","refreshSupabaseSession",...l?["type SupabaseProxySession"]:[]],v=l?`,
|
|
576
|
+
session: SupabaseProxySession['session']`:"",P=n?`,
|
|
577
|
+
language: string`:"",b=c?"{ request }":"",x=`/${Z.sessionSegment}`,T=`// Generated by @donotdev/config - DO NOT EDIT
|
|
578
578
|
// Request gate (Next 16 proxy)${n?`: one URL per language, the default language (${this.options.defaultLanguage}) at the
|
|
579
579
|
// root, the others under their prefix (resolveLanguageRoute in @donotdev/core)`:""}.${c?`
|
|
580
580
|
// Session: the Supabase cookie (createBrowserClient). No auth cookie: signed out, the
|
|
581
581
|
// page comes from the cache (src/app${this.treeDir("site")}, static). With one: verified and refreshed
|
|
582
582
|
// when expired (refreshSupabaseSession), then rendered per request with the refreshed
|
|
583
583
|
// cookies (src/app${this.rootDir()}${x}, an internal path: a direct hit is a 404); the browser
|
|
584
|
-
// gets the refreshed cookies on the response.`:""}${
|
|
584
|
+
// gets the refreshed cookies on the response.`:""}${o?`
|
|
585
585
|
// Auth redirects for pages whose PageMeta sets \`auth\`, on the verified session.
|
|
586
586
|
// Redirect gate only: data access stays enforced by RLS, and the page's AuthGuard still
|
|
587
|
-
// runs on the client
|
|
587
|
+
// runs on the client. Those pages have no cached copy: rendered per request for every
|
|
588
|
+
// visitor that is not redirected.`:""}${i?"\n// Signed-in redirects for pages whose PageMeta sets `signedInRedirect` (verified\n// session); the page's SignedInRedirect still runs on the client.":""}
|
|
588
589
|
|
|
589
590
|
import { NextResponse } from 'next/server';
|
|
590
591
|
import type { NextRequest } from 'next/server';
|
|
591
592
|
|
|
592
593
|
${w.length?`import { ${w.join(", ")} } from '@donotdev/core/server';
|
|
593
|
-
`:""}${c?`import { ${
|
|
594
|
-
`:""}`,
|
|
594
|
+
`:""}${c?`import { ${y.join(", ")} } from '@donotdev/supabase/server';
|
|
595
|
+
`:""}`,C=c?`
|
|
595
596
|
/** Supabase project of the cookie session (same env as src/config/providers.ts) */
|
|
596
597
|
const SUPABASE = supabaseProject(
|
|
597
598
|
process.env.NEXT_PUBLIC_SUPABASE_URL,
|
|
@@ -608,7 +609,7 @@ function supabaseProject(url: string | undefined, publicKey: string | undefined)
|
|
|
608
609
|
}
|
|
609
610
|
${n?`
|
|
610
611
|
/** Internal tree of the per-request pages (src/app/[lang]${x}), after the language: never a public URL */
|
|
611
|
-
const SESSION_SEGMENT = ${JSON.stringify(
|
|
612
|
+
const SESSION_SEGMENT = ${JSON.stringify(Z.sessionSegment)};
|
|
612
613
|
|
|
613
614
|
/** Internal URL path of a page rendered per request: \`/fr/compte\` \u2192 \`/fr${x}/compte\` */
|
|
614
615
|
function sessionPath(path: string): string {
|
|
@@ -633,10 +634,10 @@ function sessionPath(path: string): string {
|
|
|
633
634
|
function isSessionTreePath(pathname: string): boolean {
|
|
634
635
|
return pathname === SESSION_TREE || pathname.startsWith(\`\${SESSION_TREE}/\`);
|
|
635
636
|
}
|
|
636
|
-
`}${
|
|
637
|
+
`}${l?`
|
|
637
638
|
/** Session of a request without an auth cookie: signed out, nothing to verify */
|
|
638
639
|
const SIGNED_OUT: SupabaseProxySession['session'] = { user: null };
|
|
639
|
-
`:""}`:"",_=
|
|
640
|
+
`:""}`:"",_=o?`
|
|
640
641
|
/** appConfig.auth.authRoute: where a signed-out visitor goes (null: page fallback) */
|
|
641
642
|
const AUTH_ROUTE: string | null = ${JSON.stringify(p.authRoute??null)};
|
|
642
643
|
/** appConfig.auth.roleRoute: where a visitor without the role goes (null: page fallback) */
|
|
@@ -646,10 +647,15 @@ const protectedRoutes: Array<{ pattern: RegExp; role?: string }> = [
|
|
|
646
647
|
${u}
|
|
647
648
|
];
|
|
648
649
|
|
|
650
|
+
/** Protected pages exist only in the per-request tree (no cached copy) */
|
|
651
|
+
function isProtectedRoute(routePath: string): boolean {
|
|
652
|
+
return protectedRoutes.some((r) => r.pattern.test(routePath));
|
|
653
|
+
}
|
|
654
|
+
|
|
649
655
|
/** Redirect of a protected route, or null to let the page render. */
|
|
650
656
|
function authRedirect(
|
|
651
|
-
request: NextRequest${
|
|
652
|
-
routePath: string${
|
|
657
|
+
request: NextRequest${v},
|
|
658
|
+
routePath: string${P}
|
|
653
659
|
): NextResponse | null {
|
|
654
660
|
const route = protectedRoutes.find((r) => r.pattern.test(routePath));
|
|
655
661
|
if (!route) return null;
|
|
@@ -668,7 +674,7 @@ function authRedirect(
|
|
|
668
674
|
}
|
|
669
675
|
return null;
|
|
670
676
|
}
|
|
671
|
-
`:"",
|
|
677
|
+
`:"",j=i?`
|
|
672
678
|
/** PageMeta \`signedInRedirect\`: where a signed-in visitor of the page goes */
|
|
673
679
|
const signedInRoutes: Array<{ pattern: RegExp; to: string }> = [
|
|
674
680
|
${g}
|
|
@@ -676,8 +682,8 @@ ${g}
|
|
|
676
682
|
|
|
677
683
|
/** Redirect of a signed-in visitor, or null to let the page render. */
|
|
678
684
|
function signedInRedirect(
|
|
679
|
-
request: NextRequest${
|
|
680
|
-
routePath: string${
|
|
685
|
+
request: NextRequest${v},
|
|
686
|
+
routePath: string${P}
|
|
681
687
|
): NextResponse | null {
|
|
682
688
|
const route = signedInRoutes.find((r) => r.pattern.test(routePath));
|
|
683
689
|
if (!route) return null;
|
|
@@ -694,29 +700,30 @@ const LANGUAGE_ROUTING = {
|
|
|
694
700
|
};
|
|
695
701
|
|
|
696
702
|
/** Request header of the URL's language, read by the 404 page (src/app/global-not-found) */
|
|
697
|
-
const LANGUAGE_HEADER = ${JSON.stringify(
|
|
703
|
+
const LANGUAGE_HEADER = ${JSON.stringify(Z.languageHeader)};
|
|
698
704
|
|
|
699
705
|
/** First URL segments of the app's hand-written routes outside src/app/[lang] (route handlers) */
|
|
700
706
|
const APP_ROUTE_SEGMENTS: readonly string[] = ${JSON.stringify(this.appRouteSegments)};
|
|
701
707
|
`:"",ee=n||c?`
|
|
702
708
|
/** App pages (src/pages): API routes, files and hand-written app routes pass untouched */
|
|
703
709
|
const pageRoutes: RegExp[] = [
|
|
704
|
-
${
|
|
710
|
+
${h}
|
|
705
711
|
];
|
|
706
|
-
`:"",
|
|
707
|
-
request: NextRequest${
|
|
712
|
+
`:"",d=l?"session, ":"",ne=" // Verified session, refreshed when expired: the redirects and the server render\n // (refreshed cookies forwarded with `request`) see the same signed-in state\n const auth = await refreshSupabaseSession(request, SUPABASE.url, SUPABASE.publicKey);",E=`
|
|
713
|
+
request: NextRequest${v}${c?`,
|
|
708
714
|
personal: boolean`:""}
|
|
709
|
-
`,
|
|
710
|
-
const redirect = authRedirect(request, ${
|
|
715
|
+
`,K=(N,k)=>`${o?`
|
|
716
|
+
const redirect = authRedirect(request, ${d}${N}${k});
|
|
711
717
|
if (redirect) return redirect;
|
|
712
|
-
`:""}${
|
|
713
|
-
const signedIn = signedInRedirect(request, ${
|
|
718
|
+
`:""}${i?`
|
|
719
|
+
const signedIn = signedInRedirect(request, ${d}${N}${k});
|
|
714
720
|
if (signedIn) return signedIn;
|
|
715
|
-
`:""}`,z=k=>c?`
|
|
716
|
-
// Auth cookie: rendered per request with the visitor's cookies
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
721
|
+
`:""}`,z=(N,k)=>c?`
|
|
722
|
+
// Auth cookie: rendered per request with the visitor's cookies${o?`. Protected pages
|
|
723
|
+
// have no cached copy: per request for every visitor`:""}
|
|
724
|
+
if (personal${o?` || isProtectedRoute(${k})`:""}) {${N==="pathname"?"":`
|
|
725
|
+
const page = ${N};`}
|
|
726
|
+
return NextResponse.rewrite(new URL(sessionPath(${N==="pathname"?"pathname":"page"}) + search, request.url), { request });
|
|
720
727
|
}`:"",U;n?U=`
|
|
721
728
|
/** Language routing, redirects and render tree of a page request. */
|
|
722
729
|
function route(${E}): NextResponse {
|
|
@@ -752,11 +759,11 @@ function route(${E}): NextResponse {
|
|
|
752
759
|
decision.permanent ? 308 : 307
|
|
753
760
|
);
|
|
754
761
|
}
|
|
755
|
-
${
|
|
762
|
+
${K("decision.path",", decision.language")}${z("decision.type === 'rewrite' ? decision.destination : pathname","decision.path")}
|
|
756
763
|
if (decision.type === 'rewrite') {
|
|
757
764
|
return NextResponse.rewrite(new URL(decision.destination + search, request.url)${c?", { request }":""});
|
|
758
765
|
}
|
|
759
|
-
return NextResponse.next(${
|
|
766
|
+
return NextResponse.next(${b});
|
|
760
767
|
}
|
|
761
768
|
`:U=`
|
|
762
769
|
/** Redirects and render tree of a page request. */
|
|
@@ -765,10 +772,10 @@ function route(${E}): NextResponse {
|
|
|
765
772
|
if (!pageRoutes.some((pattern) => pattern.test(pathname))) {
|
|
766
773
|
return NextResponse.next({ request });
|
|
767
774
|
}
|
|
768
|
-
${
|
|
775
|
+
${K("pathname","")}${z("pathname","pathname")}
|
|
769
776
|
return NextResponse.next({ request });
|
|
770
777
|
}
|
|
771
|
-
`;let
|
|
778
|
+
`;let W;return c?W=`
|
|
772
779
|
export async function proxy(request: NextRequest) {
|
|
773
780
|
if (isSessionTreePath(request.nextUrl.pathname)) {
|
|
774
781
|
return new NextResponse(null, { status: 404 });
|
|
@@ -776,27 +783,27 @@ export async function proxy(request: NextRequest) {
|
|
|
776
783
|
// No auth cookie: signed out. Nothing to verify or refresh, no cookie written: the
|
|
777
784
|
// page is served from the cache.
|
|
778
785
|
if (!hasSupabaseSessionCookie(request)) {
|
|
779
|
-
return route(request${
|
|
786
|
+
return route(request${l?", SIGNED_OUT":""}, false);
|
|
780
787
|
}
|
|
781
788
|
|
|
782
789
|
${ne}
|
|
783
790
|
// Signed in, or cannot tell (Supabase unreachable): per-request render. Signed out
|
|
784
791
|
// (refresh failed, session revoked): the cached page, with the cleared cookies.
|
|
785
|
-
return auth.apply(route(request, ${
|
|
792
|
+
return auth.apply(route(request, ${l?"auth.session, ":""}auth.session?.user !== null));
|
|
786
793
|
}
|
|
787
|
-
${U}`:
|
|
794
|
+
${U}`:W=`
|
|
788
795
|
export function proxy(request: NextRequest) {
|
|
789
796
|
return route(request);
|
|
790
797
|
}
|
|
791
|
-
${U}`,`${
|
|
798
|
+
${U}`,`${T}${C}${re}${ee}${_}${j}${W}
|
|
792
799
|
export const config = {
|
|
793
800
|
matcher: [
|
|
794
|
-
${
|
|
801
|
+
${f}
|
|
795
802
|
],
|
|
796
803
|
};
|
|
797
|
-
`}normalizeAuth(e){return e===!0?{}:!e||typeof e!="object"||!e.required&&!e.role&&!e.tier?null:{role:e.role,tier:e.tier}}usesCookieSession(){try{let e=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"));if(!{...e.dependencies,...e.devDependencies}["@donotdev/supabase"])return!1;let s=this.pathResolver.resolveAppPath("src/config/providers.ts");return this.pathResolver.pathExists(s)?this.pathResolver.readSync(s).includes("createBrowserClient("):!1}catch(e){return this.logger.debug(`Cookie session detection failed: ${e.message}`),!1}}removeLegacyMiddleware(){for(let e of["middleware.ts","src/middleware.ts"]){let t=this.pathResolver.resolveAppPath(e);try{this.pathResolver.pathExists(t)&&this.pathResolver.readSync(t).startsWith("// Auto-generated middleware by @donotdev/config")&&(this.pathResolver.removeSync(t),this.logger.debug(`Removed legacy generated ${e}`))}catch(s){this.logger.debug(`Could not remove legacy ${e}: ${s.message}`)}}}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),n=s.relativePath||s.file;if(!n)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let
|
|
804
|
+
`}normalizeAuth(e){return e===!0?{}:!e||typeof e!="object"||!e.required&&!e.role&&!e.tier?null:{role:e.role,tier:e.tier}}usesCookieSession(){try{let e=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"));if(!{...e.dependencies,...e.devDependencies}["@donotdev/supabase"])return!1;let s=this.pathResolver.resolveAppPath("src/config/providers.ts");return this.pathResolver.pathExists(s)?this.pathResolver.readSync(s).includes("createBrowserClient("):!1}catch(e){return this.logger.debug(`Cookie session detection failed: ${e.message}`),!1}}removeLegacyMiddleware(){for(let e of["middleware.ts","src/middleware.ts"]){let t=this.pathResolver.resolveAppPath(e);try{this.pathResolver.pathExists(t)&&this.pathResolver.readSync(t).startsWith("// Auto-generated middleware by @donotdev/config")&&(this.pathResolver.removeSync(t),this.logger.debug(`Removed legacy generated ${e}`))}catch(s){this.logger.debug(`Could not remove legacy ${e}: ${s.message}`)}}}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),n=s.relativePath||s.file;if(!n)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let o=n.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
|
|
798
805
|
path: '${s.path}',
|
|
799
|
-
component: lazy(() => import('${
|
|
806
|
+
component: lazy(() => import('${o}')),
|
|
800
807
|
auth: ${JSON.stringify(s.auth)},
|
|
801
808
|
meta: ${JSON.stringify(s.meta)}
|
|
802
809
|
}`}).filter(s=>s!==null).join(`,
|
|
@@ -1030,9 +1037,9 @@ export default async function BlogPostRoute({ params }: { params: Params }) {
|
|
|
1030
1037
|
);
|
|
1031
1038
|
}
|
|
1032
1039
|
`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let s=this.pathResolver.readSync(t);return s?s.split(`
|
|
1033
|
-
`).slice(0,50).some(n=>n.trim()==="'use client';"||n.trim()==='"use client";'):!1}catch{return!1}}};function
|
|
1034
|
-
`)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:n,changefreq:
|
|
1035
|
-
<image:loc>${L(this.options.baseUrl)}${L(
|
|
1040
|
+
`).slice(0,50).some(n=>n.trim()==="'use client';"||n.trim()==='"use client";'):!1}catch{return!1}}};function as(a={}){return new it(a)}function L(a){return a?a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}function is(a){return a?a.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Fr=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function cs(a,e){let t;try{let s=new URL(a);if(s.protocol!=="https:"&&s.protocol!=="http:")throw new Error;t=s.hostname}catch{throw new Error(`[dndev] SEO: base URL "${a}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(Fr.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: production build with base URL "${a}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}function ls(a){return a.auth&&a.auth!==!1?!1:a.meta?.seo?.noindex!==!0}var Oe=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:n,siteName:o,crawlDelay:i=1,aiCrawlers:l="recommended",routes:c={},...p}=e;if(!n||!o)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:n,siteName:o,crawlDelay:i,aiCrawlers:l,routes:c,defaultImage:pe,twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=G("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(),o={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&&(o.robotsTxt=await this.generateRobotsTxt(r,t)),this.options.generateSitemap&&(o.sitemap=await this.generateSitemap(r,t,n)),n.length>0&&(o.rss=await this.generateRSSFeed(n,t)),o.manifest=await this.generateManifest(r,t),o}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 o=n.path.startsWith("/")?n.path:`/${n.path}`;s.push(o)}}),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=>!(!ls(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 o=this.generateSitemapContent(n);return await t("sitemap.xml",o),{fileName:"sitemap.xml",content:o,publicRoutes:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:s}=this.options,r=[];for(let n of e||[]){if(!ls(n)||typeof n.path!="string")continue;let o=n.path===s||n.path.startsWith(`${s}/`);if(!(t.length>0&&o))if(n.path.includes(":")){if(o)continue;r.push({path:n.path,...n.meta?.entity&&{collection:n.meta.entity}})}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,o=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...s.map(c=>`Disallow: ${o(c)}`),...t.map(c=>`Allow: ${o(c)}`)];n&&i.push(`Crawl-delay: ${n}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Or(l))),i.join(`
|
|
1041
|
+
`)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:n,changefreq:o,priority:i,image:l})=>{let c=[` <loc>${L(this.options.baseUrl)}${L(r)}</loc>`];return n&&c.push(` <lastmod>${n}</lastmod>`),o&&c.push(` <changefreq>${o}</changefreq>`),i&&c.push(` <priority>${i}</priority>`),l&&c.push(` <image:image>
|
|
1042
|
+
<image:loc>${L(this.options.baseUrl)}${L(l)}</image:loc>
|
|
1036
1043
|
</image:image>`),` <url>
|
|
1037
1044
|
${c.join(`
|
|
1038
1045
|
`)}
|
|
@@ -1041,12 +1048,12 @@ ${c.join(`
|
|
|
1041
1048
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
|
|
1042
1049
|
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
|
|
1043
1050
|
${s}
|
|
1044
|
-
</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(
|
|
1045
|
-
`)){let
|
|
1046
|
-
<title><![CDATA[${
|
|
1051
|
+
</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=R.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 o=e.resolvePath(n,t),i=e.readSync(o,{format:"text"}),l=n.replace(/_en\.md$/,""),c=i.match(/^---\r?\n([\s\S]*?)\r?\n---/),p={};if(c)for(let g of c[1].split(`
|
|
1052
|
+
`)){let h=g.indexOf(":");h!==-1&&(p[g.slice(0,h).trim()]=g.slice(h+1).trim())}let u=p.date;if(!u)try{u=e.statSync(o).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no frontmatter date, using file mtime (${u})`)}catch{u=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:p.title||l,description:p.description||"",date:u,tags:p.tags?p.tags.split(",").map(g=>g.trim()):[],image:p.image||null})}return r.sort((n,o)=>o.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>
|
|
1053
|
+
<title><![CDATA[${is(n.title)}]]></title>
|
|
1047
1054
|
<link>${L(this.options.baseUrl)}${L(this.options.blogPath)}/${L(n.slug)}</link>
|
|
1048
1055
|
<guid>${L(this.options.baseUrl)}${L(this.options.blogPath)}/${L(n.slug)}</guid>
|
|
1049
|
-
<description><![CDATA[${
|
|
1056
|
+
<description><![CDATA[${is(n.description)}]]></description>
|
|
1050
1057
|
<pubDate>${n.date?new Date(n.date).toUTCString():""}</pubDate>${n.tags.length?`
|
|
1051
1058
|
<category>${L(n.tags.join(", "))}</category>`:""}${n.image?`
|
|
1052
1059
|
<enclosure url="${L(this.options.baseUrl)}${L(n.image)}" type="image/png" length="0"/>`:""}
|
|
@@ -1061,14 +1068,14 @@ ${c.join(`
|
|
|
1061
1068
|
<atom:link href="${L(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
1062
1069
|
${s}
|
|
1063
1070
|
</channel>
|
|
1064
|
-
</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()}}},lt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],ct=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function
|
|
1065
|
-
`)}var
|
|
1066
|
-
`];
|
|
1067
|
-
`);for(let p of s){let u=
|
|
1068
|
-
`),c.push(`Source: ${
|
|
1071
|
+
</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()}}},lt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],ct=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Or(a){let e=["# AI Crawler Management"];if(a==="block-all"){for(let t of[...lt,...ct])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(a==="allow-all"){for(let t of[...lt,...ct])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of lt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of ct)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Pe(a){return a.replace(/\s+/g," ").trim()}function ps(a){let e=[`# ${Pe(a.name)}`,""];a.summary&&e.push(`> ${Pe(a.summary)}`,"");for(let t of a.sections)if(t.links.length!==0){e.push(`## ${Pe(t.heading)}`,"");for(let s of t.links){let r=`- [${Pe(s.title)}](${s.url})`;e.push(s.description?`${r}: ${Pe(s.description)}`:r)}e.push("")}return e.join(`
|
|
1072
|
+
`)}var Ir="dndev",Lr="crud",Ur="entity-";function us(a,e,t){return e?a?.[e]?.[t]:void 0}function H(a){return typeof a=="string"&&a.trim()!==""?a.trim():void 0}function Mr(a,e,t){let s=a.metaExport||a.meta||{},r=s.seo||{},n=us(e,s.namespace,t),o=H(n?.title)??H(r.title)??H(n?.meta?.fullTitle)??H(r.fullTitle),i=r.description===null?void 0:H(r.description)??H(n?.description);return{...o&&{title:o},...i&&{description:i}}}function gs(a){let{siteName:e,description:t,baseUrl:s,sitemapRoutes:r,routes:n,blogPosts:o=[],blogPath:i="/blog",translations:l,language:c}=a,p=us(l,Ir,c)?.seo,u=H(p?.llmsPages),g=H(p?.llmsBlog);if(!u||!g)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${c}".`);let h=new Map(n.map(b=>[b.path,b])),f=new Map(o.map(b=>[`${i}/${b.slug}`,b])),w=r.map(({path:b,collection:x})=>{let T=f.get(b);if(T)return{path:b,title:T.title,...H(T.description)&&{description:H(T.description)},section:g};if(x)return{path:b,collection:x};let C=y(b);if(b===i&&!C.title)return{path:b,...C,title:g};if(!C.title){let _=h.get(b),j=(_?.metaExport||_?.meta)?.namespace;throw new Error(`[dndev] llms.txt: page "${b}" has no title in "${c}". Add "title" to `+(j?`${j}_${c}.json`:"its translations")+" or `seo: { title }` to its PageMeta.")}return{path:b,...C}});function y(b){let x=h.get(b);return x?Mr(x,l,c):{}}let v={},P={};for(let[b,x]of Object.entries(l||{})){if(b===Lr&&x?.[c]&&(P[b]=x[c]),!b.startsWith(Ur))continue;x?.[c]&&(P[b]=x[c]);let T=H(x?.[c]?.namePlural);T&&(v[b]=T)}return{name:e,...H(t)&&{summary:H(t)},baseUrl:s,pagesHeading:u,routes:w,entityHeadings:v,language:c,translations:P}}function hs(a={}){let{siteName:e,baseUrl:t,blogPosts:s=[],blogPath:r="/blog",appRoot:n,logger:o}=a;if(!e||!t)return null;if(s.length===0)return o?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=R.getInstance(),l=n?i.resolvePath("src/content/blog",n):null;if(!l||!i.pathExists(l))return null;let c=[`# ${e}
|
|
1073
|
+
`];a.description&&c.push(`> ${a.description}
|
|
1074
|
+
`);for(let p of s){let u=i.resolvePath(`${p.slug}_en.md`,l);try{let g=i.readSync(u,{format:"text"});if(!g)continue;let h=g.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),f=`${t}${r}/${p.slug}`;c.push(`## ${p.title}
|
|
1075
|
+
`),c.push(`Source: ${f}
|
|
1069
1076
|
`),p.date&&c.push(`Date: ${p.date}
|
|
1070
|
-
`),c.push(
|
|
1071
|
-
`)}var
|
|
1077
|
+
`),c.push(h.trim()),c.push("")}catch{o?.debug?.(`llms-full.txt: could not read ${p.slug}`)}}return c.join(`
|
|
1078
|
+
`)}var fs=`src/app/sitemap.xml/${F("route","ts")}`,ds=`src/app/llms.txt/${F("route","ts")}`;function ms(a){let e=a.filter(r=>r.path.includes(":")),t=`${a.length-e.length} static + ${e.length} dynamic`;if(e.length===0)return t;let s=e.map(r=>`${r.path} \u2192 ${r.collection??"no collection"}`);return`${t} (${s.join(", ")})`}var pt=class extends M{constructor(e={}){super(de,e);let t=R.getInstance(),s=G("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let n=e.baseUrl;if(!n&&r){let l=r.trim().replace(/\/+$/,"");n=/^https?:\/\//i.test(l)?l:`https://${l}`}n?s.debug(`Found app URL: ${n}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let o=e.siteName||null;if(s.verbose(`Name: ${o||"Not found"}`),s.verbose(`URL: ${n||"Not found"}`),o&&s.debug(` - Site name from appConfig: "${o}"`),e.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let i=[];if(n||i.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),o||i.push("siteName (APP_NAME in src/config/app.ts)"),i.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),i.forEach(l=>s.warn(` - ${l}`)),s.warn(""),s.warn(" To fix:"),n||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),o||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this.options.isDev||cs(n,"NEXT_PUBLIC_APP_URL"),this._baseUrl=n,this._siteName=o,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this._sitemapEnabled=this.options.generateSitemap!==!1,this.seoGenerator=new Oe({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,baseUrl:n,siteName:o,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e,generateSitemap:!1})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(r,n)=>{if(!r){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${r}`,n,r)},s=await this.seoGenerator.generateSEOFiles(e,t);if(this._sitemapEnabled&&await this.generateSitemapRoute(e.routes||[]),s.robotsTxt&&!s.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${s.robotsTxt.disallowedPaths||0} disallowed paths`),s.sitemap&&!s.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${s.sitemap.publicRoutes||0} routes`),s.rss&&!s.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${s.rss.postCount||0} blog posts`),s.manifest&&!s.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json"),this._llmsTxtEnabled){let r=this.seoGenerator.discoverBlogPosts(),n=this.pathResolver.getAppRoot();if(await this.generateLlmsTxtRoute(e.routes||[],r),r.length>0){let o=hs({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:n,blogPosts:r,logger:this.logger});o&&(this.writeGeneratedFile("public/llms-full.txt",o,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))}}}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}useLanguages(e){this._languageRouting=e}async generateSitemapRoute(e){if(!this._languageRouting)throw new Error("SEO handler: languages not set before sitemap generation (runDiscoveries calls useLanguages)");let t=this.seoGenerator.getSitemapRoutes(e,this.seoGenerator.discoverBlogPosts()),s=this.serverCrudReader(t),r=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1072
1079
|
// Regenerated on every build from src/pages (PageMeta) and appConfig.
|
|
1073
1080
|
// Public routes + one URL per published record of each dynamic route's entity
|
|
1074
1081
|
// (read with the public role). Keep a page out with \`seo: { noindex: true }\`.
|
|
@@ -1078,8 +1085,8 @@ import type { LanguageRouting } from '@donotdev/core/server';
|
|
|
1078
1085
|
import { buildSitemap, formatSitemapXml } from '@donotdev/core/next';
|
|
1079
1086
|
import type { SitemapRoute } from '@donotdev/core/next';
|
|
1080
1087
|
${s.imports}
|
|
1081
|
-
//
|
|
1082
|
-
export const revalidate = ${
|
|
1088
|
+
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
1089
|
+
export const revalidate = ${this.revalidate()};
|
|
1083
1090
|
|
|
1084
1091
|
const BASE_URL = ${JSON.stringify(this._baseUrl)};
|
|
1085
1092
|
|
|
@@ -1099,7 +1106,7 @@ export async function GET(): Promise<Response> {
|
|
|
1099
1106
|
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
|
|
1100
1107
|
});
|
|
1101
1108
|
}
|
|
1102
|
-
`;this.writeGeneratedFile(
|
|
1109
|
+
`;this.writeGeneratedFile(fs,r,"sitemap route");let n=this.pathResolver.resolveAppPath("public/sitemap.xml");this.pathResolver.pathExists(n)&&await this.pathResolver.remove(n),this.logger.info(`\u{1F5FA}\uFE0F sitemap: ${ms(t)} (${fs}); URL count printed by dndev build`)}useTranslations(e){this._translations=e}async generateLlmsTxtRoute(e,t){if(!this._languageRouting||!this._translations)throw new Error("SEO handler: languages/translations not set before llms.txt generation (runDiscoveries calls useLanguages and useTranslations)");let s=gs({siteName:this._siteName,description:this._siteDescription,baseUrl:this._baseUrl,sitemapRoutes:this.seoGenerator.getSitemapRoutes(e,t),routes:e,blogPosts:t,blogPath:this.seoGenerator.options.blogPath,translations:this._translations,language:this._languageRouting.defaultLanguage}),r=this.serverCrudReader(s.routes),n=this.appDependsOn("entities"),o=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1103
1110
|
// Regenerated on every build from src/pages (PageMeta), translations and appConfig.
|
|
1104
1111
|
// Same URLs as app/sitemap.xml: public pages + one link per published record of each
|
|
1105
1112
|
// dynamic route's entity. Keep a page out with \`seo: { noindex: true }\`.
|
|
@@ -1109,8 +1116,8 @@ import { buildLlmsTxt } from '@donotdev/core/next';
|
|
|
1109
1116
|
import type { LlmsTxtSource } from '@donotdev/core/next';
|
|
1110
1117
|
${n?`import * as entities from 'entities';
|
|
1111
1118
|
`:""}${r.imports}
|
|
1112
|
-
//
|
|
1113
|
-
export const revalidate = ${
|
|
1119
|
+
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
1120
|
+
export const revalidate = ${this.revalidate()};
|
|
1114
1121
|
|
|
1115
1122
|
const SOURCE: LlmsTxtSource = ${JSON.stringify(s,null,2)};
|
|
1116
1123
|
${r.setup}
|
|
@@ -1126,7 +1133,7 @@ export async function GET(): Promise<Response> {
|
|
|
1126
1133
|
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
1127
1134
|
});
|
|
1128
1135
|
}
|
|
1129
|
-
`;this.writeGeneratedFile(
|
|
1136
|
+
`;this.writeGeneratedFile(ds,o,"llms.txt route"),this.logger.info(`\u{1F4C4} llms.txt: ${ms(s.routes)} (${ds})`)}appDependsOn(e){let t=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"),{format:"json"});return!!(t?.dependencies?.[e]||t?.devDependencies?.[e])}serverCrudReader(e){let t=e.filter(s=>s.collection);if(t.length===0)return{imports:"",setup:"",expr:null};if(this.appDependsOn("@donotdev/supabase"))return{imports:`import { createPublicServerClient, SupabaseCrudAdapter } from '@donotdev/supabase/server';
|
|
1130
1137
|
`,setup:`
|
|
1131
1138
|
// Public (anonymous) reader: RLS returns what a signed-out visitor can read.
|
|
1132
1139
|
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
|
@@ -1139,7 +1146,7 @@ if (!SUPABASE_URL || !SUPABASE_PUBLIC_KEY) {
|
|
|
1139
1146
|
const CRUD = new SupabaseCrudAdapter(
|
|
1140
1147
|
createPublicServerClient(SUPABASE_URL, SUPABASE_PUBLIC_KEY)
|
|
1141
1148
|
);
|
|
1142
|
-
`,expr:"CRUD"};throw new Error(`[dndev] SEO: ${t.map(s=>s.path).join(", ")} list published records, but the app's backend provider has no server reader (supported: @donotdev/supabase). Mark these pages \`seo: { noindex: true }\`.`)}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function ds(o={}){return new pt(o)}function fs(o={}){let{debug:e}=o;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:n}=r;return n||(s.externals||(s.externals={}),vt.forEach(a=>{s.externals[a]=`commonjs ${a}`})),t.webpack?t.webpack(s,r):s}})}var ms=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,vs=/['"]([^'"]+)['"]/g,ve=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:{...Be.selectors,...this.options.customPatterns?.selectors},themes:{...Be.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,l)=>{let i=a.replace(/[^a-zA-Z0-9]/g,"");return i?l===0?i.toLowerCase():i.charAt(0).toUpperCase()+i.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],n,a=this.pathResolver.normalizePath(t),l=this._stripComments(e),i=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(n=i.exec(l))!==null;){let[,c,p,u]=n;if(!c||!u)continue;let g=p.match(this.patterns.themes.themeIcon),d=p.match(this.patterns.themes.themeIsDark),h={name:c,displayName:u,isDark:d?d[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${u})`),r.push(h),s.themes.set(c,{name:c,displayName:u,isDark:h.isDark,file:a,variables:new Set,meta:h.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${a}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let 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}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(ms.lastIndex=0;(r=ms.exec(t))!==null;){let n=r[1],a;for(vs.lastIndex=0;(a=vs.exec(n))!==null;){let l=a[1].trim();l&&s.add(l)}}return Array.from(s)}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 Le=class extends K{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new ve(t,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:s}=e;this.logger.debug(`Scanning ${t.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",s),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t),await this._processConsumerFiles(s);let r=this._serializeThemes();return this.logger.debug(`Discovered ${r.length} themes:`,r.map(n=>n.name)),{themes:r,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return We.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning framework file ${t}: ${s.message}`)}}async _processConsumerFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${t}: ${s.message}`)}}_addEssentialThemes(){We.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var ut=class extends j{constructor(e={}){super(Le,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new ve(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(n=>!n.essential).length,r=t.length;if(r===0)throw rs("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
1149
|
+
`,expr:"CRUD"};throw new Error(`[dndev] SEO: ${t.map(s=>s.path).join(", ")} list published records, but the app's backend provider has no server reader (supported: @donotdev/supabase). Mark these pages \`seo: { noindex: true }\`.`)}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function vs(a={}){return new pt(a)}function ys(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:n}=r;return n||(s.externals||(s.externals={}),mt.forEach(o=>{s.externals[o]=`commonjs ${o}`})),t.webpack?t.webpack(s,r):s}})}var me=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{...ze.selectors,...this.options.customPatterns?.selectors},themes:{...ze.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(o=>o.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((o,i)=>{let l=o.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,o=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[,c,p,u]=n;if(!c||!u)continue;let g=p.match(this.patterns.themes.themeIcon),h=p.match(this.patterns.themes.themeIsDark),f={name:c,displayName:u,isDark:h?h[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${u})`),r.push(f),s.themes.set(c,{name:c,displayName:u,isDark:f.isDark,file:o,variables:new Set,meta:f.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${o}`),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 o=n.match(/\.([a-z][a-z0-9-]+)/)?.[1];o&&t.push(`Theme class "${o}" 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 o=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:o}}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 bs="@donotdev/components/styles",jr=/@import\s+['"](\.[^'"]+)['"]\s*;/g,Ie=class extends X{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new me(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(),o=jt({frameworkCss:this._readFrameworkTokenCss(),appCss:r});return this.logger.debug("Theme font families:",o),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:o}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return Be.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(bs,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw new Error(`Theme discovery: cannot resolve ${bs} (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 o=this.pathResolver.getDirname(r);return n.replace(jr,(i,l)=>s(this.pathResolver.resolvePath(l,o)))};return s(e)}_addEssentialThemes(){Be.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var ut=class extends M{constructor(e={}){super(Ie,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new me(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(n=>!n.essential).length,r=t.length;if(r===0)throw os("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
1143
1150
|
// Generated at: ${new Date().toISOString()}
|
|
1144
1151
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
1145
1152
|
|
|
@@ -1171,12 +1178,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1171
1178
|
timestamp: Date.now(),
|
|
1172
1179
|
};
|
|
1173
1180
|
}
|
|
1174
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1181
|
+
globalThis._DNDEV_CONFIG_.${J.themes} = themeConfig;
|
|
1175
1182
|
}
|
|
1176
1183
|
|
|
1177
1184
|
// Export for compatibility
|
|
1178
1185
|
export default themeConfig;
|
|
1179
|
-
`}};function
|
|
1180
|
-
\u{1F3D7}\uFE0F DnDev Framework - Building for ${
|
|
1181
|
-
`)),
|
|
1182
|
-
`)}import
|
|
1186
|
+
`}};function ws(a={}){return new ut(a)}function Ss({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:n,assetOptions:o,seoOptions:i,pwaOptions:l,serverShimOptions:c,appUrl:p,isDev:u,logger:g}){let h=s.debug??a,f=r.debug??a,w=n.debug??a,y=o.debug??a,v=i.debug??a,P=l.debug??a,b=c.debug??a,x=s.verbose??e,T=r.verbose??e,C=n.verbose??e,_=o.verbose??e,j=i.verbose??e,re=l.verbose??e,ee=c.verbose??e,d={debug:a,verbose:e,generateManifest:t},ne=s.disabled?null:as({...d,...s,debug:h,verbose:x});a&&g.debug(`Route handler created: ${ne?"enabled":"disabled"} (debug: ${h})`);let E=ws({...d,...r,debug:f,verbose:T}),K=ts({...d,...n,debug:w,verbose:C}),z=Qt({...d,...o,debug:y,verbose:_}),U=vs({...d,...i,debug:v,verbose:j,appUrl:p,isDev:u}),W=ss({...d,...l,debug:P,verbose:re}),N=ys({...d,...c,debug:b,verbose:ee}),k=es({debug:a,verbose:e});return{routeHandler:ne,themeHandler:E,i18nHandler:K,assetHandler:z,seoHandler:U,pwaHandler:W,serverShimHandler:N,blogContentHandler:k}}function $s(a,e){let t={};if(a.routeHandler)try{t.routeConfig=a.routeHandler.createNextConfig()}catch(r){e.error(`Route handler failed during config creation: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.routeConfig=()=>({})}else t.routeConfig=()=>({});let s=[{name:"theme",handler:a.themeHandler},{name:"i18n",handler:a.i18nHandler},{name:"asset",handler:a.assetHandler},{name:"seo",handler:a.seoHandler},{name:"pwa",handler:a.pwaHandler}];for(let{name:r,handler:n}of s)try{t[`${r}Config`]=n.createNextConfig()}catch(o){e.error(`${r.charAt(0).toUpperCase()+r.slice(1)} handler failed: ${o.message}`),e.error(`Stack: ${o.stack||"No stack trace available"}`),t[`${r}Config`]=()=>({})}try{t.serverShimConfig=a.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}var Gr=new Set(["@donotdev/functions"]);function Rs(){try{let a=R.getInstance(),e=a.resolveAppPath("package.json"),t=a.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(r=>r.startsWith("@donotdev/")).filter(r=>!_e.buildTimePackages.includes(r)).filter(r=>!Gr.has(r)).sort()}catch{return[]}}var gt=new Map;function zr(a={}){let{port:e,...t}=a;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let $=process.env.CI==="true";process.env.DNDEV_BUILD_ID=$?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let s=process.env.DNDEV_BUILD_ID;if(s&>.has(s))return gt.get(s).configFn;let{appConfig:r,...n}=t;if(!r)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let o=r?.features?{debug:r.features.debug}:void 0,i=r?.seo===!1?{disabled:!0}:r?.seo&&typeof r.seo!="boolean"?{...r.seo,siteName:r.seo.siteName||r.app?.name,siteDescription:r.app?.description}:r?.app?.name?{siteName:r.app.name,siteDescription:r.app.description}:void 0,l=r?.app?{name:r.app.name,shortName:r.app.shortName,description:r.app.description}:void 0,{features:c,seo:p,...u}=n,g={...o?{features:o}:{},...i?{seo:i}:{},...u},h=Yt(g),f=Zt(h);if(!f)throw new Error("normalizeOptions returned undefined");let{generateManifest:w,debug:y,verbose:v,mode:P,isDev:b,routeOptions:x,themeOptions:T,i18nOptions:C,assetOptions:_,pwaOptions:j,seoOptions:re,serverShimOptions:ee,nextConfigOptions:d,reactCompiler:ne}=f,E=G("next-config",y,v),{appRoot:K,appRootSet:z}=Pt({logger:E,debug:y}),U=!1,W=x?.routingMode||"app",N=z&&Ke(K);if(N||(E.info(`
|
|
1187
|
+
\u{1F3D7}\uFE0F DnDev Framework - Building for ${P}${s?` [build:${s}]`:""}`),E.info(` Platform: Next.js | Routing: ${W}
|
|
1188
|
+
`)),b){let $=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${$}`,y&&(E.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&E.debug(`Port configured: ${$} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||E.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let k=Ss({debug:y,verbose:v,generateManifest:w,routeOptions:{...x,ssr:r?.ssr!==!1,auth:r?.auth,revalidate:r?.revalidate},themeOptions:T,i18nOptions:C,assetOptions:_,seoOptions:{...re,revalidate:r?.revalidate},pwaOptions:{...j,app:l},serverShimOptions:ee,isDev:b,logger:E}),te=$s(k,E),m=async function(A={}){let D=R.getInstance(),q=z?Rs():[];y&&q.length>0&&E.debug(`Discovered ${q.length} packages: ${q.join(", ")}`);let{missing:le,installed:Ee}=Ce(D.getAppRoot()),Me=le.filter(ve=>ve.startsWith("@donotdev/")),xs=Ee.filter(ve=>ve.startsWith("@donotdev/"));y&&le.length>0&&E.debug(`Missing optional deps (will alias to empty): ${le.join(", ")}`),z&&(W==="app"&&Ct({pathResolver:D,logger:E,isCI:!!(process.env.CI||process.env.VERCEL)}),await Vt(k,E));let ce=typeof A=="object"&&A!==null?A:{},{webpack:Es,rewrites:As,redirects:_s,...ks}=ce;z&&!U&&(U=await Jt(k.assetHandler,E,U));let Ns=te.routeConfig(ce),Cs=te.themeConfig(ce),Ds=te.i18nConfig(ce),Ts=te.assetConfig(ce),Fs=te.seoConfig(ce),Os=te.pwaConfig(ce),Is=te.serverShimConfig(),ft=(await k.i18nHandler?.getDiscoveryData?.())?.flagCodes||[],Ls=Ft({originalWebpack:Es,unusedFeaturePackages:Me,usedFeaturePackages:xs,missingOptionalDeps:le,flagCodes:ft,logger:E,debug:y}),Us=Ot({originalRewrites:As,handlers:[k.routeHandler,k.themeHandler,k.i18nHandler,k.assetHandler,k.pwaHandler],logger:E}),Ms=It({originalRedirects:_s,seoRedirects:re?.redirects||[],logger:E}),js={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Gs=Lt({routeResult:Ns,themeResult:Cs,i18nResult:Ds,assetResult:Ts,seoResult:Fs,pwaResult:Os,serverShimResult:Is,restNextConfig:ks,discoveredPackages:q,reactCompiler:ne,routingMode:W,webpackConfig:Ls,rewritesConfig:Us,redirectsConfig:Ms,missingOptionalDeps:le,flagCodes:ft,pathResolver:D,env:js,logger:E});if(E.debug("Next.js config generated"),z&&!N){let ve=l?.name||"app";E.info(`Name: ${ve}`),E.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),E.info(`App root (final): ${D.getAppRoot()}`)}return Gs};return s&>.set(s,{configFn:m}),m}var Ps=zr;import{readFileSync as Br,existsSync as Hr}from"node:fs";import{join as Wr}from"node:path";var xe=null,ht=0,qr=6e4;function Vr(){let a=Date.now();if(xe&&a-ht<qr)return xe;try{let e=Wr(process.cwd(),"public","metadata-manifest.json");if(!Hr(e))return null;let t=Br(e,"utf-8");return xe=JSON.parse(t),ht=a,xe}catch{return null}}function Jr(a,e,t){let s=Vr(),r={title:t?.siteName||"Site"};if(!s)return r;let n=a.startsWith("/")?a:`/${a}`,o=s[n];if(!o)return r;let i=e||o.defaultLocale||"en",l=o.locales[i]||o.locales[o.defaultLocale]||Object.values(o.locales)[0];if(!l)return r;let c=process.env.NEXT_PUBLIC_APP_URL,p={title:l.title,...c&&{metadataBase:new URL(c)}};return l.description&&(p.description=l.description),l.keywords&&(p.keywords=l.keywords),p.openGraph={title:l.title,type:l.type||"website",...l.description&&{description:l.description},...l.image&&{images:[l.image]},...t?.siteName&&{siteName:t.siteName}},p.twitter={card:"summary_large_image",title:l.title,...l.description&&{description:l.description},...l.image&&{images:[l.image]}},l.noindex&&(p.robots={index:!1,follow:!1}),p}function Xr(){xe=null,ht=0}function Kr(a){return a.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}async function Le(a,e,t){let s=[];for(let r of a){let n=Kr(r.path);if(n.length===0){s.push({route:r,path:r.path});continue}let o=n[0];if(n.length>1||!r.collection||!o)throw new Error(`[dndev] Cannot list the public URLs of route "${r.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 "${r.path}" lists "${r.collection}" records but no server CRUD reader was given.`);let i=await e.query(r.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3});for(let l of i.items){let c=l[o];typeof c!="string"&&typeof c!="number"||s.push({route:r,path:r.path.replace(`:${o}`,encodeURIComponent(String(c))),record:l})}}return s}function Ue(a){return String(a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function Yr(a,{baseUrl:e,routing:t,crud:s,languageUrls:r,hiddenStatuses:n}){let o=[],i=(l,c)=>{let p=r(l,e,t),u=t.languages.length>1?{alternates:{languages:p}}:{};for(let g of t.languages)o.push({url:p[g],...c,...u})};for(let{route:l,path:c,record:p}of await Le(a,s,n)){if(!p){i(c,{changeFrequency:l.changeFrequency??"weekly",priority:l.priority??(c==="/"?1:.8),...l.lastModified&&{lastModified:l.lastModified}});continue}let u=p.updatedAt instanceof Date?p.updatedAt.toISOString():p.updatedAt;i(c,{changeFrequency:l.changeFrequency??"weekly",priority:l.priority??.7,...typeof u=="string"&&{lastModified:u}})}return o}function Zr(a){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${a.some(s=>s.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let s of a){t.push(" <url>",` <loc>${Ue(s.url)}</loc>`);for(let[r,n]of Object.entries(s.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${Ue(r)}" href="${Ue(n)}" />`);s.lastModified&&t.push(` <lastmod>${Ue(s.lastModified)}</lastmod>`),s.changeFrequency&&t.push(` <changefreq>${s.changeFrequency}</changefreq>`),s.priority!==void 0&&t.push(` <priority>${s.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
|
|
1189
|
+
`)}import Qr from"i18next";function en(a){let e=new Map;for(let t of Object.values(a))typeof t=="object"&&t!==null&&"collection"in t&&"fields"in t&&e.set(t.collection,t);return e}function tn(a,e){let t=Qr.createInstance();return t.init({lng:a,resources:{[a]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),s=>t.getFixedT(a,[s,"crud"])}async function sn(a){let{crud:e,deriveEntitySeo:t,hiddenStatuses:s}=a,r=en(a.entities),n,o=new Map,i=l=>{let c=o.get(l);return c||(c={heading:l,links:[]},o.set(l,c)),c};i(a.pagesHeading);for(let{route:l,path:c,record:p}of await Le(a.routes,e,s)){let u=`${a.baseUrl}${c}`;if(!p){if(!l.title)throw new Error(`[dndev] llms.txt: page "${l.path}" has no label in the app language.`);i(l.section??a.pagesHeading).links.push({title:l.title,url:u,...l.description&&{description:l.description}});continue}let g=r.get(l.collection);if(!g)throw new Error(`[dndev] llms.txt: no entity definition for collection "${l.collection}" (route "${l.path}"). Export it from the app's \`entities\` package.`);let h=l.section??(g.namespace?a.entityHeadings[g.namespace]:void 0);if(!h)throw new Error(`[dndev] llms.txt: no heading for route "${l.path}". Add "namePlural" to the ${g.namespace??`entity-${g.name.toLowerCase()}`} translations.`);if(!n){if(!a.language||!a.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");n=tn(a.language,a.translations)}let f=t(g,p,{t:n(g.namespace),locale:a.language});if(!f.title)throw new Error(`[dndev] llms.txt: published "${l.collection}" record at "${c}" has no title (listCardFields title fields, or first text field, are empty).`);i(h).links.push({title:f.title,url:u,...f.description&&{description:f.description}})}return ps({name:a.name,...a.summary&&{summary:a.summary},sections:[...o.values()]})}export{sn as buildLlmsTxt,Yr as buildSitemap,Xr as clearMetadataCache,Ps as default,Ps as defineNextConfig,Zs as definePostCSSConfig,Zr as formatSitemapXml,Jr as getMetadataForPath};
|