@donotdev/core 0.3.3 → 0.3.4
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/i18n/locales/lazy/auth_ar.json +7 -1
- package/i18n/locales/lazy/auth_da.json +7 -1
- package/i18n/locales/lazy/auth_de.json +7 -1
- package/i18n/locales/lazy/auth_en.json +7 -1
- package/i18n/locales/lazy/auth_es.json +7 -1
- package/i18n/locales/lazy/auth_fr.json +7 -1
- package/i18n/locales/lazy/auth_it.json +7 -1
- package/i18n/locales/lazy/auth_ja.json +7 -1
- package/i18n/locales/lazy/auth_ko.json +7 -1
- package/i18n/locales/lazy/auth_nl.json +7 -1
- package/i18n/locales/lazy/auth_pl.json +7 -1
- package/i18n/locales/lazy/auth_pt.json +7 -1
- package/i18n/locales/lazy/auth_zh.json +7 -1
- package/index.d.ts +304 -50
- package/index.js +5 -5
- package/next/index.d.ts +15 -9
- package/next/index.js +137 -132
- package/next/runtime.js +2 -2
- package/package.json +2 -2
- package/server.d.ts +170 -25
- package/shared.js +2 -2
- package/symbol-index.json +1 -1
- package/vite/index.d.ts +1 -1
- package/vite/index.js +149 -149
package/next/index.js
CHANGED
|
@@ -1,17 +1,16 @@
|
|
|
1
|
-
import*as $ from"node:fs";import"node:fs";import{createRequire as Ls}from"node:module";import{resolve as Ue,join as fe,dirname as ye,relative as rn,normalize as Ms,sep as sn,extname as Us}from"node:path";import js from"fast-glob";var Ae={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var Qt={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},Y={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},Z={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},L={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts",fonts:"src/app/fonts.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ne="/og-image.png";var lt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},le={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},we={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy",PUBLISHED_FLAGS:"i18n/flags"},X={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:[`${we.SOURCE_EAGER}/*_*.json`],lazy:[`${we.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","icon-*x*.png",Ne.slice(1)],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},Le={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"]};var ct={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)/}},en=["-apple-system","BlinkMacSystemFont","SF Pro","SF Pro Text","SF Pro Display","SF Mono","Helvetica Neue","Helvetica","Menlo","Monaco","Apple SD Gothic Neo","Hiragino Sans","Hiragino Kaku Gothic ProN","PingFang SC","PingFang TC","Apple Color Emoji","Segoe UI","Segoe UI Emoji","Segoe UI Symbol","Cascadia Code","Cascadia Mono","Consolas","Arial","Georgia","Times New Roman","Times","Courier New","Courier","Verdana","Tahoma","Trebuchet MS","Malgun Gothic","Yu Gothic","Meiryo","Microsoft YaHei","Microsoft JhengHei","Liberation Sans","Liberation Serif","Liberation Mono","DejaVu Sans","DejaVu Serif","DejaVu Sans Mono","Ubuntu","Cantarell","Noto Sans","Noto Serif","Noto Color Emoji","Droid Sans","Droid Sans Mono"],tn={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:[]},ut=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Zt={base:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...X.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...X.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore}};function nn(r,e=null){let t=X[r];if(!t)throw new Error(`Unknown pattern type: ${r}`);return e&&t.framework?{...t,framework:t.framework.map(n=>`${e}/${n}`)}:t}function Me(r){return Zt[r]||Zt.base}var Se={getGlobOptionsFor:Me||void 0,SCAN_PATTERNS:X||void 0,getPatternsFor:nn||void 0,I18N_PATHS:we||void 0},z={error:(r,e)=>{},warn:(r,e)=>{},info:r=>{}};function Ee(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="EEXIST"}function on(r,e){return r().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var an={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},D=class r{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return r._instance||(r._instance=new r(e)),r._instance}static _reset(){r._instance=null}constructor(e={}){if(r._instance)return r._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,r._instance=this}normalizePath(e){if(!e)return"";try{return Ms(e).split(sn).join("/")}catch{return String(e).split(sn).join("/")}}getRelativePath(e){let t=this.getAppRoot(),n=rn(t,e);return this.normalizePath(n)}getBasename(e){if(!e)return"";let n=this.normalizePath(e).split("/");return n[n.length-1]||""}getDirname(e){return e?this.normalizePath(ye(e)):""}resolvePackage(e,t=null){try{let n=t||this.getAppRoot(),o=Ls(fe(n,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let n=this.resolvePackage(`${e}/package.json`,t);if(n)return this.getDirname(n);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let s=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(s))return s;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),n=Ue(t,e);return this.normalizePath(n)}resolveRepoPath(e){let t=this.getRepoRoot(),n=this.normalizePath(e),s=Ue(t,n);return this.normalizePath(s)}resolvePath(e,t){let n=this.normalizePath(t),s=this.normalizePath(e),o=Ue(n,s);return this.normalizePath(o)}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:Us(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:n="auto",encoding:s="utf8"}=t,o=this._detectFormat(e,n);try{if(o==="buffer")return await $.promises.readFile(e);let a=await $.promises.readFile(e,s),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&z.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:n="auto",encoding:s="utf8"}=t,o=this._detectFormat(e,n);try{if(o==="buffer")return $.readFileSync(e);let a=$.readFileSync(e,s),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&z.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,n={}){let{format:s="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),u=this.normalizePath(ye(l)),c=this.pathExists(l);if(c&&!o)return i&&z.info(`Skipping existing file: ${l}`),!1;if(a)return z.info(`[DRY RUN] Would write file: ${l}`),!0;try{await $.promises.mkdir(u,{recursive:!0})}catch(f){if(!Ee(f))throw f}let p=this._detectFormat(e,s),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
2
|
-
`:d=String(t);try{return await
|
|
3
|
-
`:d=String(t);try{return Buffer.isBuffer(d)?$.writeFileSync(l,d):$.writeFileSync(l,d,"utf8"),this._writtenPaths?.add(l),i&&z.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,n={}){let{overwrite:s=!1,dryRun:o=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!s)return a&&z.info(`Skipping existing file: ${i}`),!1;if(o)return z.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(ye(i));try{await $.promises.mkdir(u,{recursive:!0})}catch(c){if(!Ee(c))throw c}try{return await on(async()=>(await $.promises.copyFile(e,i),a&&z.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,n={}){let{overwrite:s=!1,dryRun:o=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!s)return a&&z.info(`Skipping existing file: ${i}`),!1;if(o)return z.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(ye(i));try{$.mkdirSync(u,{recursive:!0})}catch(c){if(!Ee(c))throw c}try{return $.copyFileSync(e,i),this._writtenPaths?.add(i),a&&z.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return $.existsSync(e)}catch(n){return t||z.error(`Error checking path existence: ${e}`,n),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return $.existsSync(t)||$.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return $.readdirSync(e,t)}catch(n){return this.options.debug&&z.warn(`Failed to read directory: ${e}`,n),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return $.statSync(e)}catch(t){return this.options.debug&&z.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return $.realpathSync(e)}watch(e,t,n){return $.watch(e,t,n)}lstatSync(e){try{return $.lstatSync(e)}catch(t){return this.options.debug&&z.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await $.promises.mkdir(e,{recursive:!0})}catch(t){if(!Ee(t))throw t}}ensureDirSync(e){try{$.mkdirSync(e,{recursive:!0})}catch(t){if(!Ee(t))throw t}}async remove(e){await $.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){$.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return $.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=fe(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Ue(e)),n=this.getAppRoot(),s=rn(n,t),o=this.normalizePath(s);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,n={}){let s=this.normalizePath(fe(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=s.startsWith(a)?s.slice(a.length+1):s,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:Se.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...n})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Se.I18N_PATHS;if(!t)return null;let n=e.replace(t.SOURCE_ROOT+"/",""),s=this.resolveFrameworkPackage("@donotdev/core");if(!s)return null;let o=this.normalizePath(fe(s,t.PUBLISHED_ROOT,n)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await js(e,t)).map(s=>{let o=typeof s=="string"?s:s.path;return this.normalizePath(o)}).sort()}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let n=[...e.framework,...e.consumer];for(let c of n)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let s=this.getAppRoot(),o=Se.getGlobOptionsFor?Se.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(s),i=e.framework.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),u={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s};try{let c=i.length>0?await this._globWithNormalization(i,u):[],p=await this._globWithNormalization(l,u);return{frameworkFiles:c,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!Se.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),n=this.getRepoRoot();if(e==="i18n"&&(!t||t===n))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${n}). Ensure configResolved hook has run before discovery.`);let s=Se.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=s,u={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let a=s,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),n=0,s=this.options.maxLevels;for(;n<s;){let o=this.normalizePath(fe(t,an.TOOLING)),a=this.normalizePath(fe(t,an.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=fe(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(fe(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(ye(t))===t)return t;let u=this.normalizePath(ye(t));if(u===t)break;t=u,n++}return this.normalizePath(e)}};function ln({logger:r,debug:e=!1}={}){let t=D.getInstance(),n=!1,s=null;if(process.env.DNDEV_APP_ROOT?(s=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(s)?(t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root set from DNDEV_APP_ROOT: ${s}`)):r&&r.warn(`DNDEV_APP_ROOT path does not exist: ${s}`)):e&&r&&r.debug("DNDEV_APP_ROOT env var not set"),!n){if(t.getRepoRoot()){let a=t.resolveRepoPath("apps");if(t.pathExists(a))try{let i=process.cwd(),l=t.normalizePath(i);if(l.includes("/apps/")){let u=l.indexOf("/apps/"),p=l.substring(u+6).split("/")[0];if(p){let d=t.resolveRepoPath(`apps/${p}`),f=t.resolveRepoPath(`apps/${p}/next.config.js`);t.pathExists(f)&&(s=d,t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root detected from process.cwd(): ${s}`))}}}catch{}}!n&&!s&&(s=process.cwd(),t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root fallback to process.cwd(): ${s}`))}return{appRoot:s,appRootSet:n}}import oo from"node:fs";import{readdirSync as Bs,readFileSync as Gs,writeFileSync as zs}from"node:fs";import{createRequire as Hs}from"node:module";import{join as dt,resolve as Ws}from"node:path";var je=Hs(import.meta.url),pt=[14,1];function cn(r){if(!r)return!1;let[e,t=0]=String(r).split(".").map(Number);return e<pt[0]||e===pt[0]&&t<pt[1]}function qs(r){let e=je("@babel/core"),{targets:t}=e.loadPartialConfig({cwd:r,root:r,babelrc:!1,configFile:!1,filename:dt(r,"index.js")}).options;return cn(t?.safari)||cn(t?.ios)}function*un(r){for(let e of Bs(r,{withFileTypes:!0})){let t=dt(r,e.name);e.isDirectory()?yield*un(t):e.name.endsWith(".js")&&(yield t)}}function Js(){return{pre(r){r.metadata.script=r.path.node.sourceType==="script";let e=Object.keys(r.scope.bindings);if(r.metadata.script&&e.length>0)throw new Error(`declares top-level ${e.join(", ")}, which its own function scope would hide from the other chunks`)}}}async function pn({distDir:r,projectDir:e}){if(!qs(e))return 0;let t=je("@babel/core"),n=[Js,[je.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],je.resolve("@babel/plugin-transform-parameters")],s=0;for(let o of un(dt(Ws(e,r),"static"))){let a=Gs(o,"utf8"),i;try{i=t.transformSync(a,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:n})}catch(l){throw new Error(`[dndev] Safari destructuring fix: cannot transform ${o}: ${l.message}`)}i?.code&&i.code!==a&&(zs(o,i.metadata.script?`(function(){${i.code}
|
|
4
|
-
|
|
5
|
-
`).length;function go(r){let e=[];for(let{file:t,content:n}of r){if(/\.generated\.[a-z]+$/.test(t))continue;let s=t.endsWith(".css"),o=t.endsWith(".html"),a=fo(n,o?[io,gt]:s?[gt]:[gt,ao]),i=s?[["fontsource",uo],["font-face",En]]:o?[["font-face",En]]:[["next-font",lo],["fontsource",co]];for(let[l,u]of i)for(let c of a.matchAll(u))e.push({file:t,line:ho(a,c.index),rule:l})}return e}function xn(r){let e=go(r);if(e.length===0)return;let t=e.map(({file:n,line:s,rule:o})=>` ${n}:${s} ${po[o].message}`);throw C("dndev-fonts",`the app loads fonts itself; the framework font plan is the one way:
|
|
1
|
+
import*as $ from"node:fs";import"node:fs";import{createRequire as Gs}from"node:module";import{resolve as je,join as fe,dirname as ye,relative as ln,normalize as zs,sep as cn,extname as Hs}from"node:path";import Ws from"fast-glob";var Ne={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var rn={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"},Z={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},L={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts",fonts:"src/app/fonts.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Se="/og-image.png";var pt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},le={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},we={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy",PUBLISHED_FLAGS:"i18n/flags"},Y={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:[`${we.SOURCE_EAGER}/*_*.json`],lazy:[`${we.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","icon-*x*.png",Se.slice(1)],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},Me={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"]};var dt={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)/}},sn=["-apple-system","BlinkMacSystemFont","SF Pro","SF Pro Text","SF Pro Display","SF Mono","Helvetica Neue","Helvetica","Menlo","Monaco","Apple SD Gothic Neo","Hiragino Sans","Hiragino Kaku Gothic ProN","PingFang SC","PingFang TC","Apple Color Emoji","Segoe UI","Segoe UI Emoji","Segoe UI Symbol","Cascadia Code","Cascadia Mono","Consolas","Arial","Georgia","Times New Roman","Times","Courier New","Courier","Verdana","Tahoma","Trebuchet MS","Malgun Gothic","Yu Gothic","Meiryo","Microsoft YaHei","Microsoft JhengHei","Liberation Sans","Liberation Serif","Liberation Mono","DejaVu Sans","DejaVu Serif","DejaVu Sans Mono","Ubuntu","Cantarell","Noto Sans","Noto Serif","Noto Color Emoji","Droid Sans","Droid Sans Mono"],on={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:[]},ft=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],nn={base:{absolute:!0,onlyFiles:!0,ignore:Y.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...Y.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...Y.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:Y.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:Y.globalIgnore}};function an(r,e=null){let t=Y[r];if(!t)throw new Error(`Unknown pattern type: ${r}`);return e&&t.framework?{...t,framework:t.framework.map(n=>`${e}/${n}`)}:t}function Ue(r){return nn[r]||nn.base}var Ee={getGlobOptionsFor:Ue||void 0,SCAN_PATTERNS:Y||void 0,getPatternsFor:an||void 0,I18N_PATHS:we||void 0},z={error:(r,e)=>{},warn:(r,e)=>{},info:r=>{}};function Re(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="EEXIST"}function un(r,e){return r().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var pn={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},O=class r{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return r._instance||(r._instance=new r(e)),r._instance}static _reset(){r._instance=null}constructor(e={}){if(r._instance)return r._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,r._instance=this}normalizePath(e){if(!e)return"";try{return zs(e).split(cn).join("/")}catch{return String(e).split(cn).join("/")}}getRelativePath(e){let t=this.getAppRoot(),n=ln(t,e);return this.normalizePath(n)}getBasename(e){if(!e)return"";let n=this.normalizePath(e).split("/");return n[n.length-1]||""}getDirname(e){return e?this.normalizePath(ye(e)):""}resolvePackage(e,t=null){try{let n=t||this.getAppRoot(),o=Gs(fe(n,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let n=this.resolvePackage(`${e}/package.json`,t);if(n)return this.getDirname(n);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let s=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(s))return s;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),n=je(t,e);return this.normalizePath(n)}resolveRepoPath(e){let t=this.getRepoRoot(),n=this.normalizePath(e),s=je(t,n);return this.normalizePath(s)}resolvePath(e,t){let n=this.normalizePath(t),s=this.normalizePath(e),o=je(n,s);return this.normalizePath(o)}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:Hs(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:n="auto",encoding:s="utf8"}=t,o=this._detectFormat(e,n);try{if(o==="buffer")return await $.promises.readFile(e);let a=await $.promises.readFile(e,s),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&z.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:n="auto",encoding:s="utf8"}=t,o=this._detectFormat(e,n);try{if(o==="buffer")return $.readFileSync(e);let a=$.readFileSync(e,s),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&z.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,n={}){let{format:s="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),c=this.normalizePath(ye(l)),u=this.pathExists(l);if(u&&!o)return i&&z.info(`Skipping existing file: ${l}`),!1;if(a)return z.info(`[DRY RUN] Would write file: ${l}`),!0;try{await $.promises.mkdir(c,{recursive:!0})}catch(f){if(!Re(f))throw f}let p=this._detectFormat(e,s),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`:d=String(t);try{return await un(async()=>(Buffer.isBuffer(d)?await $.promises.writeFile(l,d):await $.promises.writeFile(l,d,"utf8"),i&&z.info(`${u?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,n={}){let{format:s="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),c=this.normalizePath(ye(l)),u=this.pathExists(l);if(u&&!o)return i&&z.info(`Skipping existing file: ${l}`),!1;if(a)return z.info(`[DRY RUN] Would write file: ${l}`),!0;try{$.mkdirSync(c,{recursive:!0})}catch(f){if(!Re(f))throw f}let p=this._detectFormat(e,s),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
3
|
+
`:d=String(t);try{return Buffer.isBuffer(d)?$.writeFileSync(l,d):$.writeFileSync(l,d,"utf8"),this._writtenPaths?.add(l),i&&z.info(`${u?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,n={}){let{overwrite:s=!1,dryRun:o=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!s)return a&&z.info(`Skipping existing file: ${i}`),!1;if(o)return z.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(ye(i));try{await $.promises.mkdir(c,{recursive:!0})}catch(u){if(!Re(u))throw u}try{return await un(async()=>(await $.promises.copyFile(e,i),a&&z.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,n={}){let{overwrite:s=!1,dryRun:o=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!s)return a&&z.info(`Skipping existing file: ${i}`),!1;if(o)return z.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(ye(i));try{$.mkdirSync(c,{recursive:!0})}catch(u){if(!Re(u))throw u}try{return $.copyFileSync(e,i),this._writtenPaths?.add(i),a&&z.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return $.existsSync(e)}catch(n){return t||z.error(`Error checking path existence: ${e}`,n),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return $.existsSync(t)||$.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return $.readdirSync(e,t)}catch(n){return this.options.debug&&z.warn(`Failed to read directory: ${e}`,n),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return $.statSync(e)}catch(t){return this.options.debug&&z.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return $.realpathSync(e)}watch(e,t,n){return $.watch(e,t,n)}lstatSync(e){try{return $.lstatSync(e)}catch(t){return this.options.debug&&z.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await $.promises.mkdir(e,{recursive:!0})}catch(t){if(!Re(t))throw t}}ensureDirSync(e){try{$.mkdirSync(e,{recursive:!0})}catch(t){if(!Re(t))throw t}}async remove(e){await $.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){$.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return $.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=fe(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(je(e)),n=this.getAppRoot(),s=ln(n,t),o=this.normalizePath(s);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,n={}){let s=this.normalizePath(fe(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=s.startsWith(a)?s.slice(a.length+1):s,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:Ee.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...n})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Ee.I18N_PATHS;if(!t)return null;let n=e.replace(t.SOURCE_ROOT+"/",""),s=this.resolveFrameworkPackage("@donotdev/core");if(!s)return null;let o=this.normalizePath(fe(s,t.PUBLISHED_ROOT,n)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await Ws(e,t)).map(s=>{let o=typeof s=="string"?s:s.path;return this.normalizePath(o)}).sort()}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let n=[...e.framework,...e.consumer];for(let u of n)if(typeof u!="string"||u.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let s=this.getAppRoot(),o=Ee.getGlobOptionsFor?Ee.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(s),i=e.framework.map(u=>{let p=this.normalizePath(u);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(u=>{let p=this.normalizePath(u);return p.startsWith(a)?p.slice(a.length+1):p}),c={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s};try{let u=i.length>0?await this._globWithNormalization(i,c):[],p=await this._globWithNormalization(l,c);return{frameworkFiles:u,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!Ee.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),n=this.getRepoRoot();if(e==="i18n"&&(!t||t===n))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${n}). Ensure configResolved hook has run before discovery.`);let s=Ee.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=s,c={eager:l.eager.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),lazy:l.lazy.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),framework:{eager:o?(l.framework?.eager||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean))},all:[]};return c.all=[...c.eager,...c.lazy,...c.framework.eager,...c.framework.lazy],c}let a=s,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),n=0,s=this.options.maxLevels;for(;n<s;){let o=this.normalizePath(fe(t,pn.TOOLING)),a=this.normalizePath(fe(t,pn.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=fe(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(fe(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(ye(t))===t)return t;let c=this.normalizePath(ye(t));if(c===t)break;t=c,n++}return this.normalizePath(e)}};function dn({logger:r,debug:e=!1}={}){let t=O.getInstance(),n=!1,s=null;if(process.env.DNDEV_APP_ROOT?(s=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(s)?(t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root set from DNDEV_APP_ROOT: ${s}`)):r&&r.warn(`DNDEV_APP_ROOT path does not exist: ${s}`)):e&&r&&r.debug("DNDEV_APP_ROOT env var not set"),!n){if(t.getRepoRoot()){let a=t.resolveRepoPath("apps");if(t.pathExists(a))try{let i=process.cwd(),l=t.normalizePath(i);if(l.includes("/apps/")){let c=l.indexOf("/apps/"),p=l.substring(c+6).split("/")[0];if(p){let d=t.resolveRepoPath(`apps/${p}`),f=t.resolveRepoPath(`apps/${p}/next.config.js`);t.pathExists(f)&&(s=d,t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root detected from process.cwd(): ${s}`))}}}catch{}}!n&&!s&&(s=process.cwd(),t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root fallback to process.cwd(): ${s}`))}return{appRoot:s,appRootSet:n}}import ro from"node:fs";function fn({postcssImport:r,postcssNesting:e,autoprefixer:t,resolve:n}){return{plugins:[n?r({resolve:n}):r,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function qs(r){return(e,t)=>{let n=r.resolvePackage(e,t);if(n)return n;if(e.startsWith("@donotdev/")){let s=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),a=r.resolveFrameworkPackage(s,t);if(a){if(o){let l=r.resolvePath(o,a);if(r.pathExists(l))return l;let c=l+".css";if(r.pathExists(c))return c}let i=r.resolvePath("index.css",a);if(r.pathExists(i))return i}}return r.resolvePath(e,t)}}async function Js(){let[r,e,t]=await Promise.all([import("postcss-import").then(s=>s.default),import("postcss-nesting").then(s=>s.default),import("autoprefixer").then(s=>s.default)]),n=O.getInstance();return fn({postcssImport:r,postcssNesting:e,autoprefixer:t,resolve:qs(n)})}import{renameSync as Vs}from"node:fs";import{basename as hn,dirname as Ks,join as gt,relative as Ys}from"node:path";var he="next",Xs=["tsx","ts","jsx","js"],gn=Xs.map(r=>`${he}.${r}`);function j(r,e){return`${r}.${he}.${e}`}var Zs=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],Qs=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],eo=["proxy","middleware","instrumentation"],to="// Generated by @donotdev/config";function ht(r,e){let t=r.match(new RegExp(`^(.+?)(\\.${he})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,n,s,o]=t;return e.includes(n)?{name:n,extension:o,marked:!!s}:null}function no(r){let e=[],t=r.resolveAppPath("src/app"),n=s=>{for(let o of r.readdirSync(s,{withFileTypes:!0})){let a=gt(s,o.name);if(o.isDirectory()){n(a);continue}if(!o.isFile())continue;let i=ht(o.name,Zs);i&&e.push({file:a,...i,metadata:!1});let l=ht(o.name,Qs);l&&e.push({file:a,...l,metadata:!0})}};r.pathExists(t)&&n(t);for(let s of[r.resolveAppPath("src"),r.getAppRoot()])if(r.pathExists(s))for(let o of r.readdirSync(s,{withFileTypes:!0})){let a=o.isFile()&&ht(o.name,eo);a&&e.push({file:gt(s,o.name),...a,metadata:!1})}return e}function mn({pathResolver:r,logger:e,isCI:t}){let n=r.getAppRoot(),s=c=>Ys(n,c),o=[],a=[],i=[],l=[];for(let c of no(r)){let u=r.readSync(c.file,{format:"text"})||"";if(!c.marked&&u.startsWith(to)){r.removeSync(c.file),a.push(s(c.file));continue}c.metadata?l.push(s(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/${j("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 .${he}. marker (src/pages is never a Next route). Rename: `+i.map(({file:c,name:u,extension:p})=>`${s(c)} \u2192 ${j(u,p)}`).join(", ")+". Running the app once in development renames them.");for(let{file:c,name:u,extension:p}of i){let d=gt(Ks(c),j(u,p));if(r.pathExists(d))throw new Error(`[dndev] Both ${s(c)} and ${s(d)} exist. Next only reads *.${he}.* files: merge ${hn(c)} into ${hn(d)} and delete it.`);Vs(c,d),o.push(s(c))}return o.length>0&&e.warn(`Next files renamed to *.${he}.* (src/pages is never a Next route): ${o.join(", ")}. Commit the renames.`),a.length>0&&e.debug(`Removed generated Next files without marker: ${a.join(", ")}`),{renamed:o,removed:a}}function yn(r){return r&&typeof r=="object"&&!Array.isArray(r)}function vn({originalRewrites:r,handlers:e,logger:t}){return async function(){try{let n=r?await r():[],o=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(n)?[]:n?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(n)?n:n?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(n)?[]:n?.fallback||[],...o.fallback]}}catch(n){return t.error(`Next.js config failed to merge rewrites: ${n.message}`),t.error(`Stack: ${n.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function bn({originalRedirects:r,seoRedirects:e,logger:t}){return async function(){try{let n=r?await r():[],s=(e||[]).map(({from:l,to:c,permanent:u})=>({source:l,destination:c,permanent:u!==!1})),o=[],a=new Set;for(let l of s){let c=l.source.replace(/\/+$/,"")||"/",u=l.destination.replace(/\/+$/,"")||"/";if(c===u){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(a.has(c)){t.warn(`Duplicate redirect source: "${l.source}" (skipped)`);continue}a.add(c),o.push(l)}let i=[...Array.isArray(n)?n:[],...o];return i.length===0?[]:(t.info(` \u{1F4CE} ${i.length} redirect${i.length>1?"s":""} configured`),i)}catch(n){return t.error(`Failed to merge redirects: ${n.message}`),[]}}}function wn({policyRules:r,originalHeaders:e}){if(e!==void 0&&typeof e!="function")throw new Error("[dndev] next.config headers must be a function returning an array (Next headers() contract).");return async function(){let n=e?await e():[];if(!Array.isArray(n))throw new Error(`[dndev] next.config headers() must return an array (got ${typeof n}).`);return[...r,...n]}}function Sn({restNextConfig:r,discoveredPackages:e,reactCompiler:t=!1,routingMode:n,rewritesConfig:s,redirectsConfig:o,headersConfig:a,missingOptionalDeps:i,pathResolver:l,env:c,logger:u}){let p=r?.output==="export";if(n==="app"&&r?.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 f=r?.distDir||".next";return{transpilePackages:[...e,...i||[]],...t?{reactCompiler:t}:{},...yn(r)?r:(u.warn("restNextConfig is not a plain object:",r),{}),...n==="app"&&{pageExtensions:gn},...n==="app"&&{experimental:{...r?.experimental,globalNotFound:!0}},serverExternalPackages:(r?.serverExternalPackages||r?.serverComponentsExternalPackages||[]).filter(m=>!m.startsWith("@donotdev/")&&!i?.includes(m)),turbopack:{...r?.turbopack||{},root:r?.turbopack?.root||l.getRepoRoot(),resolveAlias:{...r?.turbopack?.resolveAlias||{},[rn.blog]:(()=>{try{let m=l.resolveAppPath(L.next.blogContent);if(ro.existsSync(m))return"./"+L.next.blogContent}catch{}return"@donotdev/core/empty"})(),...i?.length>0?Object.fromEntries(i.flatMap(m=>[[m,"@donotdev/core/empty"],[`${m}/*`,"@donotdev/core/empty"]])):{}}},distDir:f,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...p?{}:{rewrites:s,...o?{redirects:o}:{},...a?{headers:a}:{}},env:c,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}import{createHash as Mo}from"node:crypto";function x(r,e,t="configuration-error",n={}){let s=`[${r}] ${e}`,o=new Error(s);return o.code=t,o.pluginName=r,o.context=n,o}function ce(r){return r instanceof Error&&typeof r.pluginName=="string"}function En(r,e,t,n={}){return x(r,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},n))}var xn="src/**/*.{ts,tsx,js,jsx,mjs,cjs}",mt=/\/\*[\s\S]*?\*\//g,so=/(^|\s)\/\/.*$/gm,oo=/<!--[\s\S]*?-->/g,ao=/(?:from\s*|import\s*\(\s*|require\s*\(\s*)['"]next\/font(?:\/[^'"]*)?['"]/g,io=/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)['"]@fontsource(?:-variable)?\/[^'"]*['"]/g,lo=/@import\s+(?:url\(\s*)?['"]?@fontsource(?:-variable)?\/[^'";)]*/g,Rn=/@font-face\b/g,$n="Name the family in src/themes.css (e.g. --font-sans: Manrope, 'Manrope Fallback', sans-serif;) and keep @fontsource-variable/<slug> or @fontsource/<slug> in package.json, or declare its woff2 files in appConfig.fonts.",co={"next-font":{message:`imports next/font: its preload cannot work in a framework app (page files carry the \`.next.\` marker, Next's font manifest is keyed without it) and it is a second font pipeline. The framework ships the theme's fonts (preloaded, inline @font-face, size-matched fallback). ${$n}`},fontsource:{message:`imports an @fontsource package: the framework ships the fonts the theme names (preloaded, inline @font-face, hashed /fonts/ files). Remove the import. ${$n}`},"font-face":{message:"declares @font-face: the framework writes every @font-face of the app (one place, preloaded, hashed files). Declare the woff2 files in appConfig.fonts (src/config/app.ts: { category, faces: [{ file, weight, unicodeRange? }] }) and name the family in src/themes.css."}};function uo(r,e){let t=r;for(let n of e)t=t.replace(n,(s,o)=>{let a=typeof o=="string"?o:"";return a+s.slice(a.length).replace(/[^\n]/g," ")});return t}var po=(r,e)=>r.slice(0,e).split(`
|
|
4
|
+
`).length;function fo(r){let e=[];for(let{file:t,content:n}of r){if(/\.generated\.[a-z]+$/.test(t))continue;let s=t.endsWith(".css"),o=t.endsWith(".html"),a=uo(n,o?[oo,mt]:s?[mt]:[mt,so]),i=s?[["fontsource",lo],["font-face",Rn]]:o?[["font-face",Rn]]:[["next-font",ao],["fontsource",io]];for(let[l,c]of i)for(let u of a.matchAll(c))e.push({file:t,line:po(a,u.index),rule:l})}return e}function Pn(r){let e=fo(r);if(e.length===0)return;let t=e.map(({file:n,line:s,rule:o})=>` ${n}:${s} ${co[o].message}`);throw x("dndev-fonts",`the app loads fonts itself; the framework font plan is the one way:
|
|
6
5
|
${t.join(`
|
|
7
|
-
`)}`,"configuration-error")}import{brotliDecompressSync as
|
|
8
|
-
`)}var Ro=2001684018,Ge=400;function He(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function $o(r){let[e,t=e]=String(r).trim().split(/\s+/).map(Number);return[e,t]}var ze=([r,e],t)=>t>=r&&t<=e;function Dn(r,e){if(e.some(o=>ze(o,r)))return r;let t=[...new Set(e.flat())],n=(o=1/0)=>t.filter(a=>a>r&&a<=o).sort((a,i)=>a-i)[0],s=()=>t.filter(o=>o<r).sort((o,a)=>a-o)[0];return r>=400&&r<=500?n(500)??s()??n():r<400?s()??n():n()??s()}function Q(r){return C("dndev-fonts",r,"configuration-error")}function xo(r){return!!(r&&r.length>=4&&r.readUInt32BE(0)===Ro)}var Po=r=>r==="serif"?"serif":"sans-serif";function Co({family:r,packageName:e,dir:t,pathResolver:n}){let s=n.readSync(n.resolvePath("metadata.json",t),{format:"json"}),o=n.readSync(n.resolvePath("unicode.json",t),{format:"json"});if(!s||!o)throw Q(`${e}: metadata.json or unicode.json missing in ${t} (not a fontsource package?).`);if(String(s.family).toLowerCase()!==r.toLowerCase())throw Q(`${e} is the family '${s.family}', the font stack names '${r}'. Write the family as the package names it.`);let a=e.startsWith("@fontsource-variable/"),i=s.variable?.wght;if(a&&!i)throw Q(`${e} has no wght axis: use @fontsource/${s.id} (static weights).`);let l=a?[Number(i.min),Number(i.max)]:null,u=["normal","italic"].filter(h=>s.styles.includes(h)),c=(h,m,y)=>n.resolvePath(`files/${s.id}-${h}-${a?"wght":m}-${y}.woff2`,t),p=h=>{if(!n.pathExists(h))throw Q(`${e}: font file missing: ${h}`);return h},d=s.subsets.includes("latin")?"latin":s.defSubset,f=s.weights.reduce((h,m)=>Math.abs(m-Ge)<Math.abs(h-Ge)?m:h);return{family:r,kind:a?"variable":"static",category:Po(s.category),label:e,provides:h=>a?ze(l,h):s.weights.includes(h),matchWeight:h=>Dn(h,a?[l]:s.weights.map(m=>[m,m])),faces({weights:h,subsets:m}){let y=m.filter(R=>s.subsets.includes(R)),S=a?[`${l[0]} ${l[1]}`]:h.map(String),T=[];for(let R of y)for(let v of S)for(let x of u)T.push({file:p(c(R,v,x)),weight:v,style:x,subset:R,unicodeRange:o[R]??null});return T},metricsFile:p(c(d,f,"normal"))}}function Ao({family:r,config:e,pathResolver:t}){let n=`appConfig.fonts['${r}']`;if(e?.category!=="sans-serif"&&e?.category!=="serif")throw Q(`${n}.category must be 'sans-serif' or 'serif' (picks the size-matched fallback face's system font).`);if(!Array.isArray(e.faces)||e.faces.length===0)throw Q(`${n}.faces must list the family's woff2 files ({ file, weight, style?, unicodeRange?, subset? }).`);let s=e.faces.map((u,c)=>{let p=`${n}.faces[${c}]`;if(typeof u?.file!="string"||!u.file.endsWith(".woff2"))throw Q(`${p}.file must be a .woff2 path relative to the app root (e.g. 'src/assets/fonts/brand.woff2').`);let[d,f]=$o(u.weight);if(!Number.isFinite(d)||!Number.isFinite(f)||d>f)throw Q(`${p}.weight must be a weight (400) or a variable range ('300 600'). Got ${JSON.stringify(u.weight)}.`);let h=u.style??"normal";if(h!=="normal"&&h!=="italic")throw Q(`${p}.style must be 'normal' or 'italic'.`);let m=t.resolveAppPath(u.file),y=t.pathExists(m)?t.readSync(m,{format:"buffer"}):null;if(!y)throw Q(`${p}.file: ${u.file} does not exist.`);if(!xo(y))throw Q(`${p}.file: ${u.file} is not a woff2 font.`);return{file:m,weight:d===f?String(d):`${d} ${f}`,range:[d,f],style:h,subset:u.subset??null,unicodeRange:u.unicodeRange??null}}),o=s.filter(u=>u.style==="normal"),a=o.filter(u=>u.unicodeRange===null),i=({range:u})=>ze(u,Ge)?0:Math.min(...u.map(c=>Math.abs(c-Ge))),l=[...a.length>0?a:o].sort((u,c)=>i(u)-i(c))[0];if(!l)throw Q(`${n}.faces has no normal-style face: the size-matched fallback face is measured on one.`);return{family:r,kind:"local",category:e.category,label:n,provides:u=>o.some(c=>ze(c.range,u)),matchWeight:u=>Dn(u,o.map(c=>c.range)),faces:()=>s.map(({range:u,...c})=>c),metricsFile:l.file}}function No(r,e,t){if(!e)return null;let n=t.resolvePackage(`${r}/package.json`,e);return n?t.getDirname(n):null}function Tn(r,{appFonts:e={},appRoot:t,uiRoot:n,pathResolver:s}){let o=Object.keys(e).find(i=>i.toLowerCase()===r.toLowerCase());if(o)return Ao({family:r,config:e[o],pathResolver:s});let a=He(r);for(let i of[t,n])for(let l of[`@fontsource-variable/${a}`,`@fontsource/${a}`]){let u=No(l,i,s);if(u)return Co({family:r,packageName:l,dir:u,pathResolver:s})}return null}var vt=Object.freeze({body:"--font-family",headline:"--font-headline",mono:"--font-mono"}),_o="--font-weight-",se=":root",ko="@donotdev/components/styles",Do=/\/\*[\s\S]*?\*\//g,To=/([^{}]+)\{([^{}]*)\}/g,Oo=/^(?::root|html|:where\(:root\))$/,Fo=/^(?::root|html)?\.([a-z][\w-]*)$/i,bt=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/,On={normal:400,bold:700};function wt(r){let e=[],t=0,n="",s=0;for(let o=0;o<r.length;o++){let a=r[o];n?a===n&&(n=""):a==='"'||a==="'"?n=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(r.slice(s,o)),s=o+1)}return e.push(r.slice(s)),e.map(o=>o.trim()).filter(Boolean)}function Io(r){return r.replace(/^['"]|['"]$/g,"").trim()}function Lo(r){if(Oo.test(r))return se;let e=Fo.exec(r);return e?e[1]:null}function Fn(r,e=""){let t=new Map,n=r.replace(Do,"");for(let[,s,o]of n.matchAll(To)){let a=s.split(";").pop(),i=wt(a).map(Lo).filter(l=>l!==null);if(i.length!==0)for(let l of o.split(";")){let u=l.indexOf(":");if(u===-1)continue;let c=l.slice(0,u).trim();if(!c.startsWith("--"))continue;let p=l.slice(u+1).replace(/!important\s*$/,"").replace(/\s+/g," ").trim();for(let d of i)t.has(d)||t.set(d,new Map),t.get(d).set(c,{value:p,source:e,scope:d})}}return t}function Mo(r){let e=new Map;for(let t of r)for(let[n,s]of t){e.has(n)||e.set(n,new Map);for(let[o,a]of s)e.get(n).set(o,a)}return e}function In({source:r,scope:e}){return`${r||"CSS"} (${e===se?":root":`.${e}`})`}function mt(r,e,t,n){let s=[];for(let o of wt(e)){let a=bt.exec(o);if(!a){s.push(Io(o));continue}let[,i,l]=a;if(t.has(i)&&!n.has(i))s.push(...mt(i,t.get(i).value,t,new Set([...n,i])));else if(l!==void 0)s.push(...mt(r,l,t,n));else throw C("dndev-fonts",`${r}: ${e} uses var(${i}), which no theme CSS defines (src/**/*.css and the framework tokens). Name the font family in the stack itself, e.g. ${r}: Manrope, 'Manrope Fallback', sans-serif; (a next/font or other runtime class variable is not a framework font).`,"configuration-error")}return s}function Uo(r,e){let t=new Set,n=r;for(;e.has(n)&&!t.has(n);){t.add(n);let s=e.get(n),o=wt(s.value),a=o[0]&&bt.exec(o[0]);if(!a)return{token:n,declaration:s,entries:o};n=a[1]}return null}function yt(r,e,t=new Set){let{value:n}=e.get(r),s=bt.exec(n);if(s){let[,a,i]=s;if(e.has(a)&&!t.has(a))return yt(a,e,new Set([...t,r]));if(i!==void 0)return yt(r,new Map([[r,{value:i.trim()}]]),t)}if(n in On)return On[n];let o=Number(n);if(Number.isFinite(o)&&o>=1&&o<=1e3)return o;throw C("dndev-fonts",`${r}: ${n} is not a font weight (a number from 1 to 1000, normal or bold): the font plan ships the weights the --font-weight-* tokens name.`,"configuration-error")}function Ln({frameworkCss:r,appCss:e}){if(typeof r!="string"||!Array.isArray(e))throw new Error("resolveThemeFonts: frameworkCss (string) and appCss ({ file, css }[]) are required (ThemeDiscovery fontCss)");let t=Fn(r,ko),n=Mo(e.map(({file:o,css:a})=>Fn(a,o)));return[se,...new Set([...t.keys(),...n.keys()])].filter((o,a,i)=>i.indexOf(o)===a).map(o=>{let a=new Map([...t.get(se)??[],...n.get(se)??[],...o===se?[]:t.get(o)??[],...o===se?[]:n.get(o)??[]]),i={};for(let[u,c]of Object.entries(vt))a.has(c)&&(i[u]={stack:mt(c,a.get(c).value,a,new Set([c])),origin:Uo(c,a)});let l=new Map;for(let u of a.keys())u.startsWith(_o)&&l.set(u,{weight:yt(u,a),declaration:a.get(u)});return{scope:o,roles:i,weights:l}})}var Un="optional",Et=le.fonts,Rt=`/${Et}`,Bo=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),Go=new Set(en.map(r=>r.toLowerCase())),zo="--font-weight-normal",Ho="--font-weight-bold",St=r=>C("dndev-fonts",r,"configuration-error");function Mn(r){let e=tn[r];return e&&e.length>0?[...e]:["latin"]}var jn=r=>`'${r.replace(/'/g,"\\'")}'`;function Wo(r,e){return["@font-face{",`font-family:${jn(r)};`,`font-style:${e.style};`,`font-weight:${e.weight};`,`font-display:${Un};`,`src:url(${e.url}) format('woff2');`,e.unicodeRange?`unicode-range:${e.unicodeRange};`:"","}"].join("")}function qo(r,e){let[t,n=t]=r.split(" ").map(Number);return e>=t&&e<=n}async function Bn({fontCss:r,appFonts:e={},languages:t,publicPath:n="",indexHtml:s=null,pathResolver:o}){if(!r||typeof r.framework!="string"||!Array.isArray(r.app))throw new Error("[dndev-fonts] buildFontPlan: fontCss is required (ThemeDiscovery fontCss: theme discovery failed?)");if(!Array.isArray(t)||t.length===0)throw new Error("[dndev-fonts] buildFontPlan: languages is required (i18n discovery supportedLanguages)");let a=o.getAppRoot(),i=await o.findFiles(a,$n);xn([...r.app.map(({file:g,css:b})=>({file:g,content:b})),...i.map(g=>({file:o.getRelativePath(g),content:o.readSync(g,{format:"text"})??""})),...s===null?[]:[{file:"index.html",content:s}]]);let l=Ln({frameworkCss:r.framework,appCss:r.app}),u=o.resolveFrameworkPackage("@donotdev/ui"),c=new Map,p=g=>{let b=g.toLowerCase();return c.has(b)||c.set(b,Tn(g,{appFonts:e,appRoot:a,uiRoot:u,pathResolver:o})),c.get(b)},d=new Map,f=new Map,h=new Map,m=new Map,y=new Map;for(let{scope:g,roles:b,weights:k}of l)for(let[N,_]of Object.entries(b)){if(!_)continue;let F=vt[N];_.stack.forEach((A,G)=>{let j=A.toLowerCase();if(Bo.has(j)||Go.has(j))return;let re=/^(.+) fallback$/i.exec(A)?.[1];if(re&&p(re))return;let w=p(A);if(!w){d.has(j)||d.set(j,{family:A,token:F,scope:g});return}m.has(j)||m.set(j,{source:w,weights:new Set,scopes:new Set});let E=m.get(j);E.scopes.add(g);for(let{weight:ie}of k.values())E.weights.add(w.matchWeight(ie)),!w.provides(ie)&&!h.has(`${j}:${ie}`)&&h.set(`${j}:${ie}`,`${w.family}: weight ${ie} not in source, browser-synthesized`);if(G!==0)return;y.set(j,w);let P=_.origin,I=P?P.entries[1]:_.stack[1],V=Be(A);if(I&&I.replace(/^['"]|['"]$/g,"").trim().toLowerCase()===V.toLowerCase())return;let ge=P?.declaration??{source:"",scope:g},de=P?.token??F,me=`${ge.source}|${de}|${ge.value??A}`;if(f.has(me))return;let Ie=P?P.entries:[A],it=`${de}: ${[Ie[0],jn(V),...Ie.slice(1)].join(", ")};`;f.set(me,{location:In(ge),declared:de,family:A,expected:V,line:it})})}let S=[];for(let{family:g,token:b,scope:k}of d.values())S.push(`${b} (${k===se?":root":`.${k}`}) names '${g}', which nothing provides: install @fontsource-variable/${He(g)} or @fontsource/${He(g)} in the app, declare its woff2 files in appConfig.fonts['${g}'], or use a system family (SYSTEM_FONT_FAMILIES) or a generic one (sans-serif, serif, monospace, system-ui\u2026).`);for(let{location:g,declared:b,family:k,expected:N,line:_}of f.values())S.push(`${g}: ${b} lacks '${N}' right after '${k}' (the size-matched fallback face: no layout shift, no flicker). Write:
|
|
9
|
-
${
|
|
6
|
+
`)}`,"configuration-error")}import{brotliDecompressSync as ho}from"node:zlib";var Cn="aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ",go={"sans-serif":{locals:["Arial","Liberation Sans"],azAvgWidth:934.5116279069767,unitsPerEm:2048},serif:{locals:["Times New Roman","Liberation Serif"],azAvgWidth:854.3953488372093,unitsPerEm:2048}},mo={0:"cmap",1:"head",2:"hhea",3:"hmtx"},yo=63,An=48,vo=2001684018;function Nn(r,e){let t=0;for(let n=0;n<5;n++){let s=r[e+n];if(t=t*128+(s&127),(s&128)===0)return[t,e+n+1]}throw new Error("woff2: invalid UIntBase128")}function bo(r){if(r.length<An||r.readUInt32BE(0)!==vo)throw new Error("woff2: bad signature");if(r.readUInt32BE(4)===1953784678)throw new Error("woff2: font collections are not supported");let e=r.readUInt16BE(12),t=r.readUInt32BE(20),n=An,s=[];for(let l=0;l<e;l++){let c=r[n++],u=c&63,p=c>>6,d=mo[u]??`#${u}`;u===yo&&(d=r.toString("latin1",n,n+4),n+=4);let f;[f,n]=Nn(r,n);let h=u===10||u===11?p!==3:p!==0,m=f;h&&([m,n]=Nn(r,n)),s.push({tag:d,length:m,transformed:h})}let o=ho(r.subarray(n,n+t)),a=new Map,i=0;for(let{tag:l,length:c,transformed:u}of s)a.set(l,{data:o.subarray(i,i+c),transformed:u}),i+=c;return a}function wo(r){let e=r.readUInt16BE(2),t=[];for(let u=0;u<e;u++){let p=4+u*8,d=r.readUInt16BE(p),f=r.readUInt16BE(p+2),h=r.readUInt32BE(p+4);(d===0||d===3&&(f===1||f===10))&&t.push({offset:h,format:r.readUInt16BE(h)})}let n=t.find(u=>u.format===12)??t.find(u=>u.format===4);if(!n)throw new Error("font: no Unicode cmap (format 4 or 12)");let s=n.offset;if(n.format===12){let u=r.readUInt32BE(s+12);return p=>{for(let d=0;d<u;d++){let f=s+16+d*12,h=r.readUInt32BE(f),m=r.readUInt32BE(f+4);if(p>=h&&p<=m)return r.readUInt32BE(f+8)+(p-h)}return 0}}let o=r.readUInt16BE(s+6)/2,a=s+14,i=a+o*2+2,l=i+o*2,c=l+o*2;return u=>{for(let p=0;p<o;p++){if(u>r.readUInt16BE(a+p*2))continue;let d=r.readUInt16BE(i+p*2);if(u<d)return 0;let f=r.readInt16BE(l+p*2),h=c+p*2,m=r.readUInt16BE(h);if(m===0)return u+f&65535;let y=r.readUInt16BE(h+m+(u-d)*2);return y===0?0:y+f&65535}return 0}}function kn(r){let e=bo(r);for(let c of["head","hhea","hmtx","cmap"])if(!e.has(c))throw new Error(`font: missing ${c} table`);let t=e.get("head").data,n=e.get("hhea").data,s=e.get("hmtx"),o=n.readUInt16BE(34),a=c=>{let u=Math.min(c,o-1);return s.transformed?s.data.readUInt16BE(1+u*2):s.data.readUInt16BE(u*4)},i=wo(e.get("cmap").data),l=0;for(let c of Cn){let u=i(c.codePointAt(0));if(u===0)throw new Error(`font: no glyph for '${c}'`);l+=a(u)}return{unitsPerEm:t.readUInt16BE(18),ascent:n.readInt16BE(4),descent:n.readInt16BE(6),lineGap:n.readInt16BE(8),azAvgWidth:l/Cn.length}}var _n=r=>`${Math.abs(r*100).toFixed(2)}%`;function Be(r){return`${r} Fallback`}function Dn({family:r,category:e,metrics:t}){let n=go[e];if(!n)throw new Error(`font fallback: unknown category '${e}'`);let{unitsPerEm:s,ascent:o,descent:a,lineGap:i,azAvgWidth:l}=t,c=l/s/(n.azAvgWidth/n.unitsPerEm),u=d=>_n(d/(s*c)),p=Be(r);return[`/* ${p}: ${n.locals[0]} size-matched to ${r} */`,"@font-face {",` font-family: '${p}';`,` src: ${n.locals.map(d=>`local('${d}')`).join(", ")};`,` ascent-override: ${u(o)};`,` descent-override: ${u(a)};`,` line-gap-override: ${u(i)};`,` size-adjust: ${_n(c)};`,"}"].join(`
|
|
7
|
+
`)}var So=2001684018,Ge=400;function He(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function Eo(r){let[e,t=e]=String(r).trim().split(/\s+/).map(Number);return[e,t]}var ze=([r,e],t)=>t>=r&&t<=e;function Tn(r,e){if(e.some(o=>ze(o,r)))return r;let t=[...new Set(e.flat())],n=(o=1/0)=>t.filter(a=>a>r&&a<=o).sort((a,i)=>a-i)[0],s=()=>t.filter(o=>o<r).sort((o,a)=>a-o)[0];return r>=400&&r<=500?n(500)??s()??n():r<400?s()??n():n()??s()}function Q(r){return x("dndev-fonts",r,"configuration-error")}function Ro(r){return!!(r&&r.length>=4&&r.readUInt32BE(0)===So)}var $o=r=>r==="serif"?"serif":"sans-serif";function xo({family:r,packageName:e,dir:t,pathResolver:n}){let s=n.readSync(n.resolvePath("metadata.json",t),{format:"json"}),o=n.readSync(n.resolvePath("unicode.json",t),{format:"json"});if(!s||!o)throw Q(`${e}: metadata.json or unicode.json missing in ${t} (not a fontsource package?).`);if(String(s.family).toLowerCase()!==r.toLowerCase())throw Q(`${e} is the family '${s.family}', the font stack names '${r}'. Write the family as the package names it.`);let a=e.startsWith("@fontsource-variable/"),i=s.variable?.wght;if(a&&!i)throw Q(`${e} has no wght axis: use @fontsource/${s.id} (static weights).`);let l=a?[Number(i.min),Number(i.max)]:null,c=["normal","italic"].filter(h=>s.styles.includes(h)),u=(h,m,y)=>n.resolvePath(`files/${s.id}-${h}-${a?"wght":m}-${y}.woff2`,t),p=h=>{if(!n.pathExists(h))throw Q(`${e}: font file missing: ${h}`);return h},d=s.subsets.includes("latin")?"latin":s.defSubset,f=s.weights.reduce((h,m)=>Math.abs(m-Ge)<Math.abs(h-Ge)?m:h);return{family:r,kind:a?"variable":"static",category:$o(s.category),label:e,provides:h=>a?ze(l,h):s.weights.includes(h),matchWeight:h=>Tn(h,a?[l]:s.weights.map(m=>[m,m])),faces({weights:h,subsets:m}){let y=m.filter(P=>s.subsets.includes(P)),S=a?[`${l[0]} ${l[1]}`]:h.map(String),_=[];for(let P of y)for(let v of S)for(let E of c)_.push({file:p(u(P,v,E)),weight:v,style:E,subset:P,unicodeRange:o[P]??null});return _},metricsFile:p(u(d,f,"normal"))}}function Po({family:r,config:e,pathResolver:t}){let n=`appConfig.fonts['${r}']`;if(e?.category!=="sans-serif"&&e?.category!=="serif")throw Q(`${n}.category must be 'sans-serif' or 'serif' (picks the size-matched fallback face's system font).`);if(!Array.isArray(e.faces)||e.faces.length===0)throw Q(`${n}.faces must list the family's woff2 files ({ file, weight, style?, unicodeRange?, subset? }).`);let s=e.faces.map((c,u)=>{let p=`${n}.faces[${u}]`;if(typeof c?.file!="string"||!c.file.endsWith(".woff2"))throw Q(`${p}.file must be a .woff2 path relative to the app root (e.g. 'src/assets/fonts/brand.woff2').`);let[d,f]=Eo(c.weight);if(!Number.isFinite(d)||!Number.isFinite(f)||d>f)throw Q(`${p}.weight must be a weight (400) or a variable range ('300 600'). Got ${JSON.stringify(c.weight)}.`);let h=c.style??"normal";if(h!=="normal"&&h!=="italic")throw Q(`${p}.style must be 'normal' or 'italic'.`);let m=t.resolveAppPath(c.file),y=t.pathExists(m)?t.readSync(m,{format:"buffer"}):null;if(!y)throw Q(`${p}.file: ${c.file} does not exist.`);if(!Ro(y))throw Q(`${p}.file: ${c.file} is not a woff2 font.`);return{file:m,weight:d===f?String(d):`${d} ${f}`,range:[d,f],style:h,subset:c.subset??null,unicodeRange:c.unicodeRange??null}}),o=s.filter(c=>c.style==="normal"),a=o.filter(c=>c.unicodeRange===null),i=({range:c})=>ze(c,Ge)?0:Math.min(...c.map(u=>Math.abs(u-Ge))),l=[...a.length>0?a:o].sort((c,u)=>i(c)-i(u))[0];if(!l)throw Q(`${n}.faces has no normal-style face: the size-matched fallback face is measured on one.`);return{family:r,kind:"local",category:e.category,label:n,provides:c=>o.some(u=>ze(u.range,c)),matchWeight:c=>Tn(c,o.map(u=>u.range)),faces:()=>s.map(({range:c,...u})=>u),metricsFile:l.file}}function Co(r,e,t){if(!e)return null;let n=t.resolvePackage(`${r}/package.json`,e);return n?t.getDirname(n):null}function On(r,{appFonts:e={},appRoot:t,uiRoot:n,pathResolver:s}){let o=Object.keys(e).find(i=>i.toLowerCase()===r.toLowerCase());if(o)return Po({family:r,config:e[o],pathResolver:s});let a=He(r);for(let i of[t,n])for(let l of[`@fontsource-variable/${a}`,`@fontsource/${a}`]){let c=Co(l,i,s);if(c)return xo({family:r,packageName:l,dir:c,pathResolver:s})}return null}var bt=Object.freeze({body:"--font-family",headline:"--font-headline",mono:"--font-mono"}),Ao="--font-weight-",se=":root",No="@donotdev/components/styles",_o=/\/\*[\s\S]*?\*\//g,ko=/([^{}]+)\{([^{}]*)\}/g,Do=/^(?::root|html|:where\(:root\))$/,To=/^(?::root|html)?\.([a-z][\w-]*)$/i,wt=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/,Fn={normal:400,bold:700};function St(r){let e=[],t=0,n="",s=0;for(let o=0;o<r.length;o++){let a=r[o];n?a===n&&(n=""):a==='"'||a==="'"?n=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(r.slice(s,o)),s=o+1)}return e.push(r.slice(s)),e.map(o=>o.trim()).filter(Boolean)}function Oo(r){return r.replace(/^['"]|['"]$/g,"").trim()}function Fo(r){if(Do.test(r))return se;let e=To.exec(r);return e?e[1]:null}function In(r,e=""){let t=new Map,n=r.replace(_o,"");for(let[,s,o]of n.matchAll(ko)){let a=s.split(";").pop(),i=St(a).map(Fo).filter(l=>l!==null);if(i.length!==0)for(let l of o.split(";")){let c=l.indexOf(":");if(c===-1)continue;let u=l.slice(0,c).trim();if(!u.startsWith("--"))continue;let p=l.slice(c+1).replace(/!important\s*$/,"").replace(/\s+/g," ").trim();for(let d of i)t.has(d)||t.set(d,new Map),t.get(d).set(u,{value:p,source:e,scope:d})}}return t}function Io(r){let e=new Map;for(let t of r)for(let[n,s]of t){e.has(n)||e.set(n,new Map);for(let[o,a]of s)e.get(n).set(o,a)}return e}function Ln({source:r,scope:e}){return`${r||"CSS"} (${e===se?":root":`.${e}`})`}function yt(r,e,t,n){let s=[];for(let o of St(e)){let a=wt.exec(o);if(!a){s.push(Oo(o));continue}let[,i,l]=a;if(t.has(i)&&!n.has(i))s.push(...yt(i,t.get(i).value,t,new Set([...n,i])));else if(l!==void 0)s.push(...yt(r,l,t,n));else throw x("dndev-fonts",`${r}: ${e} uses var(${i}), which no theme CSS defines (src/**/*.css and the framework tokens). Name the font family in the stack itself, e.g. ${r}: Manrope, 'Manrope Fallback', sans-serif; (a next/font or other runtime class variable is not a framework font).`,"configuration-error")}return s}function Lo(r,e){let t=new Set,n=r;for(;e.has(n)&&!t.has(n);){t.add(n);let s=e.get(n),o=St(s.value),a=o[0]&&wt.exec(o[0]);if(!a)return{token:n,declaration:s,entries:o};n=a[1]}return null}function vt(r,e,t=new Set){let{value:n}=e.get(r),s=wt.exec(n);if(s){let[,a,i]=s;if(e.has(a)&&!t.has(a))return vt(a,e,new Set([...t,r]));if(i!==void 0)return vt(r,new Map([[r,{value:i.trim()}]]),t)}if(n in Fn)return Fn[n];let o=Number(n);if(Number.isFinite(o)&&o>=1&&o<=1e3)return o;throw x("dndev-fonts",`${r}: ${n} is not a font weight (a number from 1 to 1000, normal or bold): the font plan ships the weights the --font-weight-* tokens name.`,"configuration-error")}function Mn({frameworkCss:r,appCss:e}){if(typeof r!="string"||!Array.isArray(e))throw new Error("resolveThemeFonts: frameworkCss (string) and appCss ({ file, css }[]) are required (ThemeDiscovery fontCss)");let t=In(r,No),n=Io(e.map(({file:o,css:a})=>In(a,o)));return[se,...new Set([...t.keys(),...n.keys()])].filter((o,a,i)=>i.indexOf(o)===a).map(o=>{let a=new Map([...t.get(se)??[],...n.get(se)??[],...o===se?[]:t.get(o)??[],...o===se?[]:n.get(o)??[]]),i={};for(let[c,u]of Object.entries(bt))a.has(u)&&(i[c]={stack:yt(u,a.get(u).value,a,new Set([u])),origin:Lo(u,a)});let l=new Map;for(let c of a.keys())c.startsWith(Ao)&&l.set(c,{weight:vt(c,a),declaration:a.get(c)});return{scope:o,roles:i,weights:l}})}var jn="optional",Rt=le.fonts,$t=`/${Rt}`,Uo=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),jo=new Set(sn.map(r=>r.toLowerCase())),Bo="--font-weight-normal",Go="--font-weight-bold",Et=r=>x("dndev-fonts",r,"configuration-error");function Un(r){let e=on[r];return e&&e.length>0?[...e]:["latin"]}var Bn=r=>`'${r.replace(/'/g,"\\'")}'`;function zo(r,e){return["@font-face{",`font-family:${Bn(r)};`,`font-style:${e.style};`,`font-weight:${e.weight};`,`font-display:${jn};`,`src:url(${e.url}) format('woff2');`,e.unicodeRange?`unicode-range:${e.unicodeRange};`:"","}"].join("")}function Ho(r,e){let[t,n=t]=r.split(" ").map(Number);return e>=t&&e<=n}async function Gn({fontCss:r,appFonts:e={},languages:t,publicPath:n="",indexHtml:s=null,pathResolver:o}){if(!r||typeof r.framework!="string"||!Array.isArray(r.app))throw new Error("[dndev-fonts] buildFontPlan: fontCss is required (ThemeDiscovery fontCss: theme discovery failed?)");if(!Array.isArray(t)||t.length===0)throw new Error("[dndev-fonts] buildFontPlan: languages is required (i18n discovery supportedLanguages)");let a=o.getAppRoot(),i=await o.findFiles(a,xn);Pn([...r.app.map(({file:g,css:b})=>({file:g,content:b})),...i.map(g=>({file:o.getRelativePath(g),content:o.readSync(g,{format:"text"})??""})),...s===null?[]:[{file:"index.html",content:s}]]);let l=Mn({frameworkCss:r.framework,appCss:r.app}),c=o.resolveFrameworkPackage("@donotdev/ui"),u=new Map,p=g=>{let b=g.toLowerCase();return u.has(b)||u.set(b,On(g,{appFonts:e,appRoot:a,uiRoot:c,pathResolver:o})),u.get(b)},d=new Map,f=new Map,h=new Map,m=new Map,y=new Map;for(let{scope:g,roles:b,weights:T}of l)for(let[k,D]of Object.entries(b)){if(!D)continue;let F=bt[k];D.stack.forEach((N,G)=>{let B=N.toLowerCase();if(Uo.has(B)||jo.has(B))return;let re=/^(.+) fallback$/i.exec(N)?.[1];if(re&&p(re))return;let w=p(N);if(!w){d.has(B)||d.set(B,{family:N,token:F,scope:g});return}m.has(B)||m.set(B,{source:w,weights:new Set,scopes:new Set});let R=m.get(B);R.scopes.add(g);for(let{weight:ie}of T.values())R.weights.add(w.matchWeight(ie)),!w.provides(ie)&&!h.has(`${B}:${ie}`)&&h.set(`${B}:${ie}`,`${w.family}: weight ${ie} not in source, browser-synthesized`);if(G!==0)return;y.set(B,w);let C=D.origin,I=C?C.entries[1]:D.stack[1],V=Be(N);if(I&&I.replace(/^['"]|['"]$/g,"").trim().toLowerCase()===V.toLowerCase())return;let ge=C?.declaration??{source:"",scope:g},de=C?.token??F,me=`${ge.source}|${de}|${ge.value??N}`;if(f.has(me))return;let Le=C?C.entries:[N],ut=`${de}: ${[Le[0],Bn(V),...Le.slice(1)].join(", ")};`;f.set(me,{location:Ln(ge),declared:de,family:N,expected:V,line:ut})})}let S=[];for(let{family:g,token:b,scope:T}of d.values())S.push(`${b} (${T===se?":root":`.${T}`}) names '${g}', which nothing provides: install @fontsource-variable/${He(g)} or @fontsource/${He(g)} in the app, declare its woff2 files in appConfig.fonts['${g}'], or use a system family (SYSTEM_FONT_FAMILIES) or a generic one (sans-serif, serif, monospace, system-ui\u2026).`);for(let{location:g,declared:b,family:T,expected:k,line:D}of f.values())S.push(`${g}: ${b} lacks '${k}' right after '${T}' (the size-matched fallback face: no layout shift, no flicker). Write:
|
|
8
|
+
${D}`);if(S.length>0)throw Et(`the theme fonts cannot ship:
|
|
10
9
|
- ${S.join(`
|
|
11
|
-
- `)}`);let
|
|
12
|
-
`),preloads:W,notices:[...h.values()]}}function
|
|
13
|
-
export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,
|
|
14
|
-
${
|
|
10
|
+
- `)}`);let _=[...new Set(["latin",...t.flatMap(Un)])],P=new Map,v=g=>{if(!P.has(g)){let b=o.readSync(g,{format:"buffer"}),T=Mo("sha256").update(b).digest("hex").slice(0,8),k=o.getBasename(g).replace(/\.woff2$/,"");P.set(g,`${n}${$t}/${k}.${T}.woff2`)}return P.get(g)},E=[],A=[];for(let[g,{source:b,weights:T}]of m){let k=b.faces({weights:[...T].sort((D,F)=>D-F),subsets:_}).map(D=>({...D,family:b.family,url:v(D.file)}));A.push(...k),E.push({family:b.family,kind:b.kind,category:b.category,source:b.label,fallback:y.has(g)?Be(b.family):null})}let U=[...y.values()].map(g=>{try{return Dn({family:g.family,category:g.category,metrics:kn(o.readSync(g.metricsFile,{format:"buffer"}))})}catch(b){throw Et(`'${g.family}' (${g.label}): cannot measure ${g.metricsFile} for its fallback face (${b.message}). Its core file must be a woff2 with the Latin letters a-z.`)}}),M=l.find(({scope:g})=>g===se),te=[["body",Bo],["headline",Go]].flatMap(([g,b])=>{let T=M.roles[g]?.stack[0];if(!T||!m.has(T.toLowerCase()))return[];let k=M.weights.get(b)?.weight;if(k===void 0)throw Et(`${b} is not defined: the framework tokens (@donotdev/components/styles) define it.`);let{source:D}=m.get(T.toLowerCase());return[{family:D.family,weight:D.matchWeight(k)}]}),W={};for(let g of t){let b=Un(g),T=[];for(let{family:k,weight:D}of te)for(let F of A){if(F.family!==k||F.style!=="normal"||!Ho(F.weight,D))continue;(F.subset===null?F.unicodeRange===null:b.includes(F.subset))&&!T.includes(F.url)&&T.push(F.url)}W[g]=T}return{display:jn,families:E,files:[...P].map(([g,b])=>({source:g,url:b})),css:[...A.map(g=>zo(g.family,g)),...U].join(`
|
|
11
|
+
`),preloads:W,notices:[...h.values()]}}function zn(r,{pathResolver:e,publicPath:t=""}){let n=e.resolveAppPath(`public/${Rt}`);e.removeSync(n),e.ensureDirSync(n);let s=`${t}${$t}/`;for(let{source:o,url:a}of r.files){if(!a.startsWith(s))throw new Error(`[dndev-fonts] writeFontPlan: ${a} is not under ${s}`);e.copySync(o,e.resolvePath(a.slice(s.length),n),{overwrite:!0})}return n}import{existsSync as Pt,readFileSync as xt,realpathSync as Wo}from"node:fs";import{dirname as Hn,join as _e,resolve as Wn}from"node:path";var ue="dndev-routes",We="entities",qo="@donotdev/core",qn=[".ts",".tsx",".js",".jsx"],Jo=`import { productEntity } from 'entities';
|
|
12
|
+
export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,Jn=null;async function Xn(){return Jn??=import("@babel/core").then(r=>r.default??r),Jn}function Zn(r,e,t){let n=/\.[jt]sx$/.test(t);try{return r.parseSync(e,{configFile:!1,babelrc:!1,filename:t,sourceType:"module",parserOpts:{plugins:n?["typescript","jsx"]:["typescript"]}}).program}catch(s){throw x(ue,`${t} could not be parsed to resolve entities (PageMeta entity, entity field types): ${s.message}. Fix the syntax error.`,"invalid-configuration")}}function ve(r){return r.type==="StringLiteral"?r.value:r.name}function $e(r){let e=r;for(;e&&["TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","ParenthesizedExpression"].includes(e.type);)e=e.expression;return e}function Vo(r,e){for(let t of r.body)if(!(t.type!=="ImportDeclaration"||t.importKind==="type")){for(let n of t.specifiers)if(n.local.name===e)return t.source.value!==We||n.type!=="ImportSpecifier"||n.importKind==="type"?null:ve(n.imported)}return null}function ke(r){let e=null,t=new Map;function n(){let u=_e(r,"package.json"),p=Pt(u)?JSON.parse(xt(u,"utf8")):null;return!!(p?.dependencies?.[We]||p?.devDependencies?.[We])}function s(u){if(e)return e;let p=n(),d=r,f=null;for(;p;){let y=_e(d,"node_modules",We);if(Pt(_e(y,"package.json"))){f=Wo(y);break}let S=Hn(d);if(S===d)break;d=S}if(!f)throw x(ue,`${u}, but the app has no \`entities\` package (${p?"not installed: run bun install":"not in the dependencies of its package.json"}). The entity is read from the app's defineEntity definitions. Fix: add \`"entities": "workspace:*"\` to the app's dependencies and export the entity from the entities package.`,"missing-required-resource");let h=JSON.parse(xt(_e(f,"package.json"),"utf8")),m=Yn(Wn(f,h.main??"./index.ts"));if(!m)throw x(ue,`The \`entities\` package (${f}) has no entry module (package.json "main": ${JSON.stringify(h.main??"./index.ts")}). Fix: set "main" to its index file (./index.ts).`,"missing-required-resource");return e=m,e}async function o(u){if(!t.has(u)){let p=await Xn();t.set(u,Zn(p,xt(u,"utf8"),u))}return t.get(u)}function a(u,p){return p.startsWith(".")?Yn(Wn(Hn(u),p)):null}async function i(u,p,d){let f=`${u}#${p}`;if(d.has(f))return null;d.add(f);let h=await o(u),m=[];for(let y of h.body)if(y.type==="ExportNamedDeclaration"&&y.exportKind!=="type"){let S=Kn(y.declaration,p);if(S!==void 0)return{init:S,program:h,file:u};for(let _ of y.specifiers??[]){if(_.exportKind==="type"||ve(_.exported)!==p)continue;if(_.type!=="ExportSpecifier")return null;let P=ve(_.local);if(y.source){let v=a(u,y.source.value);return v?i(v,P,d):null}return l(u,h,P,d)}}else if(y.type==="ExportAllDeclaration"&&y.exportKind!=="type"){let S=a(u,y.source.value);S&&m.push(S)}for(let y of m){let S=await i(y,p,d);if(S)return S}return null}async function l(u,p,d,f){for(let h of p.body){let m=Kn(h,d);if(m!==void 0)return{init:m,program:p,file:u};if(!(h.type!=="ImportDeclaration"||h.importKind==="type"))for(let y of h.specifiers){if(y.local.name!==d||y.type!=="ImportSpecifier")continue;let S=a(u,h.source.value);return S?i(S,ve(y.imported),f):null}}return null}async function c(u){let p=[u];for(let d=0;d<p.length;d+=1){let f=await o(p[d]);for(let h of f.body){if(!(h.type==="ImportDeclaration"&&h.importKind!=="type"||h.type==="ExportNamedDeclaration"&&h.source&&h.exportKind!=="type"||h.type==="ExportAllDeclaration"&&h.exportKind!=="type"))continue;let y=a(p[d],h.source.value);y&&!p.includes(y)&&p.push(y)}}return p}return{async usesFieldType(u){if(!n())return!1;for(let p of await c(s("The app's package.json lists `entities` (its entity field types are read)")))if(Ko(await o(p),u))return!0;return!1},async collectionOf(u,p){let d=await i(s(`${p} declares a PageMeta entity`),u,new Set);if(!d)throw x(ue,`${p}: PageMeta entity \`${u}\` is not exported by the \`entities\` package. The page names the entity definition it shows a record of. Fix: export it from the entities package index (export { ${u} } from './\u2026').`,"invalid-configuration");return Yo(d,u,p)}}}function Qn(r){return r.body.filter(e=>e.type==="ImportDeclaration"&&e.source.value===qo).flatMap(e=>e.specifiers).find(e=>e.type==="ImportSpecifier"&&ve(e.imported)==="defineEntity")?.local.name}function Vn(r,e){if(r?.type!=="ObjectExpression")return;let t=r.properties.find(n=>n.type==="ObjectProperty"&&!n.computed&&ve(n.key)===e);return $e(t?.value)}function Ko(r,e){let t=Qn(r);if(!t)return!1;let n=s=>{if(!s||typeof s.type!="string")return!1;if(s.type==="CallExpression"&&s.callee.type==="Identifier"&&s.callee.name===t){let o=Vn($e(s.arguments[0]),"fields");if(o?.type==="ObjectExpression"&&o.properties.some(a=>{let i=Vn($e(a.value),"type");return i?.type==="StringLiteral"&&i.value===e}))return!0}for(let o of Object.keys(s)){if(o==="loc"||o==="leadingComments"||o==="trailingComments")continue;let a=s[o];if(Array.isArray(a)?a.some(n):a&&typeof a=="object"&&n(a))return!0}return!1};return n(r)}function Kn(r,e){if(r?.type==="VariableDeclaration"){for(let t of r.declarations)if(t.id.type==="Identifier"&&t.id.name===e)return t.init??null}}function Yn(r){let e=r.replace(/\.[cm]?js$/,""),t=[r,...qn.map(n=>`${e}${n}`),...qn.map(n=>_e(r,`index${n}`))];for(let n of t)if(/\.[cm]?[jt]sx?$/.test(n)&&Pt(n))return n;return null}function Yo({init:r,program:e,file:t},n,s){let o=$e(r),a=Qn(e);if(o?.type!=="CallExpression"||o.callee.type!=="Identifier"||!a||o.callee.name!==a)throw x(ue,`${s}: PageMeta entity \`${n}\` (${t}) is not a defineEntity definition. The build reads the collection from \`defineEntity({ collection: ... })\` in the entities package. Fix: export const ${n} = defineEntity({ name: '...', collection: '...', fields: { ... } }) with defineEntity imported from '@donotdev/core'.`,"invalid-configuration");let i=$e(o.arguments[0]),l=i?.type==="ObjectExpression"?i.properties.find(p=>p.type==="ObjectProperty"&&!p.computed&&ve(p.key)==="collection"):void 0,c=$e(l?.value),u=c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0].value.cooked:null;if(!u)throw x(ue,`${s}: PageMeta entity \`${n}\` (${t}) has no literal \`collection\` in its defineEntity options. The page's records (sitemap, prerender, server metadata) are read from it. Fix: set collection: 'products' (a string literal) in the defineEntity call.`,"invalid-configuration");return u}async function er(r,e,t,n){if(!r||r.entity===void 0)return null;let s=r.entity?.identifier,o=r.entity?.expression;if(typeof o=="string"){let l=o.match(/^[A-Za-z_$][\w$]*\s*\??\.\s*([A-Za-z_$][\w$]*)$/)?.[1]??"productEntity";throw x(ue,`${t}: PageMeta entity \`${o}\` is not a bare identifier. The build reads the entity statically: only a defineEntity definition named-imported from 'entities' resolves to its collection (no namespace import, member access or call). Fix: import { ${l} } from 'entities'; then entity: ${l}`,"invalid-configuration")}if(typeof s!="string")throw x(ue,`${t}: PageMeta entity must be the entity definition imported from 'entities' (got ${JSON.stringify(r.entity)}). The build resolves it to the entity's collection. Fix:
|
|
13
|
+
${Jo}`,"invalid-configuration");let a=Zn(await Xn(),e,t),i=Vo(a,s);if(!i)throw x(ue,`${t}: PageMeta entity \`${s}\` is not imported from 'entities'. The page's entity must be a defineEntity definition of the app's \`entities\` package (one source for its collection). Fix: import { ${s} } from 'entities';`,"invalid-configuration");return n.collectionOf(i,t)}var Xo=["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",L.next.revalidateRoute],Zo="dndev-config-",tr=".dndev-build";function Ct(r){if(!r)return!1;let e=O.getInstance(),t=e.resolveAppPath(tr),n=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===n}catch{return!1}}function Qo(r){if(!r)return;let e=O.getInstance(),t=e.resolveAppPath(tr),n=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,n,{overwrite:!0})}catch{}}function ea(r,e,t){if(!r)return;let n=O.getInstance(),s=(a,i)=>{let l=n.normalizePath(a);if(!(t.has(l)||!n.pathExists(l)))try{n.removeSync(a),e.debug(`Removed stale: ${i}`)}catch{}};for(let a of Xo)s(n.resolveAppPath(a),a);let o=n.resolveAppPath("src/config");for(let a of n.readdirSync(o))a.startsWith(Zo)&&a.endsWith(".js")&&s(n.resolvePath(a,o),`src/config/${a}`)}async function nr({routeHandler:r,themeHandler:e,i18nHandler:t,assetHandler:n,seoHandler:s,pwaHandler:o,blogContentHandler:a},i,{appFonts:l}={}){let c=r?.pathResolver;if(!c)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let u=c.getAppRoot(),p=c.getRepoRoot();if(!u||u===p){i.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(y=>setTimeout(y,0));let m=c.getAppRoot();if(!m||m===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Ct(u)){i.debug("Discoveries already completed this build, skipping");return}Qo(u);let d=Date.now();c.startWriteRecording();let f;try{let m=await t.getDiscoveryData(),y={languages:m.supportedLanguages,defaultLanguage:m.fallbackLanguage};s.useLanguages(y),s.useTranslations(m.content);let{fontCss:S}=e?await e.getDiscoveryData():{},_=await Gn({fontCss:S,appFonts:l,languages:m.supportedLanguages,pathResolver:c});zn(_,{pathResolver:c}),i.debug(`Font plan: ${_.families.map(({family:v})=>v).join(", ")||"system fonts only"} (${_.files.length} files)`);for(let v of _.notices)i.info(`\u{1F524} ${v}`);if(r)try{r.useLanguages(y),r.useI18n(m),r.useFonts(_),i.info("\u{1F50D} Starting route discovery...");let v=await r.generateFiles();s.useRoutes(v);let E=v?.routes?.length||0;i.info(`\u2705 Routes generated: ${E} routes found`),E===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");n.useFlagCodes(m.flagCodes,r?r.getEntityResolver():ke(u));let P=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:n},{name:"SEO",handler:s},{name:"PWA",handler:o},{name:"BlogContent",handler:a}];for(let{name:v,handler:E}of P)try{await E.generateFiles()}catch(A){if(ce(A))throw A;i.debug(`${v} generation failed: ${A.message}`)}try{ta(c,i)}catch(v){i.debug(`Env config generation failed (non-critical): ${v.message}`)}}finally{f=c.stopWriteRecording()}ea(u,i,f);let h=Date.now()-d;i.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`)}function ta(r,e){let t={};for(let[a,i]of Object.entries(process.env))a.startsWith("NEXT_PUBLIC_")&&i!==void 0&&(t[a]=i);let n=`// Auto-generated DnDev env config by @donotdev/config
|
|
15
14
|
// Generated at: ${new Date().toISOString()}
|
|
16
15
|
// Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
|
|
17
16
|
|
|
@@ -28,34 +27,34 @@ if (typeof globalThis !== 'undefined') {
|
|
|
28
27
|
timestamp: Date.now(),
|
|
29
28
|
};
|
|
30
29
|
}
|
|
31
|
-
globalThis._DNDEV_CONFIG_.${
|
|
30
|
+
globalThis._DNDEV_CONFIG_.${X.env} = envConfig;
|
|
32
31
|
}
|
|
33
32
|
|
|
34
33
|
// Export for compatibility
|
|
35
34
|
export default envConfig;
|
|
36
|
-
`,s=r.resolveAppPath(L.next.configEnv);r.writeSync(s,n,{overwrite:!0});let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}var
|
|
37
|
-
`;a.writeSync(i,p)}let l=(
|
|
38
|
-
`;a.appendFile(i,m)}},
|
|
35
|
+
`,s=r.resolveAppPath(L.next.configEnv);r.writeSync(s,n,{overwrite:!0});let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}var rr={debug:!1,verbose:process.env.CI!=="true",seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1,aiCrawlers:"recommended",llmsTxt:!0,speculationRules:!0,hreflang:!0,breadcrumbSchema:!0,websiteSchema:!0,organizationSchema:!0},serverShim:{enabled:!0},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},features:{}};var De={...rr,generateManifest:!0,reactCompiler:!1,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function sr(r,e){let t={...r};return e&&Object.keys(e).forEach(n=>{e[n]&&typeof e[n]=="object"&&!Array.isArray(e[n])?t[n]=sr(r[n]||{},e[n]):t[n]=e[n]}),t}function or(r={}){return sr(De,r)}function ar(r){let{features:e={},routes:t={},themes:n={},i18n:s={},assets:o={},pwa:a={},seo:i={},serverShim:l,discovery:c={},generateManifest:u,debug:p,verbose:d,...f}=r,h=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:u,debug:p,verbose:d,mode:h,isDev:h==="development",routeOptions:t,themeOptions:n,i18nOptions:s,assetOptions:o,featureOptions:e,pwaOptions:a,seoOptions:i,discoveryOptions:c,nextConfigOptions:f}}import*as K from"@clack/prompts";var ne={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function na(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function oe(r,e){return na()?`${e}${r}${ne.reset}`:r}function ae(r,e,t,n={}){let{logDir:s=".dndev-logs",fileLogging:o=!1}=n,a=O.getInstance(),i=null;if(o){let u=a.resolveAppPath(s);a.pathExists(u)||a.mkdir(u),i=a.resolveAppPath(`${s}/${r.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${r} Log Started at ${new Date().toISOString()} ===
|
|
36
|
+
`;a.writeSync(i,p)}let l=(u,p,d)=>{if(i){let f=new Date().toISOString(),h=d.length>0?" "+d.map(y=>typeof y=="object"?JSON.stringify(y,null,2):String(y)).join(" "):"",m=`${f} [${u}] ${p}${h}
|
|
37
|
+
`;a.appendFile(i,m)}},c=(u,p)=>{if(p.length===0)return u;let d=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${u} ${d}`};return{debug:(u,...p)=>{e&&(o?l("DEBUG",u,p):K.log.message(oe(c(u,p),ne.gray)))},verbose:(u,...p)=>{t&&(o?l("VERBOSE",u,p):K.log.message(c(u,p)))},info:(u,...p)=>{o?l("INFO",u,p):K.log.info(oe(c(u,p),ne.brightCyan))},warn:(u,...p)=>{e&&o?l("WARN",u,p):K.log.warn(oe(c(u,p),ne.brightYellow))},error:(u,...p)=>{e&&o?l("ERROR",u,p):K.log.error(oe(c(u,p),ne.brightRed))},success:(u,...p)=>{e&&o?l("SUCCESS",u,p):K.log.success(oe(c(u,p),ne.brightGreen))},when:(u,p="debug")=>(d,...f)=>{if(u){let h=c(d,f);switch(p){case"verbose":t&&(K.log.message(h),l("VERBOSE",d,f));break;case"info":K.log.info(oe(h,ne.brightCyan)),l("INFO",d,f);break;case"warn":K.log.warn(oe(h,ne.brightYellow)),l("WARN",d,f);break;case"error":K.log.error(oe(h,ne.brightRed)),l("ERROR",d,f);break;case"success":K.log.success(oe(h,ne.brightGreen)),l("SUCCESS",d,f);break;default:e&&(K.log.message(oe(h,ne.gray)),l("DEBUG",d,f))}}},getLogFilePath:()=>i}}var ir=Object.freeze([{dependency:"@donotdev/supabase",module:"@donotdev/supabase/server",env:["SUPABASE_URL","SUPABASE_PUBLIC_KEY"],create:(r,[e,t])=>new r.SupabasePublicReader(r.createPublicServerClient(e,t))},{dependency:"@donotdev/firebase",module:"@donotdev/firebase/public",env:["FIREBASE_API_KEY","FIREBASE_PROJECT_ID"],create:(r,[e,t])=>new r.FirestorePublicReader(r.createPublicServerFirestore({apiKey:e,projectId:t}))}]);function lr(r){return ir.find(({dependency:e})=>r(e))}var cr=ir.map(({dependency:r})=>r).join(", ");var At=Object.freeze({pageGenerateMetadata:!0}),ra=Object.freeze({"@donotdev/supabase":{exports:"createPublicServerClient, SupabasePublicReader",comment:"RLS returns what a signed-out visitor can read.",construct:`new SupabasePublicReader(
|
|
39
38
|
createPublicServerClient(SUPABASE_URL, SUPABASE_PUBLIC_KEY)
|
|
40
39
|
)`},"@donotdev/firebase":{exports:"createPublicServerFirestore, FirestorePublicReader",comment:"Security Rules return what a signed-out visitor can read.",construct:`new FirestorePublicReader(
|
|
41
40
|
createPublicServerFirestore({ apiKey: FIREBASE_API_KEY, projectId: FIREBASE_PROJECT_ID })
|
|
42
|
-
)`}}),H=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=ae(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=
|
|
41
|
+
)`}}),H=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=ae(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=O.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`}appDependsOn(e){let t=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"),{format:"json"});return!!(t?.dependencies?.[e]||t?.devDependencies?.[e])}serverCrudReader(e,t="the sitemap and llms.txt list published records",n="Mark these pages `seo: { noindex: true }`."){let s=e.filter(d=>d.collection);if(s.length===0)return{imports:"",setup:"",expr:null,schemas:null,named:{}};let o=s.map(d=>d.path).join(", "),a=lr(d=>this.appDependsOn(d));if(!a)throw new Error(`[dndev] ${o} list published records, but the app's backend provider has no server reader (supported: ${cr}). ${n}`);if(!this.appDependsOn("entities")){let d=[...new Set(s.map(f=>f.collection))];throw x("dndev-routes",`${o} ${s.length===1?"lists":"list"} published ${d.map(f=>`"${f}"`).join(", ")} records, read with their entity definition's read schema, but the app does not depend on an \`entities\` package. Add the app's \`entities\` package (exporting the defineEntity definition) to its dependencies. `+n,"missing-entities-package",{routes:s.map(f=>f.path),collections:d})}let{exports:i,comment:l,construct:c}=ra[a.dependency],u=a.env,p=s.map(({path:d,collection:f})=>({path:d,collection:f}));return{imports:`import { ${i} } from '${a.module}';
|
|
43
42
|
import * as entities from 'entities';
|
|
44
43
|
`,setup:`
|
|
45
44
|
// Public (anonymous) reader: ${l}
|
|
46
|
-
${
|
|
45
|
+
${u.map(d=>`const ${d} = process.env.NEXT_PUBLIC_${d};`).join(`
|
|
47
46
|
`)}
|
|
48
|
-
if (${
|
|
47
|
+
if (${u.map(d=>`!${d}`).join(" || ")}) {
|
|
49
48
|
throw new Error(
|
|
50
|
-
'[dndev] Set ${
|
|
49
|
+
'[dndev] Set ${u.map(d=>`NEXT_PUBLIC_${d}`).join(" and ")}: ${t}.'
|
|
51
50
|
);
|
|
52
51
|
}
|
|
53
|
-
const CRUD = ${
|
|
52
|
+
const CRUD = ${c};
|
|
54
53
|
|
|
55
54
|
// Records are read with their entity's read schema: keyed by the entity's field names
|
|
56
55
|
// (RLS / Security Rules decide what a signed-out visitor reads)
|
|
57
56
|
const READ_SCHEMAS = entityReadSchemas(entities, ${JSON.stringify(p)}, createSchemas);
|
|
58
|
-
`,expr:"CRUD",schemas:"READ_SCHEMAS",named:{"@donotdev/core/server":["createSchemas"],"@donotdev/core/next":["entityReadSchemas"]}}}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...De.discovery,...this.options,...
|
|
57
|
+
`,expr:"CRUD",schemas:"READ_SCHEMAS",named:{"@donotdev/core/server":["createSchemas"],"@donotdev/core/next":["entityReadSchemas"]}}}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...De.discovery,...this.options,...At};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}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(),n=L.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!n)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 s=this.generateConfigContent(e);this.writeGeneratedFile(n,s,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),n=X[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
59
58
|
// Generated at: ${new Date().toISOString()}
|
|
60
59
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
61
60
|
|
|
@@ -77,7 +76,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
77
76
|
|
|
78
77
|
// Export for compatibility
|
|
79
78
|
export default ${t}Config;
|
|
80
|
-
`}writeGeneratedFile(e,t,n="file"){let s=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(s,t,{overwrite:!0}),this.logger.debug(`Generated ${n}: ${s}`),s}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}`)}}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")}getAPIRewrites(){throw new Error("getAPIRewrites() 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 ee=class r{constructor(e,t={}){if(this.constructor===r)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=ae(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let n=await this._getPatterns();this.options.verbose&&n&&(typeof n=="object"&&n.pattern?this.logger.verbose(`Pattern: ${n.pattern}`):typeof n=="string"&&this.logger.verbose(`Pattern: ${n}`),n.dirs&&this.logger.verbose(`Search directories: ${n.dirs.slice(0,3).join(", ")}${n.dirs.length>3?` (${n.dirs.length} total)`:""}`));let s=await this._prepareFiles(),o=await this._scanFiles(n),a=await this._processFiles(o,s);this.cache={...a,timestamp:Date.now()};let i=Date.now()-t;return this.logger.debug(`Discovery completed in ${i}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){if(ce(n))throw n;return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${n.message}`),this.logger.error(`Stack: ${n.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _prepareFiles(){return{}}async _processFiles(e,t){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),n=t[t.length-1],s=n.split(".")[0],o=n.split(".").pop();return{fileName:n,baseName:s,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let n=this.pathResolver.getFileInfo(e);return n?await t(n):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(n){if(ce(n))throw n;return this.logger.debug(`Error processing file ${e}: ${n.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(s=>this._processSingleFile(s,t)))).filter(s=>s!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var tc={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},cr=[{id:"en",name:"English",nativeName:"English",flagCode:"gb"},{id:"us",name:"English (US)",nativeName:"English (US)",countryCode:"US",dialCode:"+1"},{id:"gb",name:"English (UK)",nativeName:"English (UK)",countryCode:"GB",dialCode:"+44"},{id:"en-ca",name:"English (Canada)",nativeName:"English (Canada)",flagCode:"ca",countryCode:"CA",dialCode:"+1"},{id:"au",name:"English (Australia)",nativeName:"English (Australia)",countryCode:"AU",dialCode:"+61"},{id:"ie",name:"English (Ireland)",nativeName:"English (Ireland)",countryCode:"IE",dialCode:"+353"},{id:"es",name:"Spanish",nativeName:"Espa\xF1ol",countryCode:"ES",dialCode:"+34"},{id:"mx",name:"Spanish (Mexico)",nativeName:"Espa\xF1ol (M\xE9xico)",countryCode:"MX",dialCode:"+52"},{id:"es-ar",name:"Spanish (Argentina)",nativeName:"Espa\xF1ol (Argentina)",flagCode:"ar",countryCode:"AR",dialCode:"+54"},{id:"fr",name:"French",nativeName:"Fran\xE7ais",flagCode:"fr",countryCode:"FR",dialCode:"+33"},{id:"fr-be",name:"French (Belgium)",nativeName:"Fran\xE7ais (Belgique)",flagCode:"be",countryCode:"BE",dialCode:"+32"},{id:"ch",name:"French (Switzerland)",nativeName:"Fran\xE7ais (Suisse)",countryCode:"CH",dialCode:"+41"},{id:"de",name:"German",nativeName:"Deutsch",countryCode:"DE",dialCode:"+49"},{id:"at",name:"German (Austria)",nativeName:"Deutsch (\xD6sterreich)",countryCode:"AT",dialCode:"+43"},{id:"it",name:"Italian",nativeName:"Italiano",countryCode:"IT",dialCode:"+39"},{id:"pt",name:"Portuguese",nativeName:"Portugu\xEAs",countryCode:"PT",dialCode:"+351"},{id:"br",name:"Portuguese (Brazil)",nativeName:"Portugu\xEAs (Brasil)",flagCode:"br",countryCode:"BR",dialCode:"+55"},{id:"ru",name:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",countryCode:"RU",dialCode:"+7"},{id:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",countryCode:"JP",dialCode:"+81"},{id:"ko",name:"Korean",nativeName:"\uD55C\uAD6D\uC5B4",countryCode:"KR",dialCode:"+82"},{id:"zh",name:"Chinese",nativeName:"\u4E2D\u6587",countryCode:"CN",dialCode:"+86"},{id:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flagCode:"sa",countryCode:"SA",dialCode:"+966"},{id:"ar-ma",name:"Arabic (Morocco)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0645\u063A\u0631\u0628)",flagCode:"ma",countryCode:"MA",dialCode:"+212"},{id:"ar-dz",name:"Arabic (Algeria)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u062C\u0632\u0627\u0626\u0631)",flagCode:"dz",countryCode:"DZ",dialCode:"+213"},{id:"ar-tn",name:"Arabic (Tunisia)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u062A\u0648\u0646\u0633)",flagCode:"tn",countryCode:"TN",dialCode:"+216"},{id:"ar-ly",name:"Arabic (Libya)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0644\u064A\u0628\u064A\u0627)",flagCode:"ly",countryCode:"LY",dialCode:"+218"},{id:"ar-mr",name:"Arabic (Mauritania)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627)",flagCode:"mr",countryCode:"MR",dialCode:"+222"},{id:"hi",name:"Hindi",nativeName:"\u0939\u093F\u0928\u094D\u0926\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"nl",name:"Dutch",nativeName:"Nederlands",countryCode:"NL",dialCode:"+31"},{id:"sv",name:"Swedish",nativeName:"Svenska",countryCode:"SE",dialCode:"+46"},{id:"da",name:"Danish",nativeName:"Dansk",countryCode:"DK",dialCode:"+45"},{id:"no",name:"Norwegian",nativeName:"Norsk",countryCode:"NO",dialCode:"+47"},{id:"fi",name:"Finnish",nativeName:"Suomi",countryCode:"FI",dialCode:"+358"},{id:"pl",name:"Polish",nativeName:"Polski",countryCode:"PL",dialCode:"+48"},{id:"tr",name:"Turkish",nativeName:"T\xFCrk\xE7e",countryCode:"TR",dialCode:"+90"},{id:"th",name:"Thai",nativeName:"\u0E44\u0E17\u0E22",countryCode:"TH",dialCode:"+66"},{id:"vi",name:"Vietnamese",nativeName:"Ti\u1EBFng Vi\u1EC7t",countryCode:"VN",dialCode:"+84"},{id:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",countryCode:"ID",dialCode:"+62"},{id:"ms",name:"Malay",nativeName:"Bahasa Melayu",flagCode:"my",countryCode:"MY",dialCode:"+60"},{id:"tl",name:"Filipino",nativeName:"Tagalog",countryCode:"PH",dialCode:"+63"},{id:"bg",name:"Bulgarian",nativeName:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",countryCode:"BG",dialCode:"+359"},{id:"cs",name:"Czech",nativeName:"\u010Ce\u0161tina",countryCode:"CZ",dialCode:"+420"},{id:"el",name:"Greek",nativeName:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",countryCode:"GR",dialCode:"+30"},{id:"he",name:"Hebrew",nativeName:"\u05E2\u05D1\u05E8\u05D9\u05EA",countryCode:"IL",dialCode:"+972"},{id:"hu",name:"Hungarian",nativeName:"Magyar",countryCode:"HU",dialCode:"+36"},{id:"is",name:"Icelandic",nativeName:"\xCDslenska",countryCode:"IS",dialCode:"+354"},{id:"lt",name:"Lithuanian",nativeName:"Lietuvi\u0173",countryCode:"LT",dialCode:"+370"},{id:"lv",name:"Latvian",nativeName:"Latvie\u0161u",countryCode:"LV",dialCode:"+371"},{id:"mt",name:"Maltese",nativeName:"Malti",countryCode:"MT",dialCode:"+356"},{id:"ro",name:"Romanian",nativeName:"Rom\xE2n\u0103",countryCode:"RO",dialCode:"+40"},{id:"sk",name:"Slovak",nativeName:"Sloven\u010Dina",countryCode:"SK",dialCode:"+421"},{id:"sl",name:"Slovenian",nativeName:"Sloven\u0161\u010Dina",flagCode:"si",countryCode:"SI",dialCode:"+386"},{id:"uk",name:"Ukrainian",nativeName:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flagCode:"ua",countryCode:"UA",dialCode:"+380"},{id:"et",name:"Estonian",nativeName:"Eesti",countryCode:"EE",dialCode:"+372"},{id:"ca",name:"Catalan",nativeName:"Catal\xE0",countryCode:"ES",dialCode:"+34"},{id:"eu",name:"Basque",nativeName:"Euskara",countryCode:"ES",dialCode:"+34"},{id:"gl",name:"Galician",nativeName:"Galego",countryCode:"ES",dialCode:"+34"},{id:"cy",name:"Welsh",nativeName:"Cymraeg",countryCode:"GB",dialCode:"+44"},{id:"ga",name:"Irish",nativeName:"Gaeilge",flagCode:"ie",countryCode:"IE",dialCode:"+353"},{id:"gd",name:"Scottish Gaelic",nativeName:"G\xE0idhlig",flagCode:"gb-sct",countryCode:"GB",dialCode:"+44"},{id:"br-fr",name:"Breton",nativeName:"Brezhoneg",flagCode:"bzh",countryCode:"FR",dialCode:"+33"},{id:"co",name:"Corsican",nativeName:"Corsu",flagCode:"fr-cor",countryCode:"FR",dialCode:"+33"},{id:"oc",name:"Occitan",nativeName:"Occitan",countryCode:"FR",dialCode:"+33"},{id:"rm",name:"Romansh",nativeName:"Rumantsch",countryCode:"CH",dialCode:"+41"},{id:"lb",name:"Luxembourgish",nativeName:"L\xEBtzebuergesch",countryCode:"LU",dialCode:"+352"},{id:"af",name:"Afrikaans",nativeName:"Afrikaans",countryCode:"ZA",dialCode:"+27"},{id:"sw",name:"Swahili",nativeName:"Kiswahili",countryCode:"KE",dialCode:"+254"},{id:"am",name:"Amharic",nativeName:"\u12A0\u121B\u122D\u129B",flagCode:"et",countryCode:"ET",dialCode:"+251"},{id:"bn",name:"Bengali",nativeName:"\u09AC\u09BE\u0982\u09B2\u09BE",flagCode:"bd",countryCode:"BD",dialCode:"+880"},{id:"gu",name:"Gujarati",nativeName:"\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"kn",name:"Kannada",nativeName:"\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ml",name:"Malayalam",nativeName:"\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"mr",name:"Marathi",nativeName:"\u092E\u0930\u093E\u0920\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ne",name:"Nepali",nativeName:"\u0928\u0947\u092A\u093E\u0932\u0940",flagCode:"np",countryCode:"NP",dialCode:"+977"},{id:"pa",name:"Punjabi",nativeName:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"si",name:"Sinhala",nativeName:"\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",countryCode:"LK",dialCode:"+94"},{id:"ta",name:"Tamil",nativeName:"\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"te",name:"Telugu",nativeName:"\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ur",name:"Urdu",nativeName:"\u0627\u0631\u062F\u0648",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"fa",name:"Persian",nativeName:"\u0641\u0627\u0631\u0633\u06CC",flagCode:"ir",countryCode:"IR",dialCode:"+98"},{id:"ps",name:"Pashto",nativeName:"\u067E\u069A\u062A\u0648",countryCode:"AF",dialCode:"+93"},{id:"uz",name:"Uzbek",nativeName:"O\u02BBzbek",countryCode:"UZ",dialCode:"+998"},{id:"kk",name:"Kazakh",nativeName:"\u049A\u0430\u0437\u0430\u049B",flagCode:"kz",countryCode:"KZ",dialCode:"+7"},{id:"ky",name:"Kyrgyz",nativeName:"\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430",flagCode:"kg",countryCode:"KG",dialCode:"+996"},{id:"tg",name:"Tajik",nativeName:"\u0422\u043E\u04B7\u0438\u043A\u04E3",flagCode:"tj",countryCode:"TJ",dialCode:"+992"},{id:"mn",name:"Mongolian",nativeName:"\u041C\u043E\u043D\u0433\u043E\u043B",countryCode:"MN",dialCode:"+976"},{id:"my",name:"Burmese",nativeName:"\u1019\u103C\u1014\u103A\u1019\u102C",flagCode:"mm",countryCode:"MM",dialCode:"+95"},{id:"km",name:"Khmer",nativeName:"\u1781\u17D2\u1798\u17C2\u179A",flagCode:"kh",countryCode:"KH",dialCode:"+855"},{id:"lo",name:"Lao",nativeName:"\u0EA5\u0EB2\u0EA7",flagCode:"la",countryCode:"LA",dialCode:"+856"},{id:"ka",name:"Georgian",nativeName:"\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",flagCode:"ge",countryCode:"GE",dialCode:"+995"},{id:"hy",name:"Armenian",nativeName:"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",flagCode:"am",countryCode:"AM",dialCode:"+374"},{id:"az",name:"Azerbaijani",nativeName:"Az\u0259rbaycan",countryCode:"AZ",dialCode:"+994"},{id:"be",name:"Belarusian",nativeName:"\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",flagCode:"by",countryCode:"BY",dialCode:"+375"},{id:"mk",name:"Macedonian",nativeName:"\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",countryCode:"MK",dialCode:"+389"},{id:"sr",name:"Serbian",nativeName:"\u0421\u0440\u043F\u0441\u043A\u0438",countryCode:"RS",dialCode:"+381"},{id:"bs",name:"Bosnian",nativeName:"Bosanski",flagCode:"ba",countryCode:"BA",dialCode:"+387"},{id:"hr",name:"Croatian",nativeName:"Hrvatski",countryCode:"HR",dialCode:"+385"},{id:"sq",name:"Albanian",nativeName:"Shqip",flagCode:"al",countryCode:"AL",dialCode:"+355"},{id:"md",name:"Moldovan",nativeName:"Moldoveneasc\u0103",countryCode:"MD",dialCode:"+373"}],aa={US:"United States",GB:"United Kingdom",CA:"Canada",AU:"Australia",IE:"Ireland",FR:"France",BE:"Belgium",CH:"Switzerland",DE:"Germany",AT:"Austria",IT:"Italy",PT:"Portugal",BR:"Brazil",ES:"Spain",MX:"Mexico",AR:"Argentina",RU:"Russia",JP:"Japan",KR:"South Korea",CN:"China",SE:"Sweden",NO:"Norway",DK:"Denmark",FI:"Finland",NL:"Netherlands",PL:"Poland",CZ:"Czech Republic",HU:"Hungary",RO:"Romania",BG:"Bulgaria",GR:"Greece",TR:"Turkey",IL:"Israel",IN:"India",ZA:"South Africa"};function ia(){return cr.filter(r=>r.countryCode!==void 0&&r.dialCode!==void 0).map(r=>({code:r.countryCode,dialCode:r.dialCode,flagCode:r.flagCode||r.id,name:r.countryName||aa[r.countryCode]||r.name}))}var la=ia(),At="/flags";function ur(r){return`${r.toLowerCase()}.svg`}function Nt(r){return cr.find(t=>t.id===r)?.flagCode||r}function pr(){return[...new Set(la.map(r=>r.flagCode))]}var be={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},ca="public/logo.svg is missing: it is the site logo (Organization / publisher logo in the JSON-LD, the default logo) and the source of the favicon, PWA icons and og-image.png. Add public/logo.svg.",dr="/manifest.json",qe=class extends ee{constructor(e,t={}){super(e,{assets:X.assets.fallback,assetPatterns:X.assets.patterns,frameworkPackage:lt.package,assetsPath:lt.assetsPath,modernFormats:X.assets.modern,...t}),this.hasRunForSession=!1,this.flagCodes=null,this.entityResolver=null}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _prepareFiles(){let e=this.pathResolver.getAppRoot(),t=await this._ensureDefaultAssets(e);if(this.flagCodes){let i=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(i?[...new Set([...this.flagCodes,...pr()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${At}/: ${l.join(", ")}`)}let n=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(n)||this.logger.warn(ca);let o=[],a=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(o=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:o}}async _processFiles(e,{copiedAssets:t,generatedAssets:n}){let s=this.pathResolver.getAppRoot(),{consumerFiles:o}=e,a=await this._processAssetFiles(o),i=this._buildAssetManifest(a,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${dr}`))}),l=await this._readLogoSvgContent("/logo.svg",s);return{assets:a,manifest:{...i,logoSvgContent:l},copiedAssets:t,generatedAssets:n}}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}useFlagCodes(e,t){this.flagCodes=e,this.entityResolver=t}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let n=this.getAssets().map(o=>o.path),s=t||this.options.modernFormats;for(let o of s){let a=`/${e}.${o}`;if(n.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let n=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${n}`),!n)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let s=this.pathResolver.resolveAppPath(le.public);this.pathResolver.pathExists(s)||(this.pathResolver.mkdir(s),this.logger.debug(`Created public directory: ${s}`));for(let o of this.options.assets)await this._ensureAsset(o,s,n)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(n){this.logger.debug(`Failed to ensure default assets: ${n.message}`)}return t}async _ensureAsset(e,t,n){let s=this.pathResolver.resolveAppPath(`${le.public}/${e}`);if(this.pathResolver.pathExists(s))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${n}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,s))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}_ensureFlags(e){let t=this.pathResolver.resolveFrameworkPackage("@donotdev/core");if(!t)throw new Error("Flag copy: @donotdev/core not found");let n=this.pathResolver.normalizePath(`${t}/${we.PUBLISHED_FLAGS}`),s=`${le.public}${At}`,o=[];for(let a of e){let i=ur(a),l=this.pathResolver.resolveAppPath(`${s}/${i}`);if(this.pathResolver.pathExists(l))continue;let u=`${n}/${i}`;if(!this.pathResolver.pathExists(u)){this.logger.warn(`No flag artwork for "${a}": add ${s}/${i} to the app`);continue}if(!this.pathResolver.copySync(u,l))throw new Error(`Flag copy: cannot copy ${u} to ${l}`);o.push(i)}return o}async _processAssetFiles(e){let t=[];for(let n of e)try{let s=this.pathResolver.getFileInfo(n);if(s&&s.isFile){let o=n.split("/").pop()||n.split("\\").pop(),a=this._analyzeAsset(o,s.size);a&&t.push(a)}}catch(s){this.logger.debug(`Error processing asset file ${n}: ${s.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let n=this._determineAssetType(e),s=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:n,format:s,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(s)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let n=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(n)?"image":["woff2","woff","ttf","otf"].includes(n)?"font":["json"].includes(n)?"json":["ico"].includes(n)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,n=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+n[s]}_matchesPattern(e,t){let n=t.split("*").map(s=>s.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let n=e.map(o=>o.path);return{logo:{optimal:this._getOptimalAsset("logo",n,this.options.modernFormats),fallback:this._getOptimalAsset("logo",n,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",n,["svg","ico"]),fallback:this._getOptimalAsset("favicon",n,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",n,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",n,["png"]),512:this._getOptimalAsset("android-chrome-512x512",n,["png"])},manifest:t?dr:null,modernFormats:e.filter(o=>o.isModern).map(o=>o.path),fallbackFormats:e.filter(o=>!o.isModern).map(o=>o.path)}}_getOptimalAsset(e,t,n){for(let s of n){let o=`/${e}.${s}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),n=await this._resolvePackage("@donotdev/ui",t);if(!n)return this.logger.debug("@donotdev/ui package not found"),null;let s=this.pathResolver.normalizePath(`${n}/assets`);return this.pathResolver.pathExists(s)?(this.logger.debug(`Using framework assets from: ${s}`),s):(this.logger.debug(`Assets directory not found: ${s}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let n=this.pathResolver.resolveFrameworkPackage(e,t);return n?(this.logger.debug(`Found package: ${n}`),n):(this.logger.debug(`Package ${e} not found`),null)}catch(n){return this.logger.debug(`Error resolving package ${e}: ${n.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let n=e.slice(1),s=this.pathResolver.resolveAppPath(`${le.public}/${n}`);return this.pathResolver.pathExists(s)&&await this.pathResolver.read(s,{format:"text"})||null}catch(n){return this.logger.debug(`Failed to read logo SVG content: ${n.message}`),null}}async _renderOgImage(e,t){let{width:n,height:s}=await e(t).metadata(),o=Math.min(be.logoWidth/n,be.logoHeight/s),a=await e(t,{density:Math.ceil(72*o)}).resize(be.logoWidth,be.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:be.width,height:be.height,channels:4,background:be.background}}).composite([{input:a}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),n=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let s=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...s].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let p=`${n}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{await this.pathResolver.write(p,l),a.push(c.name)}catch(d){this.logger.debug(`Failed to copy ${c.name}: ${d.message}`),i.push(c.name)}}let u=await import("sharp").catch(()=>null);if(!u)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...s.map(c=>c.name));else{for(let p of s){let d=`${n}/${p.name}`;if(this.pathResolver.pathExists(d)){i.push(p.name);continue}try{let f=u.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;p.format==="ico"?h=await f.toFormat("png").toBuffer():h=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(d,h),a.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),i.push(p.name)}}let c=Ne.slice(1);if(this.pathResolver.pathExists(`${n}/${c}`))i.push(c);else try{let p=await this._renderOgImage(u.default,t);await this.pathResolver.write(`${n}/${c}`,p),a.push(c)}catch(p){this.logger.debug(`Failed to generate ${c}: ${p.message}`),i.push(c)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:[...o,...s].map(u=>u.name),error:l.message}}}};var _t=class extends H{constructor(e={}){super(qe,e)}getHandlerDefaults(){return{manifestPath:L.next.assetManifest,generateManifest:!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
|
|
79
|
+
`}writeGeneratedFile(e,t,n="file"){let s=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(s,t,{overwrite:!0}),this.logger.debug(`Generated ${n}: ${s}`),s}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}`)}}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")}getAPIRewrites(){throw new Error("getAPIRewrites() 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")}};import{createHash as ia}from"node:crypto";var ee=class r{constructor(e,t={}){if(this.constructor===r)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=ae(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let n=await this._getPatterns();this.options.verbose&&n&&(typeof n=="object"&&n.pattern?this.logger.verbose(`Pattern: ${n.pattern}`):typeof n=="string"&&this.logger.verbose(`Pattern: ${n}`),n.dirs&&this.logger.verbose(`Search directories: ${n.dirs.slice(0,3).join(", ")}${n.dirs.length>3?` (${n.dirs.length} total)`:""}`));let s=await this._prepareFiles(),o=await this._scanFiles(n),a=await this._processFiles(o,s);this.cache={...a,timestamp:Date.now()};let i=Date.now()-t;return this.logger.debug(`Discovery completed in ${i}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){if(ce(n))throw n;return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${n.message}`),this.logger.error(`Stack: ${n.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _prepareFiles(){return{}}async _processFiles(e,t){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),n=t[t.length-1],s=n.split(".")[0],o=n.split(".").pop();return{fileName:n,baseName:s,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let n=this.pathResolver.getFileInfo(e);return n?await t(n):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(n){if(ce(n))throw n;return this.logger.debug(`Error processing file ${e}: ${n.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(s=>this._processSingleFile(s,t)))).filter(s=>s!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var nc={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},ur=[{id:"en",name:"English",nativeName:"English",flagCode:"gb"},{id:"us",name:"English (US)",nativeName:"English (US)",countryCode:"US",dialCode:"+1"},{id:"gb",name:"English (UK)",nativeName:"English (UK)",countryCode:"GB",dialCode:"+44"},{id:"en-ca",name:"English (Canada)",nativeName:"English (Canada)",flagCode:"ca",countryCode:"CA",dialCode:"+1"},{id:"au",name:"English (Australia)",nativeName:"English (Australia)",countryCode:"AU",dialCode:"+61"},{id:"ie",name:"English (Ireland)",nativeName:"English (Ireland)",countryCode:"IE",dialCode:"+353"},{id:"es",name:"Spanish",nativeName:"Espa\xF1ol",countryCode:"ES",dialCode:"+34"},{id:"mx",name:"Spanish (Mexico)",nativeName:"Espa\xF1ol (M\xE9xico)",countryCode:"MX",dialCode:"+52"},{id:"es-ar",name:"Spanish (Argentina)",nativeName:"Espa\xF1ol (Argentina)",flagCode:"ar",countryCode:"AR",dialCode:"+54"},{id:"fr",name:"French",nativeName:"Fran\xE7ais",flagCode:"fr",countryCode:"FR",dialCode:"+33"},{id:"fr-be",name:"French (Belgium)",nativeName:"Fran\xE7ais (Belgique)",flagCode:"be",countryCode:"BE",dialCode:"+32"},{id:"ch",name:"French (Switzerland)",nativeName:"Fran\xE7ais (Suisse)",countryCode:"CH",dialCode:"+41"},{id:"de",name:"German",nativeName:"Deutsch",countryCode:"DE",dialCode:"+49"},{id:"at",name:"German (Austria)",nativeName:"Deutsch (\xD6sterreich)",countryCode:"AT",dialCode:"+43"},{id:"it",name:"Italian",nativeName:"Italiano",countryCode:"IT",dialCode:"+39"},{id:"pt",name:"Portuguese",nativeName:"Portugu\xEAs",countryCode:"PT",dialCode:"+351"},{id:"br",name:"Portuguese (Brazil)",nativeName:"Portugu\xEAs (Brasil)",flagCode:"br",countryCode:"BR",dialCode:"+55"},{id:"ru",name:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",countryCode:"RU",dialCode:"+7"},{id:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",countryCode:"JP",dialCode:"+81"},{id:"ko",name:"Korean",nativeName:"\uD55C\uAD6D\uC5B4",countryCode:"KR",dialCode:"+82"},{id:"zh",name:"Chinese",nativeName:"\u4E2D\u6587",countryCode:"CN",dialCode:"+86"},{id:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flagCode:"sa",countryCode:"SA",dialCode:"+966"},{id:"ar-ma",name:"Arabic (Morocco)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0645\u063A\u0631\u0628)",flagCode:"ma",countryCode:"MA",dialCode:"+212"},{id:"ar-dz",name:"Arabic (Algeria)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u062C\u0632\u0627\u0626\u0631)",flagCode:"dz",countryCode:"DZ",dialCode:"+213"},{id:"ar-tn",name:"Arabic (Tunisia)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u062A\u0648\u0646\u0633)",flagCode:"tn",countryCode:"TN",dialCode:"+216"},{id:"ar-ly",name:"Arabic (Libya)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0644\u064A\u0628\u064A\u0627)",flagCode:"ly",countryCode:"LY",dialCode:"+218"},{id:"ar-mr",name:"Arabic (Mauritania)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627)",flagCode:"mr",countryCode:"MR",dialCode:"+222"},{id:"hi",name:"Hindi",nativeName:"\u0939\u093F\u0928\u094D\u0926\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"nl",name:"Dutch",nativeName:"Nederlands",countryCode:"NL",dialCode:"+31"},{id:"sv",name:"Swedish",nativeName:"Svenska",countryCode:"SE",dialCode:"+46"},{id:"da",name:"Danish",nativeName:"Dansk",countryCode:"DK",dialCode:"+45"},{id:"no",name:"Norwegian",nativeName:"Norsk",countryCode:"NO",dialCode:"+47"},{id:"fi",name:"Finnish",nativeName:"Suomi",countryCode:"FI",dialCode:"+358"},{id:"pl",name:"Polish",nativeName:"Polski",countryCode:"PL",dialCode:"+48"},{id:"tr",name:"Turkish",nativeName:"T\xFCrk\xE7e",countryCode:"TR",dialCode:"+90"},{id:"th",name:"Thai",nativeName:"\u0E44\u0E17\u0E22",countryCode:"TH",dialCode:"+66"},{id:"vi",name:"Vietnamese",nativeName:"Ti\u1EBFng Vi\u1EC7t",countryCode:"VN",dialCode:"+84"},{id:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",countryCode:"ID",dialCode:"+62"},{id:"ms",name:"Malay",nativeName:"Bahasa Melayu",flagCode:"my",countryCode:"MY",dialCode:"+60"},{id:"tl",name:"Filipino",nativeName:"Tagalog",countryCode:"PH",dialCode:"+63"},{id:"bg",name:"Bulgarian",nativeName:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",countryCode:"BG",dialCode:"+359"},{id:"cs",name:"Czech",nativeName:"\u010Ce\u0161tina",countryCode:"CZ",dialCode:"+420"},{id:"el",name:"Greek",nativeName:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",countryCode:"GR",dialCode:"+30"},{id:"he",name:"Hebrew",nativeName:"\u05E2\u05D1\u05E8\u05D9\u05EA",countryCode:"IL",dialCode:"+972"},{id:"hu",name:"Hungarian",nativeName:"Magyar",countryCode:"HU",dialCode:"+36"},{id:"is",name:"Icelandic",nativeName:"\xCDslenska",countryCode:"IS",dialCode:"+354"},{id:"lt",name:"Lithuanian",nativeName:"Lietuvi\u0173",countryCode:"LT",dialCode:"+370"},{id:"lv",name:"Latvian",nativeName:"Latvie\u0161u",countryCode:"LV",dialCode:"+371"},{id:"mt",name:"Maltese",nativeName:"Malti",countryCode:"MT",dialCode:"+356"},{id:"ro",name:"Romanian",nativeName:"Rom\xE2n\u0103",countryCode:"RO",dialCode:"+40"},{id:"sk",name:"Slovak",nativeName:"Sloven\u010Dina",countryCode:"SK",dialCode:"+421"},{id:"sl",name:"Slovenian",nativeName:"Sloven\u0161\u010Dina",flagCode:"si",countryCode:"SI",dialCode:"+386"},{id:"uk",name:"Ukrainian",nativeName:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flagCode:"ua",countryCode:"UA",dialCode:"+380"},{id:"et",name:"Estonian",nativeName:"Eesti",countryCode:"EE",dialCode:"+372"},{id:"ca",name:"Catalan",nativeName:"Catal\xE0",countryCode:"ES",dialCode:"+34"},{id:"eu",name:"Basque",nativeName:"Euskara",countryCode:"ES",dialCode:"+34"},{id:"gl",name:"Galician",nativeName:"Galego",countryCode:"ES",dialCode:"+34"},{id:"cy",name:"Welsh",nativeName:"Cymraeg",countryCode:"GB",dialCode:"+44"},{id:"ga",name:"Irish",nativeName:"Gaeilge",flagCode:"ie",countryCode:"IE",dialCode:"+353"},{id:"gd",name:"Scottish Gaelic",nativeName:"G\xE0idhlig",flagCode:"gb-sct",countryCode:"GB",dialCode:"+44"},{id:"br-fr",name:"Breton",nativeName:"Brezhoneg",flagCode:"bzh",countryCode:"FR",dialCode:"+33"},{id:"co",name:"Corsican",nativeName:"Corsu",flagCode:"fr-cor",countryCode:"FR",dialCode:"+33"},{id:"oc",name:"Occitan",nativeName:"Occitan",countryCode:"FR",dialCode:"+33"},{id:"rm",name:"Romansh",nativeName:"Rumantsch",countryCode:"CH",dialCode:"+41"},{id:"lb",name:"Luxembourgish",nativeName:"L\xEBtzebuergesch",countryCode:"LU",dialCode:"+352"},{id:"af",name:"Afrikaans",nativeName:"Afrikaans",countryCode:"ZA",dialCode:"+27"},{id:"sw",name:"Swahili",nativeName:"Kiswahili",countryCode:"KE",dialCode:"+254"},{id:"am",name:"Amharic",nativeName:"\u12A0\u121B\u122D\u129B",flagCode:"et",countryCode:"ET",dialCode:"+251"},{id:"bn",name:"Bengali",nativeName:"\u09AC\u09BE\u0982\u09B2\u09BE",flagCode:"bd",countryCode:"BD",dialCode:"+880"},{id:"gu",name:"Gujarati",nativeName:"\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"kn",name:"Kannada",nativeName:"\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ml",name:"Malayalam",nativeName:"\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"mr",name:"Marathi",nativeName:"\u092E\u0930\u093E\u0920\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ne",name:"Nepali",nativeName:"\u0928\u0947\u092A\u093E\u0932\u0940",flagCode:"np",countryCode:"NP",dialCode:"+977"},{id:"pa",name:"Punjabi",nativeName:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"si",name:"Sinhala",nativeName:"\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",countryCode:"LK",dialCode:"+94"},{id:"ta",name:"Tamil",nativeName:"\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"te",name:"Telugu",nativeName:"\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ur",name:"Urdu",nativeName:"\u0627\u0631\u062F\u0648",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"fa",name:"Persian",nativeName:"\u0641\u0627\u0631\u0633\u06CC",flagCode:"ir",countryCode:"IR",dialCode:"+98"},{id:"ps",name:"Pashto",nativeName:"\u067E\u069A\u062A\u0648",countryCode:"AF",dialCode:"+93"},{id:"uz",name:"Uzbek",nativeName:"O\u02BBzbek",countryCode:"UZ",dialCode:"+998"},{id:"kk",name:"Kazakh",nativeName:"\u049A\u0430\u0437\u0430\u049B",flagCode:"kz",countryCode:"KZ",dialCode:"+7"},{id:"ky",name:"Kyrgyz",nativeName:"\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430",flagCode:"kg",countryCode:"KG",dialCode:"+996"},{id:"tg",name:"Tajik",nativeName:"\u0422\u043E\u04B7\u0438\u043A\u04E3",flagCode:"tj",countryCode:"TJ",dialCode:"+992"},{id:"mn",name:"Mongolian",nativeName:"\u041C\u043E\u043D\u0433\u043E\u043B",countryCode:"MN",dialCode:"+976"},{id:"my",name:"Burmese",nativeName:"\u1019\u103C\u1014\u103A\u1019\u102C",flagCode:"mm",countryCode:"MM",dialCode:"+95"},{id:"km",name:"Khmer",nativeName:"\u1781\u17D2\u1798\u17C2\u179A",flagCode:"kh",countryCode:"KH",dialCode:"+855"},{id:"lo",name:"Lao",nativeName:"\u0EA5\u0EB2\u0EA7",flagCode:"la",countryCode:"LA",dialCode:"+856"},{id:"ka",name:"Georgian",nativeName:"\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",flagCode:"ge",countryCode:"GE",dialCode:"+995"},{id:"hy",name:"Armenian",nativeName:"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",flagCode:"am",countryCode:"AM",dialCode:"+374"},{id:"az",name:"Azerbaijani",nativeName:"Az\u0259rbaycan",countryCode:"AZ",dialCode:"+994"},{id:"be",name:"Belarusian",nativeName:"\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",flagCode:"by",countryCode:"BY",dialCode:"+375"},{id:"mk",name:"Macedonian",nativeName:"\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",countryCode:"MK",dialCode:"+389"},{id:"sr",name:"Serbian",nativeName:"\u0421\u0440\u043F\u0441\u043A\u0438",countryCode:"RS",dialCode:"+381"},{id:"bs",name:"Bosnian",nativeName:"Bosanski",flagCode:"ba",countryCode:"BA",dialCode:"+387"},{id:"hr",name:"Croatian",nativeName:"Hrvatski",countryCode:"HR",dialCode:"+385"},{id:"sq",name:"Albanian",nativeName:"Shqip",flagCode:"al",countryCode:"AL",dialCode:"+355"},{id:"md",name:"Moldovan",nativeName:"Moldoveneasc\u0103",countryCode:"MD",dialCode:"+373"}],sa={US:"United States",GB:"United Kingdom",CA:"Canada",AU:"Australia",IE:"Ireland",FR:"France",BE:"Belgium",CH:"Switzerland",DE:"Germany",AT:"Austria",IT:"Italy",PT:"Portugal",BR:"Brazil",ES:"Spain",MX:"Mexico",AR:"Argentina",RU:"Russia",JP:"Japan",KR:"South Korea",CN:"China",SE:"Sweden",NO:"Norway",DK:"Denmark",FI:"Finland",NL:"Netherlands",PL:"Poland",CZ:"Czech Republic",HU:"Hungary",RO:"Romania",BG:"Bulgaria",GR:"Greece",TR:"Turkey",IL:"Israel",IN:"India",ZA:"South Africa"};function oa(){return ur.filter(r=>r.countryCode!==void 0&&r.dialCode!==void 0).map(r=>({code:r.countryCode,dialCode:r.dialCode,flagCode:r.flagCode||r.id,name:r.countryName||sa[r.countryCode]||r.name}))}var aa=oa(),Nt="/flags";function pr(r){return`${r.toLowerCase()}.svg`}function _t(r){return ur.find(t=>t.id===r)?.flagCode||r}function dr(){return[...new Set(aa.map(r=>r.flagCode))]}var be={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},fr="public/logo.svg is missing: it is the site logo (Organization / publisher logo in the JSON-LD, the default logo) and the source of the favicon, PWA icons and og-image.png. Add public/logo.svg.",kt=[{name:"favicon.svg",sharp:!1},{name:"favicon.ico",size:32,sharp:!0},{name:"apple-touch-icon.png",size:180,sharp:!0},{name:"icon-192x192.png",size:192,sharp:!0},{name:"icon-512x512.png",size:512,sharp:!0},{name:Se.slice(1),sharp:!0}],Dt=".dndev/icons.json",la="sharp is not installed: favicon.ico, apple-touch-icon.png, icon-192x192.png, icon-512x512.png and og-image.png cannot be generated from public/logo.svg or kept in sync with it. Add sharp to the app devDependencies.",ca=new Set(["2b2e767d7d7b8f8775f6f7c3c670f4dba20d5b721da40812b2e76b70efe5bcb2","8a6ee0566fb17bfd659284911fe9e3913fdb6b33b339b0912a68c9f6f825e690"]),hr=new Set(["2b2e767d7d7b8f8775f6f7c3c670f4dba20d5b721da40812b2e76b70efe5bcb2","74f31fd5ca0d86421b467b2191f650d18ddc8334103142fcd3fc92d3e64a56b9","3ed7374c80df501da384dcbec914e9a2270b2d0af4866061a5f5a61172d68b29","d6f17727836ccdd5dd784e6576bfe3293b4ea8523c25a98aa092be3f30594a59","69970478481c9a5cd9e4c3437c325a315d321e6b4b055a7da29a25d71bcf6b85","c5de4c60c6412ad995ea48f5d4f6204f2874473f28044bc1a21aaf0ee224f6a6","cf96587a25bbe3d259275f34f22fe5212188c2e1c8e74bf0cf7ad6fb72c82ca1","376d735f3903c8320c41df554900b03a93c1659508e91b75e0a9752464238fff","b6c933dcd6d075296cdff68aaa8f7b64287477fb19d666455ac5b94767ec88dd","8a6ee0566fb17bfd659284911fe9e3913fdb6b33b339b0912a68c9f6f825e690","3c38ea7022ee2cc83fb8d4cc2e54f09ab88dd056fc5724ba207b5fde762d879d"]),qe=r=>ia("sha256").update(r).digest("hex"),gr="/manifest.json",Je=class extends ee{constructor(e,t={}){super(e,{assets:Y.assets.fallback,assetPatterns:Y.assets.patterns,frameworkPackage:pt.package,assetsPath:pt.assetsPath,modernFormats:Y.assets.modern,...t}),this.hasRunForSession=!1,this.flagCodes=null,this.entityResolver=null}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _prepareFiles(){let e=this.pathResolver.getAppRoot(),t=await this._ensureDefaultAssets(e);if(this.flagCodes){let i=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(i?[...new Set([...this.flagCodes,...dr()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${Nt}/: ${l.join(", ")}`)}let n=this.pathResolver.resolveAppPath("public/logo.svg");if(!this.pathResolver.pathExists(n)){let i=[];for(let{name:l}of kt){let c=this.pathResolver.resolveAppPath(`public/${l}`);this.pathResolver.pathExists(c)&&hr.has(qe(await this.pathResolver.read(c,{format:"buffer"})))&&i.push(`public/${l}`)}this.logger.warn(i.length>0?`${fr} These icons are framework defaults (the DoNotDev logo): ${i.join(", ")}.`:fr)}let o=[],a=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(o=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:o}}async _processFiles(e,{copiedAssets:t,generatedAssets:n}){let s=this.pathResolver.getAppRoot(),{consumerFiles:o}=e,a=await this._processAssetFiles(o),i=this._buildAssetManifest(a,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${gr}`))}),l=await this._readLogoSvgContent("/logo.svg",s);return{assets:a,manifest:{...i,logoSvgContent:l},copiedAssets:t,generatedAssets:n}}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}useFlagCodes(e,t){this.flagCodes=e,this.entityResolver=t}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let n=this.getAssets().map(o=>o.path),s=t||this.options.modernFormats;for(let o of s){let a=`/${e}.${o}`;if(n.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let n=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${n}`),!n)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let s=this.pathResolver.resolveAppPath(le.public);this.pathResolver.pathExists(s)||(this.pathResolver.mkdir(s),this.logger.debug(`Created public directory: ${s}`));for(let o of this.options.assets)await this._ensureAsset(o,s,n)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(n){this.logger.debug(`Failed to ensure default assets: ${n.message}`)}return t}async _ensureAsset(e,t,n){let s=this.pathResolver.resolveAppPath(`${le.public}/${e}`);if(this.pathResolver.pathExists(s))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${n}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,s))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}_ensureFlags(e){let t=this.pathResolver.resolveFrameworkPackage("@donotdev/core");if(!t)throw new Error("Flag copy: @donotdev/core not found");let n=this.pathResolver.normalizePath(`${t}/${we.PUBLISHED_FLAGS}`),s=`${le.public}${Nt}`,o=[];for(let a of e){let i=pr(a),l=this.pathResolver.resolveAppPath(`${s}/${i}`);if(this.pathResolver.pathExists(l))continue;let c=`${n}/${i}`;if(!this.pathResolver.pathExists(c)){this.logger.warn(`No flag artwork for "${a}": add ${s}/${i} to the app`);continue}if(!this.pathResolver.copySync(c,l))throw new Error(`Flag copy: cannot copy ${c} to ${l}`);o.push(i)}return o}async _processAssetFiles(e){let t=[];for(let n of e)try{let s=this.pathResolver.getFileInfo(n);if(s&&s.isFile){let o=n.split("/").pop()||n.split("\\").pop(),a=this._analyzeAsset(o,s.size);a&&t.push(a)}}catch(s){this.logger.debug(`Error processing asset file ${n}: ${s.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let n=this._determineAssetType(e),s=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:n,format:s,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(s)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let n=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(n)?"image":["woff2","woff","ttf","otf"].includes(n)?"font":["json"].includes(n)?"json":["ico"].includes(n)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,n=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+n[s]}_matchesPattern(e,t){let n=t.split("*").map(s=>s.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let n=e.map(o=>o.path);return{logo:{optimal:this._getOptimalAsset("logo",n,this.options.modernFormats),fallback:this._getOptimalAsset("logo",n,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",n,["svg","ico"]),fallback:this._getOptimalAsset("favicon",n,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",n,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",n,["png"]),512:this._getOptimalAsset("android-chrome-512x512",n,["png"])},manifest:t?gr:null,modernFormats:e.filter(o=>o.isModern).map(o=>o.path),fallbackFormats:e.filter(o=>!o.isModern).map(o=>o.path)}}_getOptimalAsset(e,t,n){for(let s of n){let o=`/${e}.${s}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),n=await this._resolvePackage("@donotdev/ui",t);if(!n)return this.logger.debug("@donotdev/ui package not found"),null;let s=this.pathResolver.normalizePath(`${n}/assets`);return this.pathResolver.pathExists(s)?(this.logger.debug(`Using framework assets from: ${s}`),s):(this.logger.debug(`Assets directory not found: ${s}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let n=this.pathResolver.resolveFrameworkPackage(e,t);return n?(this.logger.debug(`Found package: ${n}`),n):(this.logger.debug(`Package ${e} not found`),null)}catch(n){return this.logger.debug(`Error resolving package ${e}: ${n.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let n=e.slice(1),s=this.pathResolver.resolveAppPath(`${le.public}/${n}`);return this.pathResolver.pathExists(s)&&await this.pathResolver.read(s,{format:"text"})||null}catch(n){return this.logger.debug(`Failed to read logo SVG content: ${n.message}`),null}}async _renderOgImage(e,t){let{width:n,height:s}=await e(t).metadata(),o=Math.min(be.logoWidth/n,be.logoHeight/s),a=await e(t,{density:Math.ceil(72*o)}).resize(be.logoWidth,be.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:be.width,height:be.height,channels:4,background:be.background}}).composite([{input:a}]).png().toBuffer()}async _importSharp(){let e=await import("sharp").catch(()=>null);return e?e.default:null}async _renderLogoOutput(e,t,n){return e.name==="favicon.svg"?t:e.name===Se.slice(1)?this._renderOgImage(n,t):n(t).resize(e.size,e.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}).png().toBuffer()}async _readIconState(){let e=this.pathResolver.resolveAppPath(Dt);if(!this.pathResolver.pathExists(e))return{};let t=await this.pathResolver.read(e,{format:"text"});try{return JSON.parse(t)}catch(n){throw x("dndev-assets",`${Dt} is not valid JSON (${n.message}): fix it, or delete it and the icons generated from public/logo.svg to regenerate both.`,"invalid-configuration")}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),n=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let s=await this.pathResolver.read(t,{format:"buffer"});if(!s)return{generated:[],skipped:kt.map(d=>d.name),error:"Failed to read logo.svg"};let o=qe(s),a=ca.has(o),i=await this._readIconState(),l={},c=await this._importSharp();c||this.logger.warn(la);let u=[],p=[];for(let d of kt){let f=`${n}/${d.name}`,h=i[d.name],m=!1;if(this.pathResolver.pathExists(f)){let y=qe(await this.pathResolver.read(f,{format:"buffer"})),S=h?.sha256===y;if(S&&(l[d.name]=h),a){p.push(d.name);continue}if(hr.has(y))m=!0;else if(S){if(h.logo===o){p.push(d.name);continue}}else{this.logger.debug(`public/${d.name} is the app's own (not generated from logo.svg): left as is`),p.push(d.name);continue}}if(d.sharp&&!c){p.push(d.name);continue}try{let y=await this._renderLogoOutput(d,s,c);if(!await this.pathResolver.write(f,y,{overwrite:!0}))throw new Error(`cannot write ${f}`);l[d.name]={logo:o,sha256:qe(y)},u.push(d.name),m&&this.logger.warn(`replaced framework default public/${d.name}`)}catch(y){this.logger.debug(`Failed to generate ${d.name}: ${y.message}`),p.push(d.name)}}return await this._writeIconState(i,l),{generated:u,skipped:p,error:null}}async _writeIconState(e,t){if(JSON.stringify(e)===JSON.stringify(t))return;let n=this.pathResolver.resolveAppPath(Dt);if(Object.keys(t).length===0){await this.pathResolver.remove(n);return}if(!await this.pathResolver.write(n,t,{overwrite:!0}))throw new Error(`Asset generation: cannot write ${n}`)}};var Tt=class extends H{constructor(e={}){super(Je,e)}getHandlerDefaults(){return{manifestPath:L.next.assetManifest,generateManifest:!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
|
|
81
80
|
// Generated at: ${new Date().toISOString()}
|
|
82
81
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
83
82
|
|
|
@@ -94,7 +93,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
94
93
|
timestamp: Date.now(),
|
|
95
94
|
};
|
|
96
95
|
}
|
|
97
|
-
globalThis._DNDEV_CONFIG_.${
|
|
96
|
+
globalThis._DNDEV_CONFIG_.${X.assets} = {
|
|
98
97
|
mapping: assetConfig.manifest,
|
|
99
98
|
logoSvgContent: ${JSON.stringify(t)},
|
|
100
99
|
manifest: {
|
|
@@ -136,16 +135,16 @@ export const assetStats = {
|
|
|
136
135
|
};
|
|
137
136
|
|
|
138
137
|
export default assets;
|
|
139
|
-
`}};function
|
|
138
|
+
`}};function mr(r={}){return new Tt(r)}import Ot from"node:fs";import ua from"node:path";var Ft=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!Ot.existsSync(e))return{blogDir:e,files:[]};let t;try{t=Ot.readdirSync(e)}catch{return{blogDir:e,files:[]}}let n=t.filter(s=>s.endsWith(".md")&&!s.startsWith(".")).sort();return{blogDir:e,files:n}}},It=class extends H{constructor(e={}){super(Ft,e)}getHandlerDefaults(){return{outputPath:L.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:n}=e;if(n.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let s=this._buildGeneratedContent(t,n);this.writeGeneratedFile(this.options.outputPath,s,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
140
139
|
// Regenerated when src/content/blog/*.md files change
|
|
141
140
|
|
|
142
141
|
const blogContent: Record<string, string> = {
|
|
143
|
-
${t.map(s=>{let o=
|
|
142
|
+
${t.map(s=>{let o=Ot.readFileSync(ua.join(e,s),"utf8");return` './${s}': ${JSON.stringify(o)},`}).join(`
|
|
144
143
|
`)}
|
|
145
144
|
};
|
|
146
145
|
|
|
147
146
|
export default blogContent;
|
|
148
|
-
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function hr(r={}){return new Tt(r)}function pa(r){if(!r)return[];let e=D.getInstance(),t=new Set;try{let n=e.resolvePackage("@donotdev/core",r);if(!n)return[];let s=e.getDirname(e.getDirname(n)),o;try{o=e.readdirSync(s)}catch{return[]}for(let a of o)try{let i=e.resolvePath(`${a}/package.json`,s),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[u,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(u)}catch{}}catch{}return Array.from(t)}function da(r){if(!r)return[];let e=D.getInstance();try{let t=e.resolvePath("package.json",r),n=e.readSync(t,{format:"json"});if(!n)return[];let s=new Set;if(n.peerDependenciesMeta)for(let[o,a]of Object.entries(n.peerDependenciesMeta))a?.optional&&s.add(o);if(n.optionalDependencies)for(let o of Object.keys(n.optionalDependencies))s.add(o);return Array.from(s)}catch{return[]}}function fa(r){let e=Le.optionalFeatures||[],t=pa(r),n=da(r);return[...new Set([...e,...t,...n])]}function ha(r){let e=D.getInstance();try{let t=e.resolvePath("package.json",r),n=e.readSync(t,{format:"json"});return n?new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{})]):new Set}catch{return new Set}}function ga(r,e,t){let n=new Set,s=t.resolvePackage("@donotdev/core",r);if(!s)return n;let o=t.getDirname(t.getDirname(s));for(let a of e){if(!a.startsWith("@donotdev/"))continue;let i=t.resolvePath(`${a.slice(10)}/package.json`,o);if(!t.pathExists(i))continue;let l=t.readSync(i,{format:"json"});for(let u of Object.keys(l?.dependencies||{}))n.add(u)}return n}function ma(r,e,t){if(t.resolvePackage(r,e||void 0))return!0;let n=r.startsWith("@")?r.split("/").slice(0,2).join("/"):r.split("/")[0],s=e;for(let o=0;o<10;o++){let a=t.resolvePath(`node_modules/${n}`,s);if(t.pathExists(a))return!0;let i=t.getDirname(s);if(i===s)break;s=i}return!1}function Je(r){let e=fa(r),t=[],n=[],s=D.getInstance(),o=ha(r),a=ga(r,o,s);for(let i of e)i.startsWith("@donotdev/")?o.has(i)?n.push(i):t.push(i):(o.has(i)||a.has(i))&&ma(i,r,s)?n.push(i):t.push(i);return{missing:t,installed:n}}var Ve=class extends ee{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[n,s]of Object.entries(e)){for(let o of Object.keys(s))t.includes(o)||delete s[o];Object.keys(s).length===0&&delete e[n]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),n=this.pathResolver.getRepoRoot();if(!t||t===n)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${n})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${n}`);let s=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${s.eager.length}, lazy: ${s.lazy.length}, framework eager: ${s.framework?.eager?.length||0}, framework lazy: ${s.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Me("i18n"),a=s.eager||[],i=s.lazy||[],l=(this.options.additionalPaths||[]).map(w=>{let E=w.endsWith(".json")?w:`${w}/*_*.json`;return this.pathResolver.resolveAppPath(E)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let u=s.framework?.eager||[],c=s.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${u.join(", ")}, framework lazy: ${c.join(", ")}`),u.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),d=this.pathResolver.normalizePath(n),f=(w,E)=>{let P=this.pathResolver.normalizePath(w),I=this.pathResolver.normalizePath(E);return P.startsWith(I)?P.slice(I.length+1):P},h=a.map(w=>f(w,t)),y=[...i,...l].map(w=>f(w,t)),S=u.map(w=>f(w,n)),T=c.map(w=>f(w,n)),R={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},v=await this.pathResolver._globWithNormalization(h,R),x=await this.pathResolver._globWithNormalization(y,R),O={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:o.ignore?.filter(w=>w!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${n}, ignore: ${JSON.stringify(O.ignore)}`);let B=await this.pathResolver._globWithNormalization(S,O),M=await this.pathResolver._globWithNormalization(T,O);this.logger.debug(`Found ${v.length} eager, ${x.length} lazy, ${B.length} framework eager, ${M.length} framework lazy files`),B.length>0?this.logger.debug(`Framework eager files (first 3): ${B.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${u.join(", ")}`),M.length>0?this.logger.debug(`Framework lazy files (first 3): ${M.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let te=[...new Set([...v,...x,...B,...M])],W=new Set([...v,...B]),g={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:b}=Je(t),k=new Set(b.filter(w=>w.startsWith("@donotdev/")).map(w=>w.replace("@donotdev/","")));k.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...k].join(", ")}] (packages not installed)`);let N=new Map,_=[...B,...M];for(let w of _){let E=this._processTranslationFile(w,B.includes(w),t);if(E){if(k.has(E.namespace))continue;let P=`${E.namespace}_${E.language}`;N.set(P,E),g.allNamespaces.add(E.namespace),g.supportedLanguages.add(E.language),B.includes(w)&&g.eagerNamespaces.add(E.namespace)}}let F=new Set;for(let w of te){if(_.includes(w))continue;let E=this._processTranslationFile(w,W.has(w),t);if(E){let{namespace:P,language:I,importPath:V,content:ge}=E,de=`${E.namespace}_${E.language}`;if(N.has(de)){let me=N.get(de);E.content=this._mergeTranslations(me.content,ge)}g.allNamespaces.add(P),g.supportedLanguages.add(I),F.add(I),W.has(w)&&g.eagerNamespaces.add(P),g.mapping[P]||(g.mapping[P]={}),g.mapping[P][I]=V,E.content&&(g.content[P]||(g.content[P]={}),g.content[P][I]=E.content),g.files.push({path:w,relativePath:this.pathResolver.getRelativePath(w),namespace:P,language:I,eager:W.has(w),size:E.content?JSON.stringify(E.content).length:0})}}for(let[w,E]of N){let P=w.lastIndexOf("_"),I=w.slice(0,P),V=w.slice(P+1);F.size>0&&!F.has(V)||(!g.mapping[I]||!g.mapping[I][V])&&(g.mapping[I]||(g.mapping[I]={}),g.mapping[I][V]=E.importPath,g.content[I]||(g.content[I]={}),g.content[I][V]=E.content,g.files.push({path:E.absolutePath,relativePath:this.pathResolver.getRelativePath(E.absolutePath),namespace:I,language:V,eager:g.eagerNamespaces.has(I),size:E.content?JSON.stringify(E.content).length:0}))}let A=F.size>0?[...F].sort():[this.options.fallbackLanguage],G=this._getLanguageAllowlist(),j=A;if(G){let w=A.filter(P=>G.includes(P));j=w.length>0?w:[this.options.fallbackLanguage],this._restrictByLanguage(g.mapping,j),this._restrictByLanguage(g.content,j),g.files=g.files.filter(P=>j.includes(P.language));let E=new Set(Object.keys(g.mapping));g.allNamespaces=new Set([...g.allNamespaces].filter(P=>E.has(P))),g.eagerNamespaces=new Set([...g.eagerNamespaces].filter(P=>E.has(P))),this.logger.debug(`I18n restricted by i18n.only [${G.join(", ")}]: languages [${j.join(", ")}], namespaces ${E.size}`)}let re=[...new Set(j.map(Nt))];return{mapping:g.mapping,content:g.content,eagerNamespaces:[...g.eagerNamespaces].sort(),allNamespaces:[...g.allNamespaces].sort(),supportedLanguages:j,fallbackLanguage:this.options.fallbackLanguage,flagCodes:re,files:g.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[Nt(this.options.fallbackLanguage)],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let n=await this._processFiles([]);this.cache={...n,timestamp:Date.now()};let s=Date.now()-t;return this.logger.debug(`Discovery completed in ${s}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){throw this.logger.error(`I18n discovery failed: ${n.message}`),n}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,n){let s=e.split("/").pop()||e.split("\\").pop()||"",o,a,i=s.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${s}`),null;if([,o,a]=i,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${s}`),null;let u="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(p){return this.logger.debug(`Error parsing JSON from ${e}: ${p.message}`),null}return{namespace:o,language:a,importPath:u,absolutePath:e,content:c}}_mergeTranslations(e,t){let n={...e};for(let[s,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?n[s]=this._mergeTranslations(n[s]||{},o):n[s]=o;return n}};var Ot=class extends H{constructor(e={}){super(Ve,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...De.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],n=Object.keys(e.mapping||{}).filter(s=>s!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${n} 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:[]}}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||{},n=t.totalNamespaces||0,s=t.totalLanguages||0;return`${n} namespaces, ${s} languages`}async generateSpecificFiles(){}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:n,eagerNamespaces:s,fallbackLanguage:o,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
147
|
+
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function yr(r={}){return new It(r)}function pa(r){if(!r)return[];let e=O.getInstance(),t=new Set;try{let n=e.resolvePackage("@donotdev/core",r);if(!n)return[];let s=e.getDirname(e.getDirname(n)),o;try{o=e.readdirSync(s)}catch{return[]}for(let a of o)try{let i=e.resolvePath(`${a}/package.json`,s),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[c,u]of Object.entries(l.peerDependenciesMeta))u?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function da(r){if(!r)return[];let e=O.getInstance();try{let t=e.resolvePath("package.json",r),n=e.readSync(t,{format:"json"});if(!n)return[];let s=new Set;if(n.peerDependenciesMeta)for(let[o,a]of Object.entries(n.peerDependenciesMeta))a?.optional&&s.add(o);if(n.optionalDependencies)for(let o of Object.keys(n.optionalDependencies))s.add(o);return Array.from(s)}catch{return[]}}function fa(r){let e=Me.optionalFeatures||[],t=pa(r),n=da(r);return[...new Set([...e,...t,...n])]}function ha(r){let e=O.getInstance();try{let t=e.resolvePath("package.json",r),n=e.readSync(t,{format:"json"});return n?new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{})]):new Set}catch{return new Set}}function ga(r,e,t){let n=new Set,s=t.resolvePackage("@donotdev/core",r);if(!s)return n;let o=t.getDirname(t.getDirname(s));for(let a of e){if(!a.startsWith("@donotdev/"))continue;let i=t.resolvePath(`${a.slice(10)}/package.json`,o);if(!t.pathExists(i))continue;let l=t.readSync(i,{format:"json"});for(let c of Object.keys(l?.dependencies||{}))n.add(c)}return n}function ma(r,e,t){if(t.resolvePackage(r,e||void 0))return!0;let n=r.startsWith("@")?r.split("/").slice(0,2).join("/"):r.split("/")[0],s=e;for(let o=0;o<10;o++){let a=t.resolvePath(`node_modules/${n}`,s);if(t.pathExists(a))return!0;let i=t.getDirname(s);if(i===s)break;s=i}return!1}function Ve(r){let e=fa(r),t=[],n=[],s=O.getInstance(),o=ha(r),a=ga(r,o,s);for(let i of e)i.startsWith("@donotdev/")?o.has(i)?n.push(i):t.push(i):(o.has(i)||a.has(i))&&ma(i,r,s)?n.push(i):t.push(i);return{missing:t,installed:n}}var Ke=class extends ee{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[n,s]of Object.entries(e)){for(let o of Object.keys(s))t.includes(o)||delete s[o];Object.keys(s).length===0&&delete e[n]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),n=this.pathResolver.getRepoRoot();if(!t||t===n)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${n})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${n}`);let s=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${s.eager.length}, lazy: ${s.lazy.length}, framework eager: ${s.framework?.eager?.length||0}, framework lazy: ${s.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Ue("i18n"),a=s.eager||[],i=s.lazy||[],l=(this.options.additionalPaths||[]).map(w=>{let R=w.endsWith(".json")?w:`${w}/*_*.json`;return this.pathResolver.resolveAppPath(R)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let c=s.framework?.eager||[],u=s.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${u.join(", ")}`),c.length===0&&u.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),d=this.pathResolver.normalizePath(n),f=(w,R)=>{let C=this.pathResolver.normalizePath(w),I=this.pathResolver.normalizePath(R);return C.startsWith(I)?C.slice(I.length+1):C},h=a.map(w=>f(w,t)),y=[...i,...l].map(w=>f(w,t)),S=c.map(w=>f(w,n)),_=u.map(w=>f(w,n)),P={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},v=await this.pathResolver._globWithNormalization(h,P),E=await this.pathResolver._globWithNormalization(y,P),A={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:o.ignore?.filter(w=>w!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${n}, ignore: ${JSON.stringify(A.ignore)}`);let U=await this.pathResolver._globWithNormalization(S,A),M=await this.pathResolver._globWithNormalization(_,A);this.logger.debug(`Found ${v.length} eager, ${E.length} lazy, ${U.length} framework eager, ${M.length} framework lazy files`),U.length>0?this.logger.debug(`Framework eager files (first 3): ${U.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),M.length>0?this.logger.debug(`Framework lazy files (first 3): ${M.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${u.join(", ")}`);let te=[...new Set([...v,...E,...U,...M])],W=new Set([...v,...U]),g={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:b}=Ve(t),T=new Set(b.filter(w=>w.startsWith("@donotdev/")).map(w=>w.replace("@donotdev/","")));T.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...T].join(", ")}] (packages not installed)`);let k=new Map,D=[...U,...M];for(let w of D){let R=this._processTranslationFile(w,U.includes(w),t);if(R){if(T.has(R.namespace))continue;let C=`${R.namespace}_${R.language}`;k.set(C,R),g.allNamespaces.add(R.namespace),g.supportedLanguages.add(R.language),U.includes(w)&&g.eagerNamespaces.add(R.namespace)}}let F=new Set;for(let w of te){if(D.includes(w))continue;let R=this._processTranslationFile(w,W.has(w),t);if(R){let{namespace:C,language:I,importPath:V,content:ge}=R,de=`${R.namespace}_${R.language}`;if(k.has(de)){let me=k.get(de);R.content=this._mergeTranslations(me.content,ge)}g.allNamespaces.add(C),g.supportedLanguages.add(I),F.add(I),W.has(w)&&g.eagerNamespaces.add(C),g.mapping[C]||(g.mapping[C]={}),g.mapping[C][I]=V,R.content&&(g.content[C]||(g.content[C]={}),g.content[C][I]=R.content),g.files.push({path:w,relativePath:this.pathResolver.getRelativePath(w),namespace:C,language:I,eager:W.has(w),size:R.content?JSON.stringify(R.content).length:0})}}for(let[w,R]of k){let C=w.lastIndexOf("_"),I=w.slice(0,C),V=w.slice(C+1);F.size>0&&!F.has(V)||(!g.mapping[I]||!g.mapping[I][V])&&(g.mapping[I]||(g.mapping[I]={}),g.mapping[I][V]=R.importPath,g.content[I]||(g.content[I]={}),g.content[I][V]=R.content,g.files.push({path:R.absolutePath,relativePath:this.pathResolver.getRelativePath(R.absolutePath),namespace:I,language:V,eager:g.eagerNamespaces.has(I),size:R.content?JSON.stringify(R.content).length:0}))}let N=F.size>0?[...F].sort():[this.options.fallbackLanguage],G=this._getLanguageAllowlist(),B=N;if(G){let w=N.filter(C=>G.includes(C));B=w.length>0?w:[this.options.fallbackLanguage],this._restrictByLanguage(g.mapping,B),this._restrictByLanguage(g.content,B),g.files=g.files.filter(C=>B.includes(C.language));let R=new Set(Object.keys(g.mapping));g.allNamespaces=new Set([...g.allNamespaces].filter(C=>R.has(C))),g.eagerNamespaces=new Set([...g.eagerNamespaces].filter(C=>R.has(C))),this.logger.debug(`I18n restricted by i18n.only [${G.join(", ")}]: languages [${B.join(", ")}], namespaces ${R.size}`)}let re=[...new Set(B.map(_t))];return{mapping:g.mapping,content:g.content,eagerNamespaces:[...g.eagerNamespaces].sort(),allNamespaces:[...g.allNamespaces].sort(),supportedLanguages:B,fallbackLanguage:this.options.fallbackLanguage,flagCodes:re,files:g.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[_t(this.options.fallbackLanguage)],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let n=await this._processFiles([]);this.cache={...n,timestamp:Date.now()};let s=Date.now()-t;return this.logger.debug(`Discovery completed in ${s}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){throw this.logger.error(`I18n discovery failed: ${n.message}`),n}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,n){let s=e.split("/").pop()||e.split("\\").pop()||"",o,a,i=s.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${s}`),null;if([,o,a]=i,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${s}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),u;try{if(u=this.pathResolver.readSync(e,{format:"json"}),!u)return this.logger.debug(`Could not read file: ${e}`),null}catch(p){return this.logger.debug(`Error parsing JSON from ${e}: ${p.message}`),null}return{namespace:o,language:a,importPath:c,absolutePath:e,content:u}}_mergeTranslations(e,t){let n={...e};for(let[s,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?n[s]=this._mergeTranslations(n[s]||{},o):n[s]=o;return n}};var Lt=class extends H{constructor(e={}){super(Ke,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...De.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],n=Object.keys(e.mapping||{}).filter(s=>s!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${n} 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:[]}}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||{},n=t.totalNamespaces||0,s=t.totalLanguages||0;return`${n} namespaces, ${s} languages`}async generateSpecificFiles(){}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:n,eagerNamespaces:s,fallbackLanguage:o,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
149
148
|
// Generated at: ${new Date().toISOString()}
|
|
150
149
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
151
150
|
|
|
@@ -187,12 +186,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
187
186
|
timestamp: Date.now(),
|
|
188
187
|
};
|
|
189
188
|
}
|
|
190
|
-
globalThis._DNDEV_CONFIG_.${
|
|
189
|
+
globalThis._DNDEV_CONFIG_.${X.i18n} = i18nConfig;
|
|
191
190
|
}
|
|
192
191
|
|
|
193
192
|
// Export for compatibility
|
|
194
193
|
export default i18nConfig;
|
|
195
|
-
`}};function
|
|
194
|
+
`}};function vr(r={}){return new Lt(r)}var Ye=class extends ee{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:n}=e,s=[...t,...n];this.logger.debug(`Processing ${s.length} PWA files`);let o=await this._analyzePWAFiles(s),a=[...o.filter(l=>l.type==="manifest"||l.type==="service-worker"),...o.filter(l=>l.type==="icon")],i=this._generatePWAManifest(a);return{assets:a,manifest:i,totalFiles:s.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let n of e){let s=typeof n=="string"?{absolutePath:n,relativePath:this.pathResolver.getRelativePath(n),fileName:n.split("/").pop()||"",extension:(n.split(".").pop()||"").toLowerCase()}:n,o=await this._analyzePWAAsset(s);o&&t.push(o)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let n=e.relativePath,s=e.fileName;return s==="manifest.json"?this._parseManifestFile(t,n):s.includes("service-worker")||s.includes("sw.")?this._parseServiceWorkerFile(t,n):this._isPWAIcon(s)?this._parseIconFile(e,n):null}_parseManifestFile(e,t){try{let n=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:n,size:typeof e=="string"?e.length:JSON.stringify(n).length}}catch(n){return this.logger.debug(`Failed to parse manifest: ${n.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let n=e.fileName,s=this._extractIconSize(n);return{type:"icon",path:t,size:s,format:e.extension,purpose:this._getIconPurpose(n)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(n=>e.includes(n))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(s=>s.type==="icon"),n=this._getDefaultManifest();return t.length>0&&(n.icons=t.map(s=>this.toManifestIcon(s))),n}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},n=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:n==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[n]||`image/${n}`,purpose:e.purpose==="maskable"?"maskable":"any"}}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let t=e.manifest||this._getDefaultManifest();return JSON.stringify(t,null,2)}generateServiceWorkerContent(e,t={}){let n=this._getWorkboxDefaults(t),s=t.backgroundSync!==!1&&t.backgroundSync,o=t.precacheManifest||[],a=JSON.stringify(o,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
196
195
|
// Generated at ${new Date().toISOString()}
|
|
197
196
|
|
|
198
197
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -226,22 +225,22 @@ self.addEventListener('message', (event) => {
|
|
|
226
225
|
self.addEventListener('activate', (event) => {
|
|
227
226
|
event.waitUntil(self.clients.claim());
|
|
228
227
|
});
|
|
229
|
-
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((n,s)=>{let{urlPattern:o,handler:a,options:i={}}=n,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",
|
|
228
|
+
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((n,s)=>{let{urlPattern:o,handler:a,options:i={}}=n,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",c;typeof o=="function"?c="({ request }) => request.destination === 'document'":o instanceof RegExp?c=o.toString():c=JSON.stringify(o);let u=[];i.expiration&&u.push(`new ExpirationPlugin({
|
|
230
229
|
maxEntries: ${i.expiration.maxEntries||50},
|
|
231
230
|
maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
|
|
232
|
-
})`),i.cacheableResponse&&
|
|
231
|
+
})`),i.cacheableResponse&&u.push(`new CacheableResponsePlugin({
|
|
233
232
|
statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
|
|
234
|
-
})`),i.backgroundSync&&
|
|
233
|
+
})`),i.backgroundSync&&u.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
|
|
235
234
|
maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
|
|
236
235
|
})`);let p="";return i.cacheName&&(p+=`
|
|
237
|
-
cacheName: '${i.cacheName}',`),
|
|
236
|
+
cacheName: '${i.cacheName}',`),u.length>0&&(p+=`
|
|
238
237
|
plugins: [
|
|
239
|
-
${
|
|
238
|
+
${u.join(`,
|
|
240
239
|
`)}
|
|
241
240
|
],`),i.networkTimeoutSeconds&&(p+=`
|
|
242
241
|
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${s+1}: ${i.cacheName||"cache-"+s}
|
|
243
242
|
registerRoute(
|
|
244
|
-
${
|
|
243
|
+
${c},
|
|
245
244
|
new ${l}({${p}
|
|
246
245
|
})
|
|
247
246
|
);`}).join(`
|
|
@@ -260,7 +259,7 @@ registerRoute(
|
|
|
260
259
|
}),
|
|
261
260
|
'POST'
|
|
262
261
|
);
|
|
263
|
-
`}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),n=this.pathResolver.resolveAppPath(`${e}/static/chunks`),s=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${n}/**/*.{js,css}`,`${s}/**/*.css`];for(let i of a){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let
|
|
262
|
+
`}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),n=this.pathResolver.resolveAppPath(`${e}/static/chunks`),s=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${n}/**/*.{js,css}`,`${s}/**/*.css`];for(let i of a){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let c of l){let u=this.pathResolver.getRelativePath(c);if(u.startsWith(`${e}/static/`)){let p=`/_next/${u.replace(`${e}/static/`,"")}`;o.push({url:p,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return o}generatePrecacheManifest(e=[],t=null){let n=e;return t&&typeof t=="function"&&(n=t(n)),n}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Mt=class extends H{constructor(e={}){super(Ye,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){return new e(this.pathResolver,this.options)}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}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)}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||{},n=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");n=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let s=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:n});this.writeGeneratedFile(this.options.serviceWorkerPath,s,"service worker")}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function br(r={}){return new Mt(r)}var wr={requestDocumentParts(r){return[[/<ClientLayout\b/,"renders <ClientLayout>"],[/from\s+['"]next\/headers['"]/,"imports next/headers"],[/export\s+const\s+dynamic\b/,"exports `dynamic`"]].filter(([e])=>e.test(r)).map(([,e])=>e)},async assertAppDocument(){let r=L.next.appDocument,e=`${r} exports \`metadata\` (site-level: metadataBase) and \`AppDocument({ lang, children })\`, which renders <html lang={lang}>, the <head> links the app needs (the framework renders the favicon and font tags), imports the global CSS and puts {children} in <body> (see the @donotdev/cli app-next template)`,t=[];for(let o of this.frameworkRootFiles()){let a=this.pathResolver.resolveAppPath(o);this.pathResolver.pathExists(a)&&!await this.hasGenerationMarker(a)&&t.push(o)}if(t.length>0)throw new Error(`[dndev] ${t.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 ${r}: ${e}. Then delete ${t.join(", ")}.`);let n=this.pathResolver.resolveAppPath(r);if(!this.pathResolver.pathExists(n))throw new Error(`[dndev] ${r} is missing: ${e}.`);let s=this.requestDocumentParts(await this.pathResolver.read(n,{format:"text"}));if(s.length!==0)throw new Error(`[dndev] ${r} ${s.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 r=j("layout","tsx"),e=j("not-found","tsx");return[L.next.appLayout,`src/app/[lang]/${r}`,`src/app/${e}`,`src/app/[lang]/${e}`,`src/app/${j("global-not-found","tsx")}`]},async generateTreeLayout(r){let e=`src/app${this.treeDir(r)}/${j("layout","tsx")}`,t=this.pathResolver.resolveAppPath(e);if(this.pathResolver.pathExists(t)&&!await this.hasGenerationMarker(t)){this.logger.debug(`Skipping ${e} - user-created file detected`);return}this.writeGeneratedFile(e,r==="session"?this.generateSessionLayoutContent():this.generateSiteLayoutContent(),`${r} layout`)},generateSiteLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
264
263
|
// Cached pages: rendered without request data (no cookies, no headers), served from the
|
|
265
264
|
// cache and ${this.revalidateLabel()} (appConfig.revalidate). One entry per URL (page and language).
|
|
266
265
|
|
|
@@ -298,7 +297,7 @@ export default async function SessionLayout({ children }: { children: ReactNode
|
|
|
298
297
|
</ClientLayout>
|
|
299
298
|
);
|
|
300
299
|
}
|
|
301
|
-
`},generateRootLayout(){this.writeGeneratedFile(L.next.fonts,this.generateFontsContent(),"font plan"),this.writeGeneratedFile(`src/app${this.rootDir()}/${
|
|
300
|
+
`},generateRootLayout(){this.writeGeneratedFile(L.next.fonts,this.generateFontsContent(),"font plan"),this.writeGeneratedFile(`src/app${this.rootDir()}/${j("layout","tsx")}`,this.generateRootLayoutContent(),"root layout")},generateFontsContent(){if(!this.fonts)throw new Error("[dndev] NextRouteHandler: the font plan is not set (runDiscoveries calls useFonts before generating routes).");let r={css:this.fonts.css,preloads:this.fonts.preloads};return`// Generated by @donotdev/config - DO NOT EDIT
|
|
302
301
|
// The app's font plan (@donotdev/core config fonts/buildFontPlan.js, from the theme font tokens
|
|
303
302
|
// and appConfig.fonts): inline @font-face rules and each language's font preloads, rendered
|
|
304
303
|
// by FontHead in the root layout and the global 404. Files: public/fonts/ (content-hashed).
|
|
@@ -367,7 +366,7 @@ export default function RootLayout({ children }: { children: ReactNode }) {
|
|
|
367
366
|
</AppDocument>
|
|
368
367
|
);
|
|
369
368
|
}
|
|
370
|
-
`},generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${
|
|
369
|
+
`},generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${j("not-found","tsx")}`,this.generateNotFoundContent(),"404 page"),this.writeGeneratedFile(`src/app/${j("global-not-found","tsx")}`,this.generateGlobalNotFoundContent(),"global 404 page")},generateNotFoundContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
371
370
|
// 404 page: the app's providers without request data (static, like every cached page).
|
|
372
371
|
// Shared fallback content must not expose the pathname captured during prerendering:
|
|
373
372
|
// NotFoundDocument drops URL-derived output (canonical, JSON-LD, breadcrumbs).
|
|
@@ -446,7 +445,7 @@ export default function GlobalNotFound() {
|
|
|
446
445
|
return (${r}
|
|
447
446
|
);
|
|
448
447
|
}
|
|
449
|
-
`}};var
|
|
448
|
+
`}};var Sr={isBlogPostRoute(r){return r.metaExport?.namespace==="blog"&&this.hasDynamicSegment(r.path)},extractDynamicParam(r){let e=r.match(/:([a-zA-Z0-9_]+)/);if(e)return e[1];let t=r.match(/\[([^\]]+)\]/);return t?t[1]:"slug"},generateBlogPostClientContent(r,e){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
450
449
|
// This file will be regenerated when src/pages changes
|
|
451
450
|
'use client';
|
|
452
451
|
|
|
@@ -597,19 +596,19 @@ export default async function BlogPostRoute({ params }: { params: Params }) {
|
|
|
597
596
|
</>
|
|
598
597
|
);
|
|
599
598
|
}
|
|
600
|
-
`}};function
|
|
601
|
-
`),p=t.map(
|
|
602
|
-
`),d=[...new Set(e.map(
|
|
599
|
+
`}};function Ut(r,e,t,n){try{if(t?.content?.[r]?.[e])return t.content[r][e];let s=t?.mapping?.[r]?.[e];if(!s)return null;let o=n.resolveAppPath(s),a=n.readSync(o,{format:"text"});return a?JSON.parse(a):null}catch{return null}}function Er(r){return r?.languages||r?.supportedLanguages||["en"]}function Rr(r){return r?.fallback||r?.fallbackLanguage||"en"}function ya(r,e,t,n={}){let{minLength:s=0,excludeEmpty:o=!0,customFilter:a}=n;return Array.from({length:t},(i,l)=>{let c=`${e}.${l}`;return r(c)}).filter((i,l)=>{let c=`${e}.${l}`;return!(i===c||o&&i.trim()===""||i.length<s||a&&!a(i,l))})}var va=20,$r={defaultValue:""};function xr(r,e,t){if(r!==null)return r!==void 0?r:t(e,$r)||void 0}function Pr(r,e){let t=o=>r(o,$r),n=o=>t(`${e}:meta.${o}`)||void 0,s=ya(t,`${e}:meta.keywords`,va);return{fullTitle:n("fullTitle"),image:n("image"),type:n("type"),keywords:s.length>0?s:void 0,author:n("author")}}function ba(r,e){return r===!0?"noindex, nofollow":r===!1?null:e?"noindex":null}function jt(r){let{meta:e,ns:t,defaultNs:n,t:s,siteName:o}=r,a=e.seo;if(!t&&!n)return{title:a?.fullTitle||o};let i=t?xr(a?.title,`${t}:title`,s):a?.title??void 0;return{title:a?.fullTitle||(t?Pr(s,t).fullTitle:void 0)||(i?`${i} | ${o}`:o),...i&&{pageTitle:i}}}function Cr(r){let{meta:e,ns:t,defaultNs:n,t:s,siteName:o,baseUrl:a,url:i,defaultImage:l}=r,c=e.seo,u=t??n,p=u?Pr(s,u):null,{title:d}=jt({meta:e,ns:t,defaultNs:n,t:s,siteName:o}),f=u?xr(c?.description,`${u}:description`,s):void 0,h=c?.image||p?.image||l||void 0,m=c?.keywords||p?.keywords,y=e.author||p?.author;return{title:d,...f&&{description:f},...h&&{image:h.startsWith("http")?h:`${a}${h}`},url:i,type:c?.type||p?.type||"website",robots:ba(c?.noindex??e.noindex,r.authOnly),...m&&{keywords:m},...y&&{author:y},...e.publishDate&&{publishDate:e.publishDate},...e.modifiedDate&&{modifiedDate:e.modifiedDate}}}function Xe(r){return(e,t)=>{let n=e.indexOf(":"),s=r[e.slice(0,n)];for(let o of e.slice(n+1).split("."))s=s&&typeof s=="object"&&o in s?s[o]:void 0;return typeof s=="string"?s:t?.defaultValue??e}}var Ar={async generateMetadataManifest(r){let e=this.i18n;if(!e)throw new Error("Route handler: translations not set before the metadata manifest (runDiscoveries calls useI18n)");let t=Er(e),n=Rr(e),s=this.options.siteName||"",o={};for(let i of r.routes){let l=i.metaExport?.namespace||null,c=this.defaultNamespace(),u=l||c,p={};for(let d of t){let f=Ut(u,d,e,this.pathResolver)||Ut(u,n,e,this.pathResolver),h=Cr({meta:i.metaExport||{},ns:l,defaultNs:c,t:Xe({[u]:f}),siteName:s,baseUrl:"",url:null,defaultImage:this.defaultImage(),authOnly:!!i.auth});p[d]={title:h.title,...h.description&&{description:h.description},image:h.image,type:h.type,...h.keywords&&{keywords:h.keywords},...h.robots&&{robots:h.robots}}}o[i.path]={locales:p,defaultLocale:n}}let a=JSON.stringify(o,null,2);this.writeGeneratedFile("public/metadata-manifest.json",a,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(o).length} routes`)}};var Nr={async generateMiddleware(r){this.removeLegacyMiddleware(),this.rendersSessionTree=!1;let e=r.routes.filter(l=>!!this.normalizeAuth(l.auth)),t=r.routes.filter(l=>l.meta?.signedInRedirect),n=this.usesCookieSession();(e.length>0||t.length>0)&&!n&&this.logger.debug("Auth session not in cookies (no Supabase createBrowserClient): pages use the client AuthGuard / SignedInRedirect only, no proxy auth redirects");let s=n?e:[],o=n?t:[],a=this.pathResolver.resolveAppPath(this.options.proxyPath),i=this.pathResolver.pathExists(a)&&!await this.hasGenerationMarker(a);if(!this.isMultilingual()&&!n){this.logger.debug("One language and no cookie session: no proxy.next.ts"),this.pathResolver.pathExists(a)&&!i&&await this.pathResolver.remove(a);return}if(i){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(s,r.routes,o,n),"proxy"),this.rendersSessionTree=n},async findAppRouteSegments(){let r=this.pathResolver.getAppRoot(),e=this.pathResolver.resolveAppPath(L.next.appPages),t=await this.pathResolver._globWithNormalization([`${L.next.appPages}/**/{route,page}.${he}.{ts,tsx,js,jsx}`],{cwd:r,absolute:!0,onlyFiles:!0,braceExpansion:!0}),n=new Set;for(let s of t){if(await this.hasGenerationMarker(s))continue;let[o]=s.slice(e.length+1).split("/").slice(0,-1).filter(a=>!/^\(.*\)$/.test(a));o&&o!=="[lang]"&&n.add(o)}return[...n].sort()},routePattern(r){return"^"+r.split("/").map(e=>e==="*"?".*":e.startsWith(":")?"[^/]+":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("/")+"$"},generateMiddlewareContent(r,e=[],t=[],n=!1){let s=this.isMultilingual(),o=r.length>0,a=t.length>0,i=o||a,l=n||i,c=this.options.auth??{},u=r.map(N=>{let{role:G}=this.normalizeAuth(N.auth);return` { pattern: new RegExp(${JSON.stringify(this.routePattern(N.path))})${G?`, role: ${JSON.stringify(G)}`:""} },`}).join(`
|
|
600
|
+
`),p=t.map(N=>` { pattern: new RegExp(${JSON.stringify(this.routePattern(N.path))}), to: ${JSON.stringify(N.meta.signedInRedirect)} },`).join(`
|
|
601
|
+
`),d=[...new Set(e.map(N=>N.path))].map(N=>` new RegExp(${JSON.stringify(this.routePattern(N))}),`).join(`
|
|
603
602
|
`),f=` ${JSON.stringify("/((?!api|_next|.*\\..*).*)")},`,h=[...o?["hasRoleAccess"]:[],...s?["LANGUAGE_COOKIE",...i?["localizePath"]:[],"parseAcceptLanguage","readCookieValue","resolveLanguageRoute","splitLanguagePath"]:[]],m=["hasSupabaseSessionCookie","refreshSupabaseSession",...i?["type SupabaseProxySession"]:[]],y=i?`,
|
|
604
603
|
session: SupabaseProxySession['session']`:"",S=s?`,
|
|
605
|
-
language: string`:"",
|
|
604
|
+
language: string`:"",_=l?"{ request }":"",P=`/${Z.sessionSegment}`,v=`// Generated by @donotdev/config - DO NOT EDIT
|
|
606
605
|
// Request gate (Next 16 proxy)${s?`: one URL per language, the default language (${this.options.defaultLanguage}) at the
|
|
607
606
|
// root, the others under their prefix (resolveLanguageRoute in @donotdev/core)`:""}.${l?`
|
|
608
607
|
// Session: the Supabase cookie (createBrowserClient). No auth cookie: signed out, the
|
|
609
608
|
// page comes from the cache (src/app${this.treeDir("site")}, static). With one: verified and refreshed
|
|
610
609
|
// when expired (refreshSupabaseSession: Auth getUser() for documents, local getClaims()
|
|
611
610
|
// for RSC soft navigations and prefetches), then rendered per request with the refreshed
|
|
612
|
-
// cookies (src/app${this.rootDir()}${
|
|
611
|
+
// cookies (src/app${this.rootDir()}${P}, an internal path: a direct hit is a 404); the browser
|
|
613
612
|
// gets the refreshed cookies on the response.`:""}${o?`
|
|
614
613
|
// Auth redirects for pages whose PageMeta sets \`auth\`, on the verified session.
|
|
615
614
|
// Redirect gate only: data access stays enforced by RLS, and the page's AuthGuard still
|
|
@@ -621,7 +620,7 @@ import type { NextRequest } from 'next/server';
|
|
|
621
620
|
|
|
622
621
|
${h.length?`import { ${h.join(", ")} } from '@donotdev/core/server';
|
|
623
622
|
`:""}${l?`import { ${m.join(", ")} } from '@donotdev/supabase/server';
|
|
624
|
-
`:""}`,
|
|
623
|
+
`:""}`,E=l?`
|
|
625
624
|
/** Supabase project of the cookie session (same env as src/config/providers.ts) */
|
|
626
625
|
const SUPABASE = supabaseProject(
|
|
627
626
|
process.env.NEXT_PUBLIC_SUPABASE_URL,
|
|
@@ -637,22 +636,22 @@ function supabaseProject(url: string | undefined, publicKey: string | undefined)
|
|
|
637
636
|
return { url, publicKey };
|
|
638
637
|
}
|
|
639
638
|
${s?`
|
|
640
|
-
/** Internal tree of the per-request pages (src/app/[lang]${
|
|
639
|
+
/** Internal tree of the per-request pages (src/app/[lang]${P}), after the language: never a public URL */
|
|
641
640
|
const SESSION_SEGMENT = ${JSON.stringify(Z.sessionSegment)};
|
|
642
641
|
|
|
643
|
-
/** Internal URL path of a page rendered per request: \`/fr/compte\` \u2192 \`/fr${
|
|
642
|
+
/** Internal URL path of a page rendered per request: \`/fr/compte\` \u2192 \`/fr${P}/compte\` */
|
|
644
643
|
function sessionPath(path: string): string {
|
|
645
644
|
const [, language, ...rest] = path.split('/');
|
|
646
645
|
return ['', language, SESSION_SEGMENT, ...rest].join('/');
|
|
647
646
|
}
|
|
648
647
|
|
|
649
|
-
/** A direct request for the internal tree (\`/fr${
|
|
648
|
+
/** A direct request for the internal tree (\`/fr${P}/\u2026\`) */
|
|
650
649
|
function isSessionTreePath(pathname: string): boolean {
|
|
651
650
|
return pathname.split('/').slice(1, 3).includes(SESSION_SEGMENT);
|
|
652
651
|
}
|
|
653
652
|
`:`
|
|
654
|
-
/** Internal tree of the per-request pages (src/app${
|
|
655
|
-
const SESSION_TREE = ${JSON.stringify(
|
|
653
|
+
/** Internal tree of the per-request pages (src/app${P}): never a public URL */
|
|
654
|
+
const SESSION_TREE = ${JSON.stringify(P)};
|
|
656
655
|
|
|
657
656
|
/** Internal URL path of a page rendered per request */
|
|
658
657
|
function sessionPath(path: string): string {
|
|
@@ -666,14 +665,14 @@ function isSessionTreePath(pathname: string): boolean {
|
|
|
666
665
|
`}${i?`
|
|
667
666
|
/** Session of a request without an auth cookie: signed out, nothing to verify */
|
|
668
667
|
const SIGNED_OUT: SupabaseProxySession['session'] = { user: null };
|
|
669
|
-
`:""}`:"",
|
|
668
|
+
`:""}`:"",A=o?`
|
|
670
669
|
/** appConfig.auth.authRoute: where a signed-out visitor goes (null: page fallback) */
|
|
671
|
-
const AUTH_ROUTE: string | null = ${JSON.stringify(
|
|
670
|
+
const AUTH_ROUTE: string | null = ${JSON.stringify(c.authRoute??null)};
|
|
672
671
|
/** appConfig.auth.roleRoute: where a visitor without the role goes (null: page fallback) */
|
|
673
|
-
const ROLE_ROUTE: string | null = ${JSON.stringify(
|
|
672
|
+
const ROLE_ROUTE: string | null = ${JSON.stringify(c.roleRoute??null)};
|
|
674
673
|
|
|
675
674
|
const protectedRoutes: Array<{ pattern: RegExp; role?: string }> = [
|
|
676
|
-
${
|
|
675
|
+
${u}
|
|
677
676
|
];
|
|
678
677
|
|
|
679
678
|
/** Protected pages exist only in the per-request tree (no cached copy) */
|
|
@@ -703,7 +702,7 @@ function authRedirect(
|
|
|
703
702
|
}
|
|
704
703
|
return null;
|
|
705
704
|
}
|
|
706
|
-
`:"",
|
|
705
|
+
`:"",U=a?`
|
|
707
706
|
/** PageMeta \`signedInRedirect\`: where a signed-in visitor of the page goes */
|
|
708
707
|
const signedInRoutes: Array<{ pattern: RegExp; to: string }> = [
|
|
709
708
|
${p}
|
|
@@ -741,19 +740,19 @@ ${d}
|
|
|
741
740
|
`:"",W=i?"session, ":"",g=" // 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);",b=`
|
|
742
741
|
request: NextRequest${y}${l?`,
|
|
743
742
|
personal: boolean`:""}
|
|
744
|
-
`,
|
|
745
|
-
const redirect = authRedirect(request, ${W}${
|
|
743
|
+
`,T=(N,G)=>`${o?`
|
|
744
|
+
const redirect = authRedirect(request, ${W}${N}${G});
|
|
746
745
|
if (redirect) return redirect;
|
|
747
746
|
`:""}${a?`
|
|
748
|
-
const signedIn = signedInRedirect(request, ${W}${
|
|
747
|
+
const signedIn = signedInRedirect(request, ${W}${N}${G});
|
|
749
748
|
if (signedIn) return signedIn;
|
|
750
|
-
`:""}`,
|
|
749
|
+
`:""}`,k=(N,G)=>l?`
|
|
751
750
|
// Auth cookie: rendered per request with the visitor's cookies${o?`. Protected pages
|
|
752
751
|
// have no cached copy: per request for every visitor`:""}
|
|
753
|
-
if (personal${o?` || isProtectedRoute(${G})`:""}) {${
|
|
754
|
-
const page = ${
|
|
755
|
-
return NextResponse.rewrite(new URL(sessionPath(${
|
|
756
|
-
}`:"",
|
|
752
|
+
if (personal${o?` || isProtectedRoute(${G})`:""}) {${N==="pathname"?"":`
|
|
753
|
+
const page = ${N};`}
|
|
754
|
+
return NextResponse.rewrite(new URL(sessionPath(${N==="pathname"?"pathname":"page"}) + search, request.url), { request });
|
|
755
|
+
}`:"",D;s?D=`
|
|
757
756
|
/** Language routing, redirects and render tree of a page request. */
|
|
758
757
|
function route(${b}): NextResponse {
|
|
759
758
|
const { pathname, search } = request.nextUrl;
|
|
@@ -788,20 +787,20 @@ function route(${b}): NextResponse {
|
|
|
788
787
|
decision.permanent ? 308 : 307
|
|
789
788
|
);
|
|
790
789
|
}
|
|
791
|
-
${
|
|
790
|
+
${T("decision.path",", decision.language")}${k("decision.type === 'rewrite' ? decision.destination : pathname","decision.path")}
|
|
792
791
|
if (decision.type === 'rewrite') {
|
|
793
792
|
return NextResponse.rewrite(new URL(decision.destination + search, request.url)${l?", { request }":""});
|
|
794
793
|
}
|
|
795
|
-
return NextResponse.next(${
|
|
794
|
+
return NextResponse.next(${_});
|
|
796
795
|
}
|
|
797
|
-
`:
|
|
796
|
+
`:D=`
|
|
798
797
|
/** Redirects and render tree of a page request. */
|
|
799
798
|
function route(${b}): NextResponse {
|
|
800
799
|
const { ${l?"pathname, search":"pathname"} } = request.nextUrl;
|
|
801
800
|
if (!pageRoutes.some((pattern) => pattern.test(pathname))) {
|
|
802
801
|
return NextResponse.next({ request });
|
|
803
802
|
}
|
|
804
|
-
${
|
|
803
|
+
${T("pathname","")}${k("pathname","pathname")}
|
|
805
804
|
return NextResponse.next({ request });
|
|
806
805
|
}
|
|
807
806
|
`;let F;return l?F=`
|
|
@@ -820,17 +819,17 @@ ${g}
|
|
|
820
819
|
// (refresh failed, session revoked): the cached page, with the cleared cookies.
|
|
821
820
|
return auth.apply(route(request, ${i?"auth.session, ":""}auth.session?.user !== null));
|
|
822
821
|
}
|
|
823
|
-
${
|
|
822
|
+
${D}`:F=`
|
|
824
823
|
export function proxy(request: NextRequest) {
|
|
825
824
|
return route(request);
|
|
826
825
|
}
|
|
827
|
-
${
|
|
826
|
+
${D}`,`${v}${E}${M}${te}${A}${U}${F}
|
|
828
827
|
export const config = {
|
|
829
828
|
matcher: [
|
|
830
829
|
${f}
|
|
831
830
|
],
|
|
832
831
|
};
|
|
833
|
-
`},usesCookieSession(){try{let r=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"));if(!{...r.dependencies,...r.devDependencies}["@donotdev/supabase"])return!1;let t=this.pathResolver.resolveAppPath("src/config/providers.ts");return this.pathResolver.pathExists(t)?this.pathResolver.readSync(t).includes("createBrowserClient("):!1}catch(r){return this.logger.debug(`Cookie session detection failed: ${r.message}`),!1}},removeLegacyMiddleware(){for(let r of["middleware.ts","src/middleware.ts"]){let e=this.pathResolver.resolveAppPath(r);try{this.pathResolver.pathExists(e)&&this.pathResolver.readSync(e).startsWith("// Auto-generated middleware by @donotdev/config")&&(this.pathResolver.removeSync(e),this.logger.debug(`Removed legacy generated ${r}`))}catch(t){this.logger.debug(`Could not remove legacy ${r}: ${t.message}`)}}}};function q(r){return r.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function
|
|
832
|
+
`},usesCookieSession(){try{let r=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"));if(!{...r.dependencies,...r.devDependencies}["@donotdev/supabase"])return!1;let t=this.pathResolver.resolveAppPath("src/config/providers.ts");return this.pathResolver.pathExists(t)?this.pathResolver.readSync(t).includes("createBrowserClient("):!1}catch(r){return this.logger.debug(`Cookie session detection failed: ${r.message}`),!1}},removeLegacyMiddleware(){for(let r of["middleware.ts","src/middleware.ts"]){let e=this.pathResolver.resolveAppPath(r);try{this.pathResolver.pathExists(e)&&this.pathResolver.readSync(e).startsWith("// Auto-generated middleware by @donotdev/config")&&(this.pathResolver.removeSync(e),this.logger.debug(`Removed legacy generated ${r}`))}catch(t){this.logger.debug(`Could not remove legacy ${r}: ${t.message}`)}}}};function q(r){return r.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function Bt(r,e){let t=e&&Object.hasOwn(e,r.collection)?e[r.collection]:void 0;if(!t)throw new Error(`[dndev] Route "${r.path}" reads "${r.collection}" records but no read schema was given for that collection (entityReadSchemas of the app's entities).`);return t}async function _r(r,e,t,n){let s=q(r.path),o=s[0];if(s.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 a=Bt(r,n),i;try{i=await e.query(r.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3},a)}catch(c){let u=c?.details?.originalMessage??c?.message??String(c);throw new Error(`[dndev] Route "${r.path}" could not read its public "${r.collection}" records (signed-out visitor: RLS / Security Rules must allow it): ${u}`,{cause:c})}let l=[];for(let c of i.items){let u=c[o];typeof u!="string"&&typeof u!="number"||l.push({param:o,value:String(u),record:c})}return l}async function Ze(r,e,t,n){let s=[];for(let o of r){if(q(o.path).length===0){s.push({route:o,path:o.path});continue}for(let{param:a,value:i,record:l}of await _r(o,e,t,n))s.push({route:o,path:o.path.replace(`:${a}`,encodeURIComponent(i)),record:l})}return s}async function wa(r,e,t,n){return(await _r(r,e,t,n)).map(({param:s,value:o})=>({[s]:o}))}import{createHash as Sa,timingSafeEqual as Ea}from"node:crypto";var Te="DNDEV_REVALIDATE_SECRET",Tr="/api/dndev/revalidate",kr=32,Dr="public",Ra=["/sitemap.xml","/llms.txt"];function $a(r){return r.replace(/[/#?\\]|%(2f|23|3f|5c)/gi,e=>encodeURIComponent(e))}function xa(r,e){return e.languages.length<2?[r]:e.languages.map(t=>`/${t}${r==="/"?"":r}`)}function Or(r,e,t){let n=new Set,s=new Set;for(let o of r){let a=q(o.path);if(a.length===0){n.add(o.path);continue}let[i]=a;if(!(a.length!==1||!i||o.collection!==e.table)){for(let l of[e.record,e.oldRecord]){let c=l?.[i];typeof c!="string"&&typeof c!="number"||n.add(o.path.replace(`:${i}`,$a(String(c))))}for(let l of Ra)s.add(l)}}for(let o of n)for(let a of xa(o,t))s.add(a);return[...s].sort()}function Pa(r,e){let t=/^Bearer (.+)$/.exec(r??"");if(!t)return!1;let n=s=>Sa("sha256").update(s).digest();return Ea(n(t[1]),n(e))}async function Ca(r,{secret:e,routes:t,routing:n,readChange:s,revalidatePath:o}){if(!e||e.length<kr)throw new Error(`[dndev] Set ${Te} to a random secret of at least ${kr} characters: the revalidation webhook (${Tr}) authenticates with it.`);if(!Pa(r.headers.get("authorization"),e))return Response.json({error:"Unauthorized"},{status:401});let a;try{a=s(await r.json())}catch(l){if(!(l instanceof Error))throw l;return Response.json({error:l.message},{status:400})}if(a.schema!==Dr)return Response.json({error:`Table "${a.schema}.${a.table}" is not in the "${Dr}" schema: only public content tables are revalidated.`},{status:400});let i=Or(t,a,n);for(let l of i)o(l);return Response.json({revalidated:i})}var Fr={revalidationRoute(r){if(this.isSessionOnlyRoute(r)||r.path.includes("*"))return null;let e=q(r.path);if(e.length===0)return{path:r.path};let t=r.meta?.entity;return e.length===1&&t?{path:r.path,collection:t}:null},generateRevalidationContent(r){let e=r.routes.map(n=>this.revalidationRoute(n)).filter(Boolean),t={languages:this.options.languages,defaultLanguage:this.options.defaultLanguage};return`// Generated by @donotdev/config - DO NOT EDIT
|
|
834
833
|
// Regenerated on every build from src/pages (PageMeta).
|
|
835
834
|
// On-demand revalidation: a Supabase database webhook POSTs each row change here
|
|
836
835
|
// (Authorization: Bearer $${Te}). The cached pages showing the row (its entity
|
|
@@ -859,7 +858,7 @@ export async function POST(request: Request): Promise<Response> {
|
|
|
859
858
|
revalidatePath,
|
|
860
859
|
});
|
|
861
860
|
}
|
|
862
|
-
`},generateRevalidationRoute(r){this.options.routingMode==="app"&&this.appDependsOn("@donotdev/supabase")&&this.writeGeneratedFile(L.next.revalidateRoute,this.generateRevalidationContent(r),"revalidation route")}};var
|
|
861
|
+
`},generateRevalidationRoute(r){this.options.routingMode==="app"&&this.appDependsOn("@donotdev/supabase")&&this.writeGeneratedFile(L.next.revalidateRoute,this.generateRevalidationContent(r),"revalidation route")}};var Ir={async generateAppRoutes(r){let e=this.generateAppRoutesContent(r.routes);this.writeGeneratedFile("src/app/routes.generated.ts",e,"app routes index")},generateAppRoutesContent(r){let e=r.map(t=>{let n=t.componentName||this.pathToComponentName(t.path),s=t.relativePath||t.file;if(!s)return this.logger.warn(`Route ${t.path} missing file path, skipping`),null;let o=s.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
|
|
863
862
|
path: '${t.path}',
|
|
864
863
|
component: lazy(() => import('${o}')),
|
|
865
864
|
auth: ${JSON.stringify(t.auth)},
|
|
@@ -900,13 +899,13 @@ export const routeManifest = {
|
|
|
900
899
|
};
|
|
901
900
|
|
|
902
901
|
export default pageRoutes;
|
|
903
|
-
`},pathToComponentName(r){return r.split("/").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")+"Page"}};import{existsSync as
|
|
904
|
-
`)){let s=n.indexOf(":");if(s===-1)continue;let o=n.slice(0,s).trim();if(!o)continue;let a=n.slice(s+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[o]=a}return{meta:t,content:r.slice(e[0].length).replace(
|
|
905
|
-
`)}discoverBlogPosts(){return this.appRoot?
|
|
906
|
-
<title><![CDATA[${
|
|
902
|
+
`},pathToComponentName(r){return r.split("/").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")+"Page"}};var Qe=r=>r.split("/").filter(Boolean);function Lr(r){return r==="*"||r.endsWith("/*")}function Aa(r){try{return decodeURIComponent(r)}catch{return r}}function Mr(r,e){let t={};return r.forEach((n,s)=>{n.startsWith(":")&&e[s]!==void 0&&(t[n.slice(1)]=Aa(e[s]))}),t}function Na(r,e){let t=Qe(e),n=t.join("/"),s=r.find(i=>typeof i.path=="string"&&Qe(i.path).join("/")===n);if(s)return{route:s,params:{}};let o=null;for(let i of r){if(typeof i.path!="string"||!i.path.includes(":")||Lr(i.path))continue;let l=Qe(i.path);l.length===t.length&&l.every((c,u)=>c.startsWith(":")||c===t[u])&&(!o||i.path.length>o.route.path.length)&&(o={route:i,pattern:l})}if(o)return{route:o.route,params:Mr(o.pattern,t)};let a=null;for(let i of r){if(typeof i.path!="string"||!Lr(i.path))continue;let l=Qe(i.path).slice(0,-1);if(t.length<l.length)continue;let c=0,u=!0;for(let d=0;d<l.length;d++){let f=l[d];if(!f.startsWith(":")){if(f!==t[d]){u=!1;break}c++}}if(!u)continue;let p=[l.length,c];(!a||p[0]>a.score[0]||p[0]===a.score[0]&&p[1]>a.score[1])&&(a={route:i,prefix:l,score:p})}return a?{route:a.route,params:Mr(a.prefix,t)}:null}function Gt(r){let e=[],t="";for(let n of r.split("/").filter(Boolean))t+=`/${n}`,e.push(t);return e}var Oe=r=>`/${r.split("/").filter(Boolean).join("/")}`,_a=r=>!r.split("/").some(e=>e.startsWith(":")||e==="*");function et(r,e){let t=new Map;for(let i of e)typeof i.path=="string"&&_a(i.path)&&t.set(Oe(i.path),i);let n=(i,l)=>{let c=Gt(i).slice(0,-1),u=c.at(-1),p=u===void 0?void 0:t.get(u);if(p)return p;let d=l?.meta?.parent;if(d!==void 0){if(Oe(d)==="/")return null;let f=t.get(Oe(d));if(!f)throw new Error(`[dndev] ${l?.path}: PageMeta parent ${JSON.stringify(d)} is not a static route path of the app.`);return f}for(let f=c.length-2;f>=0;f--){let h=t.get(c[f]);if(h)return h}return null},s=[],o=new Set([Oe(r)]),a=n(r,Na(e,r)?.route);for(;a;){let i=Oe(a.path);if(o.has(i))throw new Error(`[dndev] PageMeta parent loop: ${[...o,i].join(" \u2192 ")}. Each page needs one parent chain up to home.`);o.add(i),s.unshift(a),a=n(i,a)}return s}import{existsSync as Ta,readdirSync as Oa}from"node:fs";import{join as Fa}from"node:path";var ka=/^---\r?\n([\s\S]*?)\r?\n---/,Da=/^\r?\n/;function Ur(r){let e=r.match(ka);if(!e)return{meta:{},content:r};let t={};for(let n of(e[1]??"").split(`
|
|
903
|
+
`)){let s=n.indexOf(":");if(s===-1)continue;let o=n.slice(0,s).trim();if(!o)continue;let a=n.slice(s+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[o]=a}return{meta:t,content:r.slice(e[0].length).replace(Da,"")}}function jr(r){return r.filter(e=>e.endsWith("_en.md")).sort()}function Br(r){let e=Fa(r,"src","content","blog");try{return Ta(e)?jr(Oa(e)).length>0:!1}catch{return!1}}function Gr(r,e){let t=O.getInstance(),n=t.resolvePath("src/content/blog",r);try{if(!t.pathExists(n))return[];let s=jr(t.readdirSync(n));if(s.length===0)return[];let o=[];for(let a of s){let i=t.resolvePath(a,n),l=t.readSync(i,{format:"text"}),c=a.replace(/_en\.md$/,""),{meta:u}=Ur(l),p=u.date;if(!p)try{p=t.statSync(i).mtime.toISOString().split("T")[0],e.warn(`Blog post "${c}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],e.warn(`Blog post "${c}" has no date and file stat failed, using today`)}o.push({slug:c,title:u.title||c,description:u.description||"",date:p,tags:u.tags?u.tags.split(",").map(d=>d.trim()):[],image:u.image||null})}return o.sort((a,i)=>i.date.localeCompare(a.date)),e.info(`\u{1F4DD} Discovered ${o.length} blog post(s) in src/content/blog/`),o}catch(s){return e.debug(`Blog content discovery skipped: ${s.message}`),[]}}function J(r){return r?r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}function zr(r){return r?r.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var qr=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function Ia(r,e){let t;try{let n=new URL(r);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error;t=n.hostname}catch{throw new Error(`[dndev] SEO: base URL "${r}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(qr.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: deploy build with base URL "${r}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}var La="DNDEV_DEPLOY";function nt(r=process.env){let e=r.CI;return r[La]==="1"||r.VERCEL==="1"||e!==void 0&&e!==""&&e!=="false"&&e!=="0"}var Hr=new Set;function Jr(r,e,t,n=process.env){if(nt(n)){if(!r)throw new Error(`[dndev] SEO: deploy build without ${e}. The sitemap, robots.txt, llms.txt and canonical URLs need the production URL: set ${e} (or seo.baseUrl) in the build environment.`);return Ia(r,e),r}let s=o=>{Hr.has(o)||(Hr.add(o),t.warn(o))};return!r||!Ma(r)?(s(`[dndev] Local build without a usable ${e}${r?` ("${r}")`:""}: no sitemap.xml, llms.txt, robots.txt, rss.xml, canonical URLs or record pages. Set ${e} to build them.`),null):(Ua(r)||s(`[dndev] Local build: sitemap.xml, llms.txt, canonical URLs and record pages carry ${r} (${e}). A deploy build (dndev deploy, Vercel, CI) needs the production URL.`),r)}async function xe(r,e,t,n=process.env){try{return await e(),!0}catch(s){if(ce(s))throw s;let o=`${r.join(", ")} not written: ${s.message}`;if(nt(n))throw x("dndev-seo",`${o}. A deploy build publishes every SEO file.`,"seo-generation-failed",{files:r});return t.warn(`[dndev] Local build: ${o} (a deploy build fails on it).`),!1}}function Ma(r){try{let{protocol:e}=new URL(r);return e==="https:"||e==="http:"}catch{return!1}}function Ua(r){let{hostname:e}=new URL(r);return!qr.has(e)&&!e.endsWith(".localhost")}var zt=Object.freeze(["/api"]),Wr=new Set(["/404","/not-found","/500","/error"]);function rt(r){return r.auth&&r.auth!==!1||Wr.has(r.path)||Wr.has(r.meta?.route)?!1:r.meta?.seo?.noindex!==!0}function qt(r){return typeof r.path=="string"&&r.path.split("/").includes("*")}function Vr(r){if(!(typeof r.path!="string"||!r.path.includes(":"))&&rt(r))return r.meta?.entity||void 0}function st(r){if(typeof r.path!="string"||r.path.includes("*")||q(r.path).length!==1)return null;let e=Vr(r);return e?{path:r.path,collection:e}:null}function ja(r=[]){return{totalRoutes:r.length,publicRoutes:r.filter(e=>!e.auth||e.auth===!1).length,protectedRoutes:r.filter(e=>e.auth&&e.auth.required).length}}var tt=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:n=!0,baseUrl:s,siteName:o,crawlDelay:a=1,aiCrawlers:i="recommended",routes:l={},...c}=e;if(!s||!o)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:n,baseUrl:s,siteName:o,crawlDelay:a,aiCrawlers:i,routes:l,blogPath:"/blog",...c},this.appRoot=c.appRoot||null,this.logger=ae("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,n){let s={routes:e.routes||[],baseUrl:this.options.baseUrl,siteName:this.options.siteName},o={robotsTxt:null,rss:null,manifest:null};return this.options.generateRobotsTxt&&(o.robotsTxt=await this.generateRobotsTxt(s,t)),n.length>0&&(o.rss=await this.generateRSSFeed(n,t)),o.manifest=await this.generateManifest(s,t),o}async generateRobotsTxt(e,t){let n=this.options.shellPath?[...zt,this.options.shellPath]:zt,s=this.generateRobotsTxtContent({disallowedPaths:n,sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",s),{fileName:"robots.txt",content:s,disallowedPaths:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:n}=this.options,s=[];for(let o of e||[]){if(!rt(o)||typeof o.path!="string"||qt(o))continue;let a=o.path===n||o.path.startsWith(`${n}/`);if(!(t.length>0&&a))if(o.path.includes(":")){if(a)continue;let i=Vr(o);s.push({path:o.path,...i&&{collection:i}})}else s.push({path:o.path})}if(t.length>0){s.push({path:n,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let o of t)s.push({path:`${n}/${o.slug}`,priority:.6,changeFrequency:"monthly",...o.date&&{lastModified:o.date}})}return s}async generateManifest(e,t){let n={...ja(e.routes),baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()},s=JSON.stringify(n,null,2);return await t("seo-manifest.json",s),{fileName:"seo-manifest.json",content:s,manifest:n}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:n=zt,sitemap:s,crawlDelay:o}=e,a=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...n.map(c=>`Disallow: ${a(c)}`),...t.map(c=>`Allow: ${a(c)}`)];o&&i.push(`Crawl-delay: ${o}`),s&&i.push(`Sitemap: ${s}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Ba(l))),i.join(`
|
|
904
|
+
`)}discoverBlogPosts(){return this.appRoot?Gr(this.appRoot,this.logger):[]}async generateRSSFeed(e,t){let n=e.map(o=>` <item>
|
|
905
|
+
<title><![CDATA[${zr(o.title)}]]></title>
|
|
907
906
|
<link>${J(this.options.baseUrl)}${J(this.options.blogPath)}/${J(o.slug)}</link>
|
|
908
907
|
<guid>${J(this.options.baseUrl)}${J(this.options.blogPath)}/${J(o.slug)}</guid>
|
|
909
|
-
<description><![CDATA[${
|
|
908
|
+
<description><![CDATA[${zr(o.description)}]]></description>
|
|
910
909
|
<pubDate>${o.date?new Date(o.date).toUTCString():""}</pubDate>${o.tags.length?`
|
|
911
910
|
<category>${J(o.tags.join(", "))}</category>`:""}${o.image?`
|
|
912
911
|
<enclosure url="${J(this.options.baseUrl)}${J(o.image)}" type="image/png" length="0"/>`:""}
|
|
@@ -921,7 +920,7 @@ export default pageRoutes;
|
|
|
921
920
|
<atom:link href="${J(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
922
921
|
${n}
|
|
923
922
|
</channel>
|
|
924
|
-
</rss>`;return await t("rss.xml",s),{fileName:"rss.xml",content:s,postCount:e.length}}},
|
|
923
|
+
</rss>`;return await t("rss.xml",s),{fileName:"rss.xml",content:s,postCount:e.length}}},Ht=["GPTBot","Google-Extended","CCBot","ClaudeBot"],Wt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Ba(r){let e=["# AI Crawler Management"];if(r==="block-all"){for(let t of[...Ht,...Wt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(r==="allow-all"){for(let t of[...Ht,...Wt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of Ht)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of Wt)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Ga(r,e){return[...et(r.path,e),r].map(({path:t,meta:n={}})=>({path:t,meta:{...n.namespace&&{namespace:n.namespace},...n.seo&&{seo:n.seo},...n.parent&&{parent:n.parent}}}))}var Kr={prerendersRecords(){let r=this.options.prerenderRecords??!0;if(typeof r=="boolean")return r;throw new Error(`appConfig.prerenderRecords must be true or false. Got ${JSON.stringify(r)}.`)},prerenderedRecordsRoute(r){return this.prerendersRecords()?st(r):null},serverMetadataSource(r){return r.exportsGenerateMetadata?"page":this.isBlogPostRoute(r)?"blog":st(r)?"entity":null},entityMetadataRoute(r){return this.serverMetadataSource(r)==="entity"?st(r):null},assertServerMetadata(r){for(let e of r){if(e.exportsGenerateMetadata){if(this.isBlogPostRoute(e))throw new Error(`[dndev] ${e.file} exports \`generateMetadata\`, but blog post pages get theirs generated from the post's frontmatter (a second one would conflict). Remove it from the page.`);if(this.isClientComponent(e.file))throw new Error(`[dndev] ${e.file} exports \`generateMetadata\` but is a client module ('use client'). Next reads generateMetadata only from server modules, so the page would ship without its title and description. Keep the page module a server component (no 'use client') that exports generateMetadata and renders a 'use client' component, or remove generateMetadata.`);continue}let t=this.entityMetadataRoute(e);if(t){if(!this.appDependsOn("entities"))throw new Error(`[dndev] ${e.path} is an entity page ("${t.collection}" records): its metadata derives from the entity definition, but the app does not depend on an \`entities\` package. Add the entity to the app's \`entities\` package, mark the page \`seo: { noindex: true }\`, or export \`generateMetadata\` from a server page module.`);this.entityMetadataExport(e,this.entityPageReader(e,"site"),r)}}},entityPageReader(r,e){let t=e==="site"?this.prerenderedRecordsRoute(r):null,n=this.entityMetadataRoute(r),s=n??t;if(!s)return{imports:"",setup:"",expr:null,schemas:null,named:{}};let o=[n&&"entity pages read their record on the server (metadata, JSON-LD, 404)",t&&"entity pages prerender their published records at build"].filter(Boolean).join("; "),a=n?"Mark the page `seo: { noindex: true }`, or export `generateMetadata` from a server page module and set `appConfig.prerenderRecords: false`.":"Set `appConfig.prerenderRecords: false` to render them on their first request.";return this.serverCrudReader([s],o,a)},staticParamsExport(r,e){if(!this.convertRouteToAppPath(r.path).includes("["))return{named:{},code:""};let t=this.prerenderedRecordsRoute(r);return t?{named:{"@donotdev/core/next":["listStaticParams"]},code:`
|
|
925
924
|
// Every published "${t.collection}" record is prerendered at build (the sitemap's records,
|
|
926
925
|
// public reader). A record published later renders on its first request. All are cached
|
|
927
926
|
// like the static pages (ISR). Opt out: appConfig.prerenderRecords = false.
|
|
@@ -933,24 +932,28 @@ export async function generateStaticParams() {
|
|
|
933
932
|
export function generateStaticParams() {
|
|
934
933
|
return [];
|
|
935
934
|
}
|
|
936
|
-
`}},entityMetadataExport(r,e){let
|
|
935
|
+
`}},entityMetadataExport(r,e,t){let n=this.entityMetadataRoute(r);if(!n)return null;if(!Array.isArray(t))throw new Error(`Route handler: ${r.path} is an entity page; its BreadcrumbList needs the discovered routes`);let{defaultLanguage:s,languages:o}=this.options;if(!s)throw new Error("Route handler: languages not set before page generation (runDiscoveries calls useLanguages)");let[a]=q(n.path),i=this.isMultilingual(),l=r.meta?.seo?.type??"website",c=this.calculateRelativeImportPath("src/config/dndev-config-i18n.js",r.path),u=this.options.siteName;if(!u)throw new Error(`[dndev] ${r.path}: entity page titles end with the site name. Set appConfig.app.name (or appConfig.seo.siteName).`);return{vendorImports:`import type { Metadata } from 'next';
|
|
937
936
|
import { notFound } from 'next/navigation';
|
|
938
937
|
import { cache } from 'react';
|
|
939
|
-
`,named:{"@donotdev/core/server":["buildBreadcrumbJsonLd","buildProductJsonLd","deriveEntitySeo","languageUrl"],"@donotdev/core/next":["appBaseUrl","entityPageSeo","jsonLdScript","readEntityPageRecord"],"@donotdev/core/rsc":["useTranslation"]},typeImports:`import type { LanguageRouting } from '@donotdev/core/server';
|
|
938
|
+
`,named:{"@donotdev/core/server":["buildBreadcrumbJsonLd","buildProductJsonLd","deriveEntitySeo","languageUrl"],"@donotdev/core/next":["appBaseUrl","entityPageSeo","jsonLdScript","readEntityPageRecord"],"@donotdev/core/rsc":["useTranslation"]},typeImports:`import type { BreadcrumbRoute, LanguageRouting } from '@donotdev/core/server';
|
|
940
939
|
`,appImports:`// Server graph: the translations the server useTranslation reads
|
|
941
|
-
import '${
|
|
940
|
+
import '${c}';
|
|
942
941
|
`,code:`
|
|
943
|
-
// Page identity from the "${
|
|
944
|
-
// description, Open Graph, Twitter card, ${
|
|
942
|
+
// Page identity from the "${n.collection}" record of this URL (server, no app code): title,
|
|
943
|
+
// description, Open Graph, Twitter card, ${l==="product"?"Product JSON-LD, ":""}in the URL's language. Canonical, og:url
|
|
945
944
|
// and hreflang come from AutoMetaTags. No public record (missing, hidden status): HTTP 404.
|
|
946
|
-
const ROUTE = ${JSON.stringify(
|
|
945
|
+
const ROUTE = ${JSON.stringify(n)};
|
|
947
946
|
|
|
948
|
-
|
|
947
|
+
// BreadcrumbList: home, the page's ancestors (URL prefixes that are routes, PageMeta parent)
|
|
948
|
+
// named by their titles, the record title last
|
|
949
|
+
const BREADCRUMB_ROUTES: BreadcrumbRoute[] = ${JSON.stringify(Ga(r,t))};
|
|
950
|
+
|
|
951
|
+
const LANGUAGE_ROUTING: LanguageRouting = ${JSON.stringify({languages:o,defaultLanguage:s})};
|
|
949
952
|
|
|
950
953
|
// next.config trailingSlash: page URLs end with \`/\` when true
|
|
951
954
|
const TRAILING_SLASH = ${JSON.stringify(this.options.trailingSlash)};
|
|
952
955
|
|
|
953
|
-
type Params = Promise<{ ${
|
|
956
|
+
type Params = Promise<{ ${i?"lang: string; ":""}${a}: string }>;
|
|
954
957
|
|
|
955
958
|
// One read per request: generateMetadata and the page share it (React cache)
|
|
956
959
|
const pageSeo = cache(async (language: string, value: string) => {
|
|
@@ -965,20 +968,22 @@ const pageSeo = cache(async (language: string, value: string) => {
|
|
|
965
968
|
trailingSlash: TRAILING_SLASH,
|
|
966
969
|
siteName: ${JSON.stringify(u)},
|
|
967
970
|
defaultImage: ${JSON.stringify(this.defaultImage())},
|
|
968
|
-
type: ${JSON.stringify(
|
|
971
|
+
type: ${JSON.stringify(l)},
|
|
969
972
|
entities,
|
|
970
973
|
translate: (namespaces) => useTranslation(namespaces, { language }).t,
|
|
971
974
|
deriveEntitySeo,
|
|
972
975
|
buildProductJsonLd,
|
|
973
976
|
languageUrl,
|
|
974
977
|
buildBreadcrumbJsonLd,
|
|
978
|
+
routes: BREADCRUMB_ROUTES,
|
|
979
|
+
defaultNamespace: ${JSON.stringify(this.defaultNamespace())},
|
|
975
980
|
});
|
|
976
981
|
});
|
|
977
982
|
|
|
978
983
|
/** The URL's page identity; \`notFound()\` (HTTP 404) when no public record matches. */
|
|
979
984
|
async function requireSeo(params: Params) {
|
|
980
|
-
const { ${
|
|
981
|
-
const seo = await pageSeo(${
|
|
985
|
+
const { ${i?"lang, ":""}${a} } = await params;
|
|
986
|
+
const seo = await pageSeo(${i?"lang":JSON.stringify(s)}, ${a});
|
|
982
987
|
if (!seo) notFound();
|
|
983
988
|
return seo;
|
|
984
989
|
}
|
|
@@ -1004,9 +1009,9 @@ export async function generateMetadata({ params }: { params: Params }): Promise<
|
|
|
1004
1009
|
/>
|
|
1005
1010
|
)}
|
|
1006
1011
|
</>
|
|
1007
|
-
);`}}};var
|
|
1012
|
+
);`}}};var za=/^[A-Za-z_$][\w$]*$/,Ha=/^(?:'[^'\\]*'|"[^"\\]*"|`[^`\\$]*`|-?\d[\w.]*|null|undefined|true|false)$/;function Wa(r,e){let t=0;for(let n=e;n<r.length;n++){let s=r[n];if(s==="'"||s==='"'||s==="`"){for(n++;n<r.length&&r[n]!==s;n++)r[n]==="\\"&&n++;continue}if(t===0&&(s===","||s==="/"&&/[/*]/.test(r[n+1]??"")))return n;if("([{".includes(s))t++;else if(")]}".includes(s)){if(t===0)return n;t--}}return r.length}function qa(r){let e=/(^|[{,\s])entity\s*:\s*/gm,t="",n=0,s;for(;s=e.exec(r);){let o=s.index+s[0].length,a=Wa(r,o),i=r.slice(o,a).trimEnd();if(!i)continue;let l=Ha.test(i)?i:za.test(i)?`{ identifier: '${i}' }`:`{ expression: ${JSON.stringify(i)} }`;t+=r.slice(n,o)+l,n=o+i.length,e.lastIndex=n}return t+r.slice(n)}function Ja(r){let e=r instanceof Error?r.message:String(r),t=/^(\S+) is not defined$/.exec(e)?.[1];return t?`\`${t}\` is not a literal value (an import, a variable or a call)`:`it is not a plain object literal (${e})`}function Yr(r,e="unknown"){let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,n=r.match(t);if(!n)return null;let s=n[1];s=s.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,l)=>`icon: '${l}'`),s=qa(s);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;[...r.matchAll(o)].forEach(i=>{let l=i[1],c=i[2];s=s.replace(new RegExp(`\\b${l}\\b`,"g"),`'${c}'`)});try{return Function(`return ${s}`)()}catch(i){throw x("dndev-routes",`${e}: PageMeta cannot be read at build: ${Ja(i)}. Without it the page would lose its route, auth and seo. The build reads PageMeta statically: write every value as a literal in the object (strings, numbers, booleans, null, arrays and objects of those, icon: <Icon />, a string constant declared in the page file: const NAMESPACE = 'home'), except entity, the defineEntity identifier imported from 'entities'. Example: auth: { required: true, role: 'admin' } instead of auth: ADMIN_ONLY.`,"invalid-configuration")}}function Xr(r){return/^[ \t]*export\s+(?:(?:async\s+)?function\s*\*?\s*generateMetadata\b|(?:const|let)\s+generateMetadata\b|\{[^}]*\bgenerateMetadata\b[^}]*\})/m.test(r)}var Pe=null,Zr=null;function Va(r){let t=(r.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Ka(r){let e=r.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw x("dndev-routes",`${r.file}: PageMeta signedInRedirect must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`,"invalid-configuration");if(e.split(/[?#]/)[0]===r.path)throw x("dndev-routes",`${r.file}: PageMeta signedInRedirect points at the page itself (${e}): signed-in visitors would loop. Use another page.`,"invalid-configuration")}}function Ya(r,e){let t=r.meta?.parent;if(t===void 0)return;let n=o=>{throw x("dndev-routes",`${r.file}: PageMeta parent ${JSON.stringify(t)} ${o}`,"invalid-configuration")};(typeof t!="string"||!t.startsWith("/")||t.startsWith("//")||/[\\?#*:]/.test(t))&&n("must be the static path of one of the app's pages, starting with '/' (no :param, *, query or hash). Example: export const meta: PageMeta = { parent: '/catalogue' };"),e.some(o=>o.path===t)||n(`is not the path of a page of the app. Use the path of an existing page, e.g. one of: ${e.map(o=>o.path).filter(o=>!/[:*]/.test(o)).slice(0,8).join(", ")}.`),t===r.path&&n("is the page itself. Name the page its visitors come from.");let s=Gt(r.path).slice(0,-1).at(-1);s&&e.some(o=>o.path===s)&&n(`is never used: the URL prefix ${s} is a page, so it is the parent. Remove parent.`)}function Xa(r){for(let e of r)try{et(e.path,r)}catch(t){throw x("dndev-routes",`${e.file}: ${t.message.replace(/^\[dndev\] /,"")} Fix the PageMeta parent of one of these pages.`,"invalid-configuration")}}function Za(r,{pageGenerateMetadata:e=!1}={}){if(!r.path.split("/").some(n=>n.startsWith(":"))||qt(r)||!rt(r)||r.meta?.entity||r.metaExport?.namespace==="blog"||e&&r.exportsGenerateMetadata)return;let t=["declare the record entity it shows: import { productEntity } from 'entities'; then entity: productEntity in its PageMeta (title, description and image from the record)",...e?["export Next's generateMetadata from the page module (a server module, no 'use client')"]:[],"keep it out of search engines: seo: { noindex: true } in its PageMeta"];throw x("dndev-routes",`${r.file}: public dynamic route ${r.path} has no per-URL SEO: every URL would get the same title and description (PageMeta + i18n), duplicate pages for search engines. Fix, one of:
|
|
1008
1013
|
`+t.map((n,s)=>` ${s+1}. ${n}`).join(`
|
|
1009
|
-
`),"invalid-configuration")}var
|
|
1014
|
+
`),"invalid-configuration")}var Ce=class extends ee{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),n=process.env.DNDEV_BUILD_ID;if(Pe&&Zr===n)return this.logger.debug("Using cached route discovery results"),this.routes=Pe.routes,this.errors=Pe.errors,this.source=Pe.source,this.entityResolver=Pe.entityResolver,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let s=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${s} files in ${t}`);let o=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(o)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),Pe={routes:this.routes,errors:this.errors,source:this.source,entityResolver:this.entityResolver},Zr=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}getEntityResolver(){return this.entityResolver??=ke(this.pathResolver.getAppRoot()),this.entityResolver}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:n}=e;this.entityResolver=ke(t);let s=await this._batchProcessFiles(n,c=>this._analyzePageFile(c,t)),o=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(o,c=>this._analyzePageFile(c,t)),i=[...s,...a];this.logger.debug(`Auto-discovering from ${n.length} app + ${o.length} additional files`),this.routes=i.filter(c=>c.path==="home"||c.path==="/home"?(this.logger.debug(`Filtered reserved route: ${c.path} - Use root "/" instead (${c.file})`),!1):!0);let l=new Map;for(let c of this.routes){let u=c.path;if(l.has(u)){let p=l.get(u);throw x("dndev-routes",`${c.file}: route ${u} is also the route of ${p.file}: two pages cannot share a URL. Give one of them another path with a PageMeta route override, e.g. export const meta: PageMeta = { route: '/custom-path' };`,"invalid-configuration")}l.set(u,c),Ka(c),Za(c,{pageGenerateMetadata:this.options.pageGenerateMetadata===!0})}for(let c of this.routes)Ya(c,this.routes);Xa(this.routes),this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${n.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(n=>this.pathResolver.resolveAppPath(n));if(t.length===0)return[];try{let{consumerFiles:n}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return n}catch(n){return this.logger.debug(`Error scanning additional patterns: ${n.message}`),[]}}async _analyzePageFile(e,t){let n=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!n)return null;let s=e.relativePath,o="/src/"+s.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(n,s),i=Va(o),c=i===Ne.HOMEPAGE_COMPONENT?Ne.HOMEPAGE_PATH:this._resolveRoutePath(a,s,e.absolutePath),u=this._extractPageMeta(s),p=await er(a,n,s,this.entityResolver),{entity:d,action:f,...h}=a||{};return{path:c,component:i,importPath:o,auth:a?.auth||!1,meta:{...u,...h,...p&&{entity:p},action:u.action},metaExport:a&&{...a,...p&&{entity:p}},exportsGenerateMetadata:Xr(n),file:s}}_extractMetaExport(e,t){try{let n=Yr(e,t);return n?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(n)}`),n):null}catch(n){if(ce(n))throw n;return this.logger.debug(`Error parsing meta export from ${t}: ${n.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,n){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let s=e.route.trim();return s==="/"?"/":(s=s.replace(/\/+/g,"/"),s.startsWith("/")||(s="/"+s),s)}if(typeof e.route=="object"&&e.route!==null){let s=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let a=o.map(i=>`:${i}`).join("/");return`${s}/${a}`}return s}return this.logger.warn(`Invalid route format in ${n}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${n}`),this._generateRoutePath(t)}_extractPageMeta(e){let t=e.split("/").pop()?.replace(".tsx","")||"",n=t.replace(/Page$/,"");n=n.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),n=n.charAt(0).toUpperCase()+n.slice(1);let s=e.split("/"),o=null;return s.length>1&&(t.includes("List")?o="list":t.includes("Form")||t.includes("Create")||t.includes("Edit")?o="form":(t.includes("Detail")||t.includes("View"))&&(o="detail")),{title:n,action:o,file:e}}};var ot=class extends H{constructor(e={}){super(Ce,e),this.rendersSessionTree=!1,this.appRouteSegments=[],this.i18n=null,this.fonts=null}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,proxyPath:L.next.proxy,manifestPath:L.next.routeManifest,languages:[],defaultLanguage:null,trailingSlash:!1,siteName:null,defaultImage:void 0,defaultNamespace:void 0}}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}useI18n(e){this.i18n=e}useFonts(e){this.fonts=e}isMultilingual(){return this.options.languages.length>1}defaultImage(){return this.options.defaultImage||Se}defaultNamespace(){return this.options.defaultNamespace||"home"}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 n=e.split("/").filter(Boolean).length;return n===0?`./${t}`:`${"../".repeat(n)}${t}`}createDiscovery(e){return new e(this.pathResolver,{...this.options,...At})}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],n=t.filter(o=>o.auth&&o.auth.required).length,s=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${s} found${n>0?`, ${n} are authguarded`:""}`)}getEntityResolver(){return this.discovery.getEntityResolver()}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}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||[];this.options.generateAppPages&&this.assertServerMetadata(t);let n={totalRoutes:t.length,authRequired:t.filter(s=>s.auth&&s.auth.required).length,publicRoutes:t.filter(s=>!s.auth||s.auth===!1).length,source:e.source,hasBlogFeed:Br(this.pathResolver.getAppRoot()),trailingSlash:this.options.trailingSlash,serverMetadataPaths:this.options.generateAppPages?t.filter(s=>this.serverMetadataSource(s)).map(s=>s.path):[],recordBreadcrumbPaths:this.options.generateAppPages?t.filter(s=>this.entityMetadataRoute(s)).map(s=>s.path):[],generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
1010
1015
|
// Generated at: ${new Date().toISOString()}
|
|
1011
1016
|
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
1012
1017
|
|
|
@@ -1025,7 +1030,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1025
1030
|
timestamp: Date.now(),
|
|
1026
1031
|
};
|
|
1027
1032
|
}
|
|
1028
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1033
|
+
globalThis._DNDEV_CONFIG_.${X.routes} = {
|
|
1029
1034
|
mapping: routeMapping,
|
|
1030
1035
|
manifest: routeManifest,
|
|
1031
1036
|
};
|
|
@@ -1035,34 +1040,34 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1035
1040
|
export const routes = routeMapping;
|
|
1036
1041
|
export const manifest = routeManifest;
|
|
1037
1042
|
export default { routes: routeMapping, manifest: routeManifest };
|
|
1038
|
-
`}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.generateRevalidationRoute(e)),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e)}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 s of t)await this.generateTreeLayout(s);let n=0;for(let s of e.routes){let o=this.isSessionOnlyRoute(s)?"session":"site",a=await this.generateSingleAppPage(s,o);a&&n++,a&&o==="site"&&this.rendersSessionTree&&this.generateSessionPage(s)}this.logger.debug(`Successfully generated ${n}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}isSessionOnlyRoute(e){return this.rendersSessionTree&&!!this.normalizeAuth(e.auth)}generateSessionPage(e){let t=this.appDirFor(e.path,"session"),s=`${"../".repeat(t.split("/").filter(Boolean).length)}${this.appDirFor(e.path).slice(1)}/${
|
|
1043
|
+
`}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.generateRevalidationRoute(e)),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e)}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 s of t)await this.generateTreeLayout(s);let n=0;for(let s of e.routes){let o=this.isSessionOnlyRoute(s)?"session":"site",a=await this.generateSingleAppPage(s,o,e.routes);a&&n++,a&&o==="site"&&this.rendersSessionTree&&this.generateSessionPage(s)}this.logger.debug(`Successfully generated ${n}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}isSessionOnlyRoute(e){return this.rendersSessionTree&&!!this.normalizeAuth(e.auth)}generateSessionPage(e){let t=this.appDirFor(e.path,"session"),s=`${"../".repeat(t.split("/").filter(Boolean).length)}${this.appDirFor(e.path).slice(1)}/${j("page","tsx").replace(/\.tsx$/,"")}`,o=["default"];this.serverMetadataSource(e)&&o.push("generateMetadata"),this.writeGeneratedFile(`src/app${t}/${j("page","tsx")}`,`// Generated by @donotdev/config - DO NOT EDIT
|
|
1039
1044
|
// Per-request render of ${e.path} (visitors with an auth cookie): same page as the cached one.
|
|
1040
1045
|
|
|
1041
1046
|
export { ${o.join(", ")} } from '${s}';
|
|
1042
|
-
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${
|
|
1043
|
-
`:"",
|
|
1044
|
-
`).join(""),
|
|
1047
|
+
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${j("page","tsx")}`,`src/app/**/${j("layout","tsx")}`,`src/app/**/${j("not-found","tsx")}`,`src/app/${j("global-not-found","tsx")}`,"src/app/**/*PageClient.tsx"],n=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),s=0;for(let o of n)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),s++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(a){this.logger.debug(`Could not clean file ${o}: ${a.message}`)}s>0&&this.logger.debug(`Cleaned ${s} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e,t,n){try{let s=this.appDirFor(e.path,t),o=`src/app${s}/${j("page","tsx")}`,a=this.pathResolver.resolveAppPath(o);if(this.pathResolver.pathExists(a)&&!await this.hasGenerationMarker(a))return this.logger.debug(`Skipping ${o} - user-created file detected (no generation marker)`),!1;let i={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},l=this.generatePageFileContent(i,t,n);this.writeGeneratedFile(o,l,`app page: ${s}`);let c=this.extractComponentName(i.filePath),u=this.calculateRelativeImportPath(i.relativePath,i.path);return this.isBlogPostRoute(i)?this.writeGeneratedFile(`src/app${s}/BlogPostClient.tsx`,this.generateBlogPostClientContent(c,u),`app blog client: ${s}`):this.isClientComponent(i.filePath)&&this.writeGeneratedFile(`src/app${s}/${c}Client.tsx`,this.generateMountedClientContent(c,u),`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===Ne.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(n=>n.startsWith(":")?`[${n.slice(1)}]`:n==="*"?"[...slug]":n).join("/")}generatePageFileContent(e,t="site",n){let s=this.extractComponentName(e.filePath),o=e.relativePath||e.file,a=this.calculateRelativeImportPath(o,e.path);if(this.isBlogPostRoute(e))return this.generateBlogPostRSCContent(e,s,a);let i=this.isClientComponent(e.filePath),l=this.normalizeAuth(e.auth)?e.auth:null,c=e.meta?.signedInRedirect??null,u=[...l?["AuthGuard"]:[],...c?["SignedInRedirect"]:[]],p=u.length?`import { ${u.join(", ")} } from '@donotdev/ui';
|
|
1048
|
+
`:"",d=this.entityPageReader(e,t),f=t==="site"?this.staticParamsExport(e,d):{named:{},code:""},h=this.entityMetadataExport(e,d,n),m={"@donotdev/core/server":d.expr?["HIDDEN_STATUSES"]:[],"@donotdev/core/next":[],"@donotdev/core/rsc":[]};for(let E of[f.named,h?.named??{},d.named])for(let[A,U]of Object.entries(E))m[A].push(...U);let y=Object.entries(m).filter(([,E])=>E.length>0).map(([E,A])=>`import { ${A.join(", ")} } from '${E}';
|
|
1049
|
+
`).join(""),S=this.serverMetadataSource(e)==="page"?`
|
|
1045
1050
|
// The page module's own Next metadata
|
|
1046
|
-
export { generateMetadata } from '${
|
|
1047
|
-
`:"",
|
|
1051
|
+
export { generateMetadata } from '${a}';
|
|
1052
|
+
`:"",_=E=>{let A=c?`<SignedInRedirect to={${JSON.stringify(c)}}>${E}</SignedInRedirect>`:E;return l?`<AuthGuard auth={${JSON.stringify(l===!0?{required:!0}:l)}}>${A}</AuthGuard>`:A},P=i?`import ${s}Client from './${s}Client';`:`import ${s} from '${a}';`,v=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1048
1053
|
// This file will be regenerated when src/pages changes
|
|
1049
1054
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
1050
1055
|
|
|
1051
|
-
${
|
|
1052
|
-
${
|
|
1053
|
-
export default async function ${
|
|
1054
|
-
${
|
|
1056
|
+
${h?.vendorImports??""}${y}${h?.typeImports??""}${p}${d.imports}${h?.appImports??""}${P}
|
|
1057
|
+
${d.setup}${f.code}${h?h.code:""}${S}`;if(h){let E=i?`<${s}Client />`:`<${s} {...props} />`;return`${v}
|
|
1058
|
+
export default async function ${s}Route(props: { params: Params }) {
|
|
1059
|
+
${h.render.replace("{PAGE}",_(E))}
|
|
1055
1060
|
}
|
|
1056
|
-
`}return
|
|
1057
|
-
export default function ${
|
|
1058
|
-
return ${
|
|
1061
|
+
`}return i?`${v}
|
|
1062
|
+
export default function ${s}Route() {
|
|
1063
|
+
return ${_(`<${s}Client />`)};
|
|
1059
1064
|
}
|
|
1060
|
-
`:u.length?`${
|
|
1061
|
-
export default function ${
|
|
1062
|
-
return ${
|
|
1065
|
+
`:u.length?`${v}
|
|
1066
|
+
export default function ${s}Route(props: Record<string, unknown>) {
|
|
1067
|
+
return ${_(`<${s} {...props} />`)};
|
|
1063
1068
|
}
|
|
1064
|
-
`:`${
|
|
1065
|
-
export default ${
|
|
1069
|
+
`:`${v}
|
|
1070
|
+
export default ${s};
|
|
1066
1071
|
`}extractComponentName(e){let n=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return n.charAt(0).toUpperCase()+n.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}}normalizeAuth(e){return e===!0?{}:!e||typeof e!="object"||!e.required&&!e.role&&!e.tier?null:{role:e.role,tier:e.tier}}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let s=e.replace(/\.tsx$/,"").replace(/^src\//,""),o=this.appDirFor(t).split("/").filter(Boolean).length;return`${"../".repeat(o+1)}${s}`}hasDynamicSegment(e){return e.includes(":")||e.includes("[")}generateMountedClientContent(e,t){return this.options.ssr?`// Generated by @donotdev/config - DO NOT EDIT
|
|
1067
1072
|
// This file will be regenerated when src/pages changes
|
|
1068
1073
|
'use client';
|
|
@@ -1091,20 +1096,20 @@ export default function ${e}Client() {
|
|
|
1091
1096
|
return <${e} />;
|
|
1092
1097
|
}
|
|
1093
1098
|
`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let n=this.pathResolver.readSync(t);return n?n.split(`
|
|
1094
|
-
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};Object.assign(
|
|
1095
|
-
`];r.description&&
|
|
1096
|
-
`);for(let
|
|
1097
|
-
`),
|
|
1098
|
-
`),
|
|
1099
|
-
`),
|
|
1100
|
-
`)}function
|
|
1099
|
+
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};Object.assign(ot.prototype,wr,Ar,Nr,Ir,Kr,Fr,Sr);function Qr(r={}){return new ot(r)}var Qa="dndev",ei="crud",ti="entity-";function es(r,e,t){return e?r?.[e]?.[t]:void 0}function pe(r){return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function ts(r){return r?.metaExport||r?.meta||{}}function ni(r,{siteName:e,defaultNamespace:t,t:n}){let s=ts(r),{title:o,pageTitle:a}=jt({meta:s,ns:s.namespace||null,defaultNs:t,t:n,siteName:e});return a??o}function ri(r,e,t){let n=ts(r),s=n.seo||{};if(s.description===null)return;let o=es(e,n.namespace,t);return pe(s.description)??pe(o?.description)}function ns(r){let{siteName:e,description:t,baseUrl:n,sitemapRoutes:s,routes:o,blogPosts:a=[],blogPath:i="/blog",translations:l,language:c,defaultNamespace:u}=r,p=es(l,Qa,c)?.seo,d=pe(p?.llmsPages),f=pe(p?.llmsBlog);if(!d||!f)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${c}".`);if(!u)throw new Error('[dndev] llms.txt: getLlmsTxtSource needs options.defaultNamespace (appConfig.seo.defaultNamespace, else "home").');let h=new Map(o.map(v=>[v.path,v])),m={siteName:e,defaultNamespace:u,t:Xe(Object.fromEntries(Object.entries(l||{}).map(([v,E])=>[v,E?.[c]])))},y=new Map(a.map(v=>[`${i}/${v.slug}`,v])),S=s.map(({path:v,collection:E})=>{let A=y.get(v);if(A)return{path:v,title:A.title,...pe(A.description)&&{description:pe(A.description)},section:f};if(E)return{path:v,collection:E};let U=h.get(v);if(!U&&v===i)return{path:v,title:f};let M=ri(U,l,c);return{path:v,title:ni(U,m),...M&&{description:M}}}),_={},P={};for(let[v,E]of Object.entries(l||{})){if(v===ei&&E?.[c]&&(P[v]=E[c]),!v.startsWith(ti))continue;E?.[c]&&(P[v]=E[c]);let A=pe(E?.[c]?.namePlural);A&&(_[v]=A)}return{name:e,...pe(t)&&{summary:pe(t)},baseUrl:n,pagesHeading:d,routes:S,entityHeadings:_,language:c,translations:P}}function rs(r={}){let{siteName:e,baseUrl:t,blogPosts:n=[],blogPath:s="/blog",appRoot:o,logger:a}=r;if(!e||!t)return null;if(n.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=O.getInstance(),l=o?i.resolvePath("src/content/blog",o):null;if(!l||!i.pathExists(l))return null;let c=[`# ${e}
|
|
1100
|
+
`];r.description&&c.push(`> ${r.description}
|
|
1101
|
+
`);for(let u of n){let p=i.resolvePath(`${u.slug}_en.md`,l);try{let d=i.readSync(p,{format:"text"});if(!d)continue;let f=d.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),h=`${t}${s}/${u.slug}`;c.push(`## ${u.title}
|
|
1102
|
+
`),c.push(`Source: ${h}
|
|
1103
|
+
`),u.date&&c.push(`Date: ${u.date}
|
|
1104
|
+
`),c.push(f.trim()),c.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${u.slug}`)}}return c.join(`
|
|
1105
|
+
`)}function Jt(r){let e=(r??"").trim().replace(/\/+$/,"");return e?/^https?:\/\//i.test(e)?e:`https://${e}`:null}function si(r){let e=Jt(r);if(!e)throw new Error("[dndev] Set NEXT_PUBLIC_APP_URL: the sitemap and llms.txt publish absolute URLs.");return e}var ss=`src/app/sitemap.xml/${j("route","ts")}`,os=`src/app/llms.txt/${j("route","ts")}`;function as(r){let e=r.filter(s=>s.path.includes(":")),t=`${r.length-e.length} static + ${e.length} dynamic`;if(e.length===0)return t;let n=e.map(s=>`${s.path} \u2192 ${s.collection??"no collection"}`);return`${t} (${n.join(", ")})`}function at(r,e,t){return`import { ${[...e,...t.named[r]??[]].join(", ")} } from '${r}';`}var Vt=class extends H{constructor(e={}){super(Ce,e);let t=O.getInstance(),n=ae("SEO Handler",this.options.debug,this.options.verbose),s=process.env.NEXT_PUBLIC_APP_URL||null;s&&this.options.debug&&n.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${s}`);let o=e.baseUrl;!o&&s&&(o=Jt(s)),this._baseUrlExpr=e.baseUrl?`appBaseUrl(${JSON.stringify(e.baseUrl)})`:"appBaseUrl(process.env.NEXT_PUBLIC_APP_URL)",o?n.debug(`Found app URL: ${o}`):n.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let a=e.siteName||null;if(n.verbose(`Name: ${a||"Not found"}`),n.verbose(`URL: ${o||"Not found"}`),a&&n.debug(` - Site name from appConfig: "${a}"`),e.disabled===!0){n.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}if(!this.options.isDev&&(o=Jr(o||null,"NEXT_PUBLIC_APP_URL",n),!o)){this.disabled=!0;return}let i=[];if(o||i.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),a||i.push("siteName (APP_NAME in src/config/app.ts)"),i.length>0){n.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),i.forEach(l=>n.warn(` - ${l}`)),n.warn(""),n.warn(" To fix:"),o||n.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),a||(n.warn(" 2. Add APP_NAME export to src/config/app.ts:"),n.warn(' export const APP_NAME = "Your App Name";')),n.warn(""),n.warn(" robots.txt and sitemap.xml will NOT be generated."),n.warn(""),this.disabled=!0;return}this._baseUrl=o,this._siteName=a,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this._sitemapEnabled=this.options.generateSitemap!==!1,this.seoGenerator=new tt({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,baseUrl:o,siteName:a,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json",trailingSlash:!1}}useRoutes(e){this._routeData=e}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:this._routeData??await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}async generateManifest(e){this.disabled&&await super.generateManifest(e)}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(this.disabled)return;let t=async(i,l)=>{if(!i){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${i}`,l,i)},n=e.routes,s,o;await xe(["robots.txt","rss.xml","seo-manifest.json","sitemap.xml","llms.txt","llms-full.txt"],()=>{s=this.seoGenerator.discoverBlogPosts(),o=this.seoGenerator.getSitemapRoutes(n,s)},this.logger)&&(await xe(["robots.txt","rss.xml","seo-manifest.json"],async()=>{let i=await this.seoGenerator.generateSEOFiles(e,t,s);i.robotsTxt&&!i.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${i.robotsTxt.disallowedPaths||0} disallowed paths`),i.rss&&!i.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${i.rss.postCount||0} blog posts`),i.manifest&&!i.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json")},this.logger),this._sitemapEnabled&&await xe(["sitemap.xml"],()=>this.generateSitemapRoute(o),this.logger),this._llmsTxtEnabled&&(await xe(["llms.txt"],()=>this.generateLlmsTxtRoute(n,s,o),this.logger),s.length>0&&await xe(["llms-full.txt"],()=>{let i=rs({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:this.pathResolver.getAppRoot(),blogPosts:s,logger:this.logger});i&&(this.writeGeneratedFile("public/llms-full.txt",i,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))},this.logger)))}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.serverCrudReader(e),n=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1101
1106
|
// Regenerated on every build from src/pages (PageMeta) and appConfig.
|
|
1102
1107
|
// Public routes + one URL per published record of each dynamic route's entity
|
|
1103
1108
|
// (read with the public role). Keep a page out with \`seo: { noindex: true }\`.
|
|
1104
1109
|
|
|
1105
|
-
${
|
|
1110
|
+
${at("@donotdev/core/server",["HIDDEN_STATUSES","languageUrls"],t)}
|
|
1106
1111
|
import type { LanguageRouting } from '@donotdev/core/server';
|
|
1107
|
-
${
|
|
1112
|
+
${at("@donotdev/core/next",["appBaseUrl","buildSitemap","formatSitemapXml"],t)}
|
|
1108
1113
|
import type { SitemapRoute } from '@donotdev/core/next';
|
|
1109
1114
|
${t.imports}
|
|
1110
1115
|
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
@@ -1133,13 +1138,13 @@ export async function GET(): Promise<Response> {
|
|
|
1133
1138
|
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
|
|
1134
1139
|
});
|
|
1135
1140
|
}
|
|
1136
|
-
`;this.writeGeneratedFile(
|
|
1141
|
+
`;this.writeGeneratedFile(ss,n,"sitemap route");let s=this.pathResolver.resolveAppPath("public/sitemap.xml");this.pathResolver.pathExists(s)&&await this.pathResolver.remove(s),this.logger.info(`\u{1F5FA}\uFE0F sitemap: ${as(e)} (${ss}); URL count printed by dndev build`)}useTranslations(e){this._translations=e}async generateLlmsTxtRoute(e,t,n){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=ns({siteName:this._siteName,description:this._siteDescription,baseUrl:this._baseUrl,sitemapRoutes:n,routes:e,blogPosts:t,blogPath:this.seoGenerator.options.blogPath,translations:this._translations,language:this._languageRouting.defaultLanguage,defaultNamespace:this.options.defaultNamespace||"home"}),{baseUrl:o,...a}=s,i=this.serverCrudReader(s.routes),l=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1137
1142
|
// Regenerated on every build from src/pages (PageMeta), translations and appConfig.
|
|
1138
1143
|
// Same URLs as app/sitemap.xml: public pages + one link per published record of each
|
|
1139
1144
|
// dynamic route's entity. Keep a page out with \`seo: { noindex: true }\`.
|
|
1140
1145
|
|
|
1141
|
-
${
|
|
1142
|
-
${
|
|
1146
|
+
${at("@donotdev/core/server",["HIDDEN_STATUSES","deriveEntitySeo","formatTrailingSlash"],i)}
|
|
1147
|
+
${at("@donotdev/core/next",["appBaseUrl","buildLlmsTxt"],i)}
|
|
1143
1148
|
import type { LlmsTxtSource } from '@donotdev/core/next';
|
|
1144
1149
|
${i.imports}
|
|
1145
1150
|
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
@@ -1168,15 +1173,15 @@ export async function GET(): Promise<Response> {
|
|
|
1168
1173
|
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
1169
1174
|
});
|
|
1170
1175
|
}
|
|
1171
|
-
`;this.writeGeneratedFile(
|
|
1172
|
-
`}function
|
|
1176
|
+
`;this.writeGeneratedFile(os,l,"llms.txt route"),this.logger.info(`\u{1F4C4} llms.txt: ${as(s.routes)} (${os})`)}createManifestContent(){return{}}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function is(r={}){return new Vt(r)}var Ae=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(n,...s)=>{this.options.debug}},this.patterns={selectors:{...dt.selectors,...this.options.customPatterns?.selectors},themes:{...dt.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let n=t.split("-").filter(a=>a.length>0);if(n.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let s=n.map((a,i)=>{let l=a.replace(/[^a-zA-Z0-9]/g,"");return l?i===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!s||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(s)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${s}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(s)?`${s}Var`:s}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,n){let s=[],o,a=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(i))!==null;){let[,c,u,p]=o;if(!c||!p)continue;let d=u.match(this.patterns.themes.themeIcon),f=u.match(this.patterns.themes.themeIsDark),h={name:c,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:d?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${p})`),s.push(h),n.themes.set(c,{name:c,displayName:p,isDark:h.isDark,file:a,variables:new Set,meta:h.meta})}return s.length>0&&this._debug(`Extracted ${s.length} themes from ${a}`),s}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(s=>{let o=s.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,n){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?n==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(s=>{let o=s.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],n=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return n&&n.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let a=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,n="consumer"){let s={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,s);this.extractClasses(e,s),this.extractVariables(e,s,n),this.extractKeyframes(e,s);let a=this.validateCSS(e);return{themes:o,classes:Array.from(s.classes),variables:{framework:Array.from(s.variables.framework),consumer:Array.from(s.variables.consumer),all:[...Array.from(s.variables.framework),...Array.from(s.variables.consumer)].sort()},keyframes:Array.from(s.keyframes),warnings:a}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};var ls="@donotdev/components/styles",oi=/@import\s+['"](\.[^'"]+)['"]\s*;/g,it=class extends ee{constructor(e,t,n={}){super(t,n),this.cssExtractor=e||new Ae(t,{debug:n.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:n}=e;this.logger.debug(`Scanning ${t.length} framework + ${n.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",n),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),n.length>0?(this.logger.debug(`Consumer files found: ${n.length}`),this.logger.debug("Consumer files:",n)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t);let s=await this._processConsumerFiles(n),o=this._serializeThemes(),a={framework:this._readFrameworkTokenCss(),app:s};return this.logger.debug(`Discovered ${o.length} themes:`,o.map(i=>i.name)),{themes:o,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort(),fontCss:a}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return ft.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let n=await this.pathResolver.read(t,{format:"text"}),s=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(n,s,this.discovered),this.cssExtractor.extractClasses(n,this.discovered),this.cssExtractor.extractVariables(n,this.discovered,"framework"),this.cssExtractor.extractKeyframes(n,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(s)}`)}catch(n){this.logger.debug(`Error scanning framework file ${t}: ${n.message}`)}}async _processConsumerFiles(e){let t=[];for(let n of e)try{let s=await this.pathResolver.read(n,{format:"text"}),o=this.pathResolver.normalizePath(n);t.push({file:this.pathResolver.getRelativePath(o),css:s}),this.cssExtractor.extractThemes(s,o,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(o)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${n}: ${s.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(ls,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw x("dndev-theme",`cannot resolve ${ls} (framework font defaults), resolved from @donotdev/ui: check that @donotdev/ui and @donotdev/components are installed`,"missing-required-resource");let t=new Set,n=s=>{if(t.has(s))return"";t.add(s);let o=this.pathResolver.readSync(s,{format:"text"});if(typeof o!="string")throw x("dndev-theme",`cannot read ${s} (framework font defaults)`,"missing-required-resource");let a=this.pathResolver.getDirname(s);return o.replace(oi,(i,l)=>n(this.pathResolver.resolvePath(l,a)))};return n(e)}_addEssentialThemes(){ft.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}))}};import{createRequire as ai}from"node:module";var ii=ai(import.meta.url),us="ThemeIcon_",cs;function li(){return cs??=new Set(Object.keys(ii("lucide-react"))),cs}function ps(r,e){let t=li(),n=new Set;for(let s of r){let o=s.meta?.icon;if(!o)continue;let a=String(o).replace(/['"]/g,"").trim();/^[A-Za-z][A-Za-z0-9]*$/.test(a)&&t.has(a)?n.add(a):e.warn(`\u{1F3A8} Theme "${s.name}": --theme-icon '${a}' is not a lucide-react icon name (theme toggle shows the Palette icon)`)}return[...n].sort()}function ds(r){return r.length===0?"":`import { ${r.map(t=>`${t} as ${us}${t}`).join(", ")} } from 'lucide-react';
|
|
1177
|
+
`}function fs(r){return`{ ${r.map(t=>`${JSON.stringify(t)}: ${us}${t}`).join(", ")} }`}var Kt=class extends H{constructor(e={}){super(it,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new Ae(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],n=t.filter(o=>!o.essential).length,s=t.length;if(s===0)throw En("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: ${s} discovered${n>0?` (${n} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}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(){}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:n}=e,s=ps(t,this.logger);return`// Auto-generated DnDev config by @donotdev/config
|
|
1173
1178
|
// Generated at: ${new Date().toISOString()}
|
|
1174
1179
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
1175
|
-
${
|
|
1180
|
+
${ds(s)}
|
|
1176
1181
|
const themeConfig = {
|
|
1177
1182
|
discovered: ${JSON.stringify(t,null,2)},
|
|
1178
1183
|
// Theme icons (--theme-icon), imported by name: server-rendered without the lucide namespace
|
|
1179
|
-
icons: ${
|
|
1184
|
+
icons: ${fs(s)},
|
|
1180
1185
|
variables: ${JSON.stringify(n,null,2)},
|
|
1181
1186
|
utilities: {
|
|
1182
1187
|
framework: ${JSON.stringify(n.framework,null,2)},
|
|
@@ -1203,14 +1208,14 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1203
1208
|
timestamp: Date.now(),
|
|
1204
1209
|
};
|
|
1205
1210
|
}
|
|
1206
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1211
|
+
globalThis._DNDEV_CONFIG_.${X.themes} = themeConfig;
|
|
1207
1212
|
}
|
|
1208
1213
|
|
|
1209
1214
|
// Export for compatibility
|
|
1210
1215
|
export default themeConfig;
|
|
1211
|
-
`}};function
|
|
1212
|
-
`;return
|
|
1213
|
-
\u{1F3D7}\uFE0F DnDev Framework - Building for ${
|
|
1214
|
-
`)),
|
|
1215
|
-
`)}import
|
|
1216
|
-
`)}function
|
|
1216
|
+
`}};function hs(r={}){return new Kt(r)}function gs({debug:r,verbose:e,generateManifest:t,routeOptions:n,themeOptions:s,i18nOptions:o,assetOptions:a,seoOptions:i,pwaOptions:l,appUrl:c,isDev:u,logger:p}){let d=n.debug??r,f=s.debug??r,h=o.debug??r,m=a.debug??r,y=i.debug??r,S=l.debug??r,_=n.verbose??e,P=s.verbose??e,v=o.verbose??e,E=a.verbose??e,A=i.verbose??e,U=l.verbose??e,M={debug:r,verbose:e,generateManifest:t},te=n.disabled?null:Qr({...M,...n,debug:d,verbose:_});r&&p.debug(`Route handler created: ${te?"enabled":"disabled"} (debug: ${d})`);let W=hs({...M,...s,debug:f,verbose:P}),g=vr({...M,...o,debug:h,verbose:v}),b=mr({...M,...a,debug:m,verbose:E}),T=is({...M,...i,debug:y,verbose:A,appUrl:c,isDev:u}),k=br({...M,...l,debug:S,verbose:U}),D=yr({debug:r,verbose:e});return{routeHandler:te,themeHandler:W,i18nHandler:g,assetHandler:b,seoHandler:T,pwaHandler:k,blogContentHandler:D}}import{existsSync as ws,readFileSync as Ss,writeFileSync as ci}from"node:fs";import{join as Es}from"node:path";var ui="/(.*)",Xt=Object.freeze(["default-src","script-src","style-src","img-src","font-src","connect-src","media-src","worker-src","manifest-src","frame-src","object-src","base-uri","form-action","frame-ancestors"]),pi=Object.freeze({"default-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"frame-src":["'none'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"]}),ms=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),Rs=Object.freeze({"@donotdev/supabase":{"script-src":["https://challenges.cloudflare.com"],"connect-src":["https://*.supabase.co","wss://*.supabase.co"],"frame-src":["https://challenges.cloudflare.com"]},"@donotdev/firebase":{"script-src":["https://accounts.google.com","https://apis.google.com"],"connect-src":["https://identitytoolkit.googleapis.com","https://securetoken.googleapis.com","https://www.googleapis.com","https://*.googleapis.com","https://*.firebaseio.com"],"frame-src":["https://accounts.google.com"]}}),di=Object.freeze([{key:"X-Content-Type-Options",value:"nosniff"},{key:"X-Frame-Options",value:"DENY"},{key:"X-XSS-Protection",value:"1; mode=block"},{key:"Referrer-Policy",value:"strict-origin-when-cross-origin"},{key:"Permissions-Policy",value:"geolocation=(), microphone=(), camera=()"}]),fi=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),hi=31536e3,gi=86400,$s=3600,ys=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(r=>`/assets/:path*.${r}`),"next-export":["/_next/static/:path*"],next:[]}),mi=`/${le.fonts}/:path*`,yi=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),vi=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${$s}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),vs=Object.freeze(["csp","cache"]);function lt(r,e=!1){return`public, max-age=${r}${e?", immutable":""}`}function Yt(r,e){return{source:r,headers:[{key:"Cache-Control",value:e}]}}var bs=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),bi=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function wi(r,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${r}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!bs.includes(e)&&!bi.test(e))throw new Error(`[dndev] appConfig.headers.csp['${r}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${bs.join(" ")} or a hash like 'sha256-<base64>').`)}function Si(r){if(r===void 0)return{csp:{},cache:[]};if(!r||typeof r!="object"||Array.isArray(r))throw new Error("[dndev] appConfig.headers must be an object.");for(let n of Object.keys(r))if(!vs.includes(n))throw new Error(`[dndev] appConfig.headers.${n} is not a header option (allowed: ${vs.join(", ")}).`);let e=r.csp??{};for(let[n,s]of Object.entries(e)){if(!Xt.includes(n))throw new Error(`[dndev] appConfig.headers.csp['${n}'] is not a CSP directive the framework merges (allowed: ${Xt.join(", ")}).`);if(!Array.isArray(s))throw new Error(`[dndev] appConfig.headers.csp['${n}'] must be an array of sources.`);for(let o of s)wi(n,o)}let t=r.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let n of t){if(typeof n?.source!="string"||!n.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(n?.source)}).`);if(!Number.isInteger(n.maxAge)||n.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${n.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(n.maxAge)}).`)}return{csp:e,cache:t}}function Ei({csp:r={},providers:e=[],target:t}){if(!(t in ms))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...Xt.map(s=>{let o=[...s==="script-src"?ms[t]:pi[s]??[],...e.flatMap(l=>Rs[l]?.[s]??[]),...r[s]??[]],a=[...new Set(o)],i=a.length>1?a.filter(l=>l!=="'none'"):a;return i.length>0?`${s} ${i.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function xs({appConfig:r,target:e,providers:t=[],pwa:n=!1}){if(!(e in ys))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:s,cache:o}=Si(r?.headers),a=[{key:"Content-Security-Policy",value:Ei({csp:s,providers:t,target:e})},...r?.seo===!1?[fi]:[],...di].map(i=>({...i}));return[{source:ui,headers:a},...[...ys[e],mi].map(i=>Yt(i,lt(hi,!0))),...yi.map(i=>Yt(`/:path*.${i}`,lt(gi))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:lt($s)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...n?vi.map(i=>({source:i.source,headers:i.headers.map(l=>({...l}))})):[],...o.map(i=>Yt(i.source,lt(i.maxAge,i.immutable===!0)))]}function Ps(r){let e=Es(r,"package.json");if(!ws(e))return[];let t=JSON.parse(Ss(e,"utf8")),n={...t.dependencies,...t.devDependencies};return Object.keys(Rs).filter(s=>!!n[s])}function Cs(r){let e=Es(r,"vercel.json");if(!ws(e))return null;try{return{path:e,config:JSON.parse(Ss(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function As({appRoot:r,rules:e,ci:t,logger:n}){let s=Cs(r);if(!s)return"absent";if(JSON.stringify(s.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${s.path}: "headers" differ from the framework header policy (appConfig.headers, appConfig.seo). The host reads the committed file, so this deploy would serve stale headers. Run the app locally (dev or build) to regenerate vercel.json, then commit it.`);let o=`${JSON.stringify({...s.config,headers:e},null,2)}
|
|
1217
|
+
`;return ci(s.path,o),n?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function Ns(r){let e=Cs(r);if(e&&"headers"in e.config)throw new Error(`[dndev] ${e.path} has "headers": Next serves the framework header policy from next.config headers(). Remove the "headers" key; declare app deltas (CSP sources, cache overrides) in appConfig.headers.`)}var Ri=new Set(["@donotdev/functions"]);function _s(){try{let r=O.getInstance(),e=r.resolveAppPath("package.json"),t=r.readSync(e,{format:"json"});if(!t)return[];let n={...t.dependencies,...t.devDependencies};return Object.keys(n).filter(s=>s.startsWith("@donotdev/")).filter(s=>!Me.buildTimePackages.includes(s)).filter(s=>!Ri.has(s)).sort()}catch{return[]}}var Zt=new Map;function $i(r={}){let{port:e,...t}=r;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let re=process.env.CI==="true";process.env.DNDEV_BUILD_ID=re?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let n=process.env.DNDEV_BUILD_ID;if(n&&Zt.has(n))return Zt.get(n).configFn;let{appConfig:s,...o}=t;if(!s)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let a=s?.features?{debug:s.features.debug}:void 0,i=s?.seo===!1?{disabled:!0}:s?.seo&&typeof s.seo!="boolean"?{...s.seo,siteName:s.seo.siteName||s.app?.name,siteDescription:s.app?.description}:s?.app?.name?{siteName:s.app.name,siteDescription:s.app.description}:void 0,l=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:c,seo:u,...p}=o,d={...a?{features:a}:{},...i?{seo:i}:{},...p},f=or(d),h=ar(f);if(!h)throw new Error("normalizeOptions returned undefined");let{generateManifest:m,debug:y,verbose:S,mode:_,isDev:P,routeOptions:v,themeOptions:E,i18nOptions:A,assetOptions:U,pwaOptions:M,seoOptions:te,nextConfigOptions:W,reactCompiler:g}=h,b=ae("next-config",y,S),{appRoot:T,appRootSet:k}=dn({logger:b,debug:y}),D=v?.routingMode||"app",F=k&&Ct(T);if(F||(b.info(`
|
|
1218
|
+
\u{1F3D7}\uFE0F DnDev Framework - Building for ${_}${n?` [build:${n}]`:""}`),b.info(` Platform: Next.js | Routing: ${D}
|
|
1219
|
+
`)),P){let re=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${re}`,y&&(b.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&b.debug(`Port configured: ${re} (set PORT env var)`))}else!process.env.NEXT_PUBLIC_APP_URL&&!nt()&&(process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${process.env.PORT||3e3}`);let N=W.trailingSlash===!0,G=gs({debug:y,verbose:S,generateManifest:m,routeOptions:{...v,ssr:s?.ssr!==!1,auth:s?.auth,revalidate:s?.revalidate,prerenderRecords:s?.prerenderRecords,trailingSlash:N,siteName:s?.seo?.siteName||s?.app?.name,defaultImage:s?.seo?.defaultImage,defaultNamespace:s?.seo?.defaultNamespace},themeOptions:E,i18nOptions:A,assetOptions:U,seoOptions:{...te,revalidate:s?.revalidate,trailingSlash:N},pwaOptions:{...M,app:l},isDev:P,logger:b}),B=async function(){let w=O.getInstance(),R=k?_s():[];y&&R.length>0&&b.debug(`Discovered ${R.length} packages: ${R.join(", ")}`);let{missing:C}=Ve(w.getAppRoot());y&&C.length>0&&b.debug(`Missing optional deps (will alias to empty): ${C.join(", ")}`),k&&(D==="app"&&mn({pathResolver:w,logger:b,isCI:!!(process.env.CI||process.env.VERCEL)}),await nr(G,b,{appFonts:s?.fonts}));let I=W,{rewrites:V,redirects:ge,headers:de,...me}=I,Le=vn({originalRewrites:V,handlers:[G.routeHandler,G.themeHandler,G.i18nHandler,G.assetHandler,G.pwaHandler],logger:b}),ut=bn({originalRedirects:ge,seoRedirects:te?.redirects||[],logger:b}),ie=me.output==="export",tn=k?xs({appConfig:s,target:ie?"next-export":"next",providers:Ps(w.getAppRoot()),pwa:M?.enabled===!0}):[];k&&ie?As({appRoot:w.getAppRoot(),rules:tn,ci:!!(process.env.CI||process.env.VERCEL),logger:b}):k&&Ns(w.getAppRoot());let Ls=ie?null:wn({policyRules:P?[]:tn,originalHeaders:de}),Ms={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Us=Sn({restNextConfig:me,discoveredPackages:R,reactCompiler:g,routingMode:D,rewritesConfig:Le,redirectsConfig:ut,headersConfig:Ls,missingOptionalDeps:C,pathResolver:w,env:Ms,logger:b});if(b.debug("Next.js config generated"),k&&!F){let js=l?.name||"app";b.info(`Name: ${js}`),b.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),b.info(`App root (final): ${w.getAppRoot()}`)}return Us};return n&&Zt.set(n,{configFn:B}),B}var ks=$i;import{readFileSync as xi,existsSync as Pi}from"node:fs";import{join as Ci}from"node:path";var Fe=null,Qt=0,Ai=6e4;function Ni(){let r=Date.now();if(Fe&&r-Qt<Ai)return Fe;try{let e=Ci(process.cwd(),"public","metadata-manifest.json");if(!Pi(e))return null;let t=xi(e,"utf-8");return Fe=JSON.parse(t),Qt=r,Fe}catch{return null}}function _i(r,e,t){let n=Ni(),s={title:t?.siteName||"Site"};if(!n)return s;let o=r.startsWith("/")?r:`/${r}`,a=n[o];if(!a)return s;let i=e||a.defaultLocale||"en",l=a.locales[i]||a.locales[a.defaultLocale]||Object.values(a.locales)[0];if(!l)return s;let c=process.env.NEXT_PUBLIC_APP_URL,u={title:l.title,...c&&{metadataBase:new URL(c)}};return l.description&&(u.description=l.description),l.keywords&&(u.keywords=l.keywords),u.openGraph={title:l.title,type:l.type||"website",...l.description&&{description:l.description},...l.image&&{images:[l.image]},...t?.siteName&&{siteName:t.siteName}},u.twitter={card:"summary_large_image",title:l.title,...l.description&&{description:l.description},...l.image&&{images:[l.image]}},l.robots&&(u.robots={index:!1,...l.robots==="noindex, nofollow"&&{follow:!1}}),u}function ki(){Fe=null,Qt=0}function ct(r){return String(r).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function Di(r,{baseUrl:e,routing:t,trailingSlash:n,crud:s,readSchemas:o,languageUrls:a,hiddenStatuses:i}){let l=[],c=(u,p)=>{let d=a(u,e,t,n),f=t.languages.length>1?{alternates:{languages:d}}:{};for(let h of t.languages)l.push({url:d[h],...p,...f})};for(let{route:u,path:p,record:d}of await Ze(r,s,i,o)){if(!d){c(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??(p==="/"?1:.8),...u.lastModified&&{lastModified:u.lastModified}});continue}let f=d.updatedAt instanceof Date?d.updatedAt.toISOString():d.updatedAt;c(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??.7,...typeof f=="string"&&{lastModified:f}})}return l}function Ti(r){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${r.some(n=>n.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let n of r){t.push(" <url>",` <loc>${ct(n.url)}</loc>`);for(let[s,o]of Object.entries(n.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${ct(s)}" href="${ct(o)}" />`);n.lastModified&&t.push(` <lastmod>${ct(n.lastModified)}</lastmod>`),n.changeFrequency&&t.push(` <changefreq>${n.changeFrequency}</changefreq>`),n.priority!==void 0&&t.push(` <priority>${n.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
|
|
1220
|
+
`)}import Fi from"i18next";function Ds(r,e){return r.startsWith("/")?`${e}${r}`:r}function en(r){return typeof r=="object"&&r!==null&&"collection"in r&&"fields"in r}function Ts(r,e,t){for(let n of Object.values(r))if(en(n)&&n.collection===e)return n;throw new Error(`[dndev] Entity page "${t}": no entity definition for collection "${e}". Export it from the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`)}function Oi(r,e,t){let n=Object.create(null);for(let s of e)!s.collection||Object.hasOwn(n,s.collection)||(n[s.collection]=t(Ts(r,s.collection,s.path)).get);return Object.freeze(n)}function Os(r,e){let{route:t,value:n,language:s,baseUrl:o,siteName:a,type:i}=e,l=Ts(e.entities,t.collection,t.path),c=e.deriveEntitySeo(l,r,{t:e.translate([l.namespace,"crud"]),locale:s}),u=q(t.path)[0],p=t.path.replace(`:${u}`,encodeURIComponent(n)),d=S=>e.languageUrl(S,s,o,e.routing,e.trailingSlash),f=d(p),h=c.title?`${c.title} | ${a}`:a,m=Ds(c.image||e.defaultImage,o),y=i==="product"?e.buildProductJsonLd({...c,images:[...new Set(c.images.map(S=>Ds(S,o)))]},f):null;return{url:f,title:h,...c.description&&{description:c.description},image:m,type:i,jsonLd:y,breadcrumb:c.title?e.buildBreadcrumbJsonLd({pathname:p,routes:e.routes,siteName:a,t:e.translate([e.defaultNamespace]),defaultNs:e.defaultNamespace,pageUrl:d,lastName:c.title}):null}}function Ie(r){return r.replace(/\s+/g," ").trim()}function Fs(r){let e=[`# ${Ie(r.name)}`,""];r.summary&&e.push(`> ${Ie(r.summary)}`,"");for(let t of r.sections)if(t.links.length!==0){e.push(`## ${Ie(t.heading)}`,"");for(let n of t.links){let s=`- [${Ie(n.title)}](${n.url})`;e.push(n.description?`${s}: ${Ie(n.description)}`:s)}e.push("")}return e.join(`
|
|
1221
|
+
`)}function Ii(r){let e=new Map;for(let t of Object.values(r))en(t)&&e.set(t.collection,t);return e}function Li(r,e){let t=Fi.createInstance();return t.init({lng:r,resources:{[r]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),n=>t.getFixedT(r,[n,"crud"])}async function Mi(r){let{crud:e,readSchemas:t,deriveEntitySeo:n,hiddenStatuses:s,formatTrailingSlash:o,trailingSlash:a}=r,i=Ii(r.entities),l,c=new Map,u=p=>{let d=c.get(p);return d||(d={heading:p,links:[]},c.set(p,d)),d};u(r.pagesHeading);for(let{route:p,path:d,record:f}of await Ze(r.routes,e,s,t)){let h=`${r.baseUrl}${o(d,a)}`;if(!f){if(!p.title)throw new Error(`[dndev] llms.txt: source route "${p.path}" has no title (getLlmsTxtSource gives every static page one).`);u(p.section??r.pagesHeading).links.push({title:p.title,url:h,...p.description&&{description:p.description}});continue}let m=i.get(p.collection);if(!m)throw new Error(`[dndev] llms.txt: no entity definition for collection "${p.collection}" (route "${p.path}"). Export it from the app's \`entities\` package.`);let y=p.section??(m.namespace?r.entityHeadings[m.namespace]:void 0);if(!y)throw new Error(`[dndev] llms.txt: no heading for route "${p.path}". Add "namePlural" to the ${m.namespace??`entity-${m.name.toLowerCase()}`} translations.`);if(!l){if(!r.language||!r.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");l=Li(r.language,r.translations)}let S=n(m,f,{t:l(m.namespace),locale:r.language});u(y).links.push({title:S.title||r.name,url:h,...S.description&&{description:S.description}})}return Fs({name:r.name,...r.summary&&{summary:r.summary},sections:[...c.values()]})}var Is=new Set(["website","article"]);async function Ui(r,e,t,n,s){let o=q(r.path),a=o[0];if(o.length!==1||!r.collection||!a)throw new Error(`[dndev] Entity page "${r.path}": only single-param routes of an entity collection read a record.`);if(!t)throw new Error(`[dndev] Entity page "${r.path}" reads a "${r.collection}" record but no server CRUD reader was given.`);let i=Bt(r,s),l;try{l=await t.query(r.collection,{where:[{field:a,operator:"==",value:e},{field:"status",operator:"not-in",value:[...n]}],limit:1},i)}catch(c){let u=c?.details?.originalMessage??c?.message??String(c);throw new Error(`[dndev] Entity page "${r.path}" could not read its public "${r.collection}" record (signed-out visitor: RLS / Security Rules must allow it): ${u}`,{cause:c})}return l.items[0]??null}function ji(r,e){let{title:t,description:n,image:s,type:o,jsonLd:a,breadcrumb:i}=Os(r,e);return{metadata:{title:{absolute:t},...n&&{description:n},openGraph:{title:{absolute:t},...n&&{description:n},...Is.has(o)&&{type:o},images:[s]},twitter:{card:"summary_large_image",title:{absolute:t},...n&&{description:n},images:[s]}},ogType:Is.has(o)?null:o,jsonLd:a,breadcrumb:i}}function Bi(r){return JSON.stringify(r).replace(/</g,"\\u003c")}export{Tr as REVALIDATE_ROUTE_PATH,Te as REVALIDATE_SECRET_ENV,si as appBaseUrl,Mi as buildLlmsTxt,Di as buildSitemap,ki as clearMetadataCache,ks as default,ks as defineNextConfig,Js as definePostCSSConfig,ji as entityPageSeo,Oi as entityReadSchemas,Ti as formatSitemapXml,_i as getMetadataForPath,Ca as handleRevalidationWebhook,Bi as jsonLdScript,wa as listStaticParams,Ui as readEntityPageRecord,Or as revalidationPaths};
|