@donotdev/core 0.0.40 → 0.0.42
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/empty.js +5 -3
- package/functions/index.js +2 -2
- package/index.d.ts +10 -12
- package/next/index.js +42 -41
- package/package.json +4 -4
- package/server.d.ts +9 -11
- package/vite/index.js +1 -1
package/empty.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @fileoverview ESM empty module for
|
|
2
|
+
* @fileoverview ESM empty module for Vite browser serving ONLY (via absolute file path)
|
|
3
3
|
* @description Proxy-based noop that silently absorbs any property access or function call.
|
|
4
|
-
* Used by Vite's resolveId hook
|
|
5
|
-
*
|
|
4
|
+
* Used ONLY by Vite's resolveId hook (absolute path from PathResolver.getEmptyModulePath()).
|
|
5
|
+
* NOT used via the @donotdev/core/empty package export — that resolves to empty.cjs
|
|
6
|
+
* because bundlers (Turbopack, esbuild) statically analyze ESM and reject unknown named imports.
|
|
7
|
+
* For all bundler alias targets, see empty.cjs (CJS = dynamic exports = any named import resolves).
|
|
6
8
|
*/
|
|
7
9
|
const handler = {
|
|
8
10
|
get(_, prop) {
|
package/functions/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import A from"node:fs";import P from"node:path";import{fileURLToPath as oe}from"node:url";var ne=oe(import.meta.url),Pe=P.dirname(ne);function j(){let a=process.cwd(),e=10;for(let t=0;t<e;t++){let o=P.join(a,"package.json");if(A.existsSync(o))try{let s=JSON.parse(A.readFileSync(o,"utf8")),r=s.workspaces&&Array.isArray(s.workspaces);if(r&&s.workspaces.some(i=>i==="packages/**"||i.startsWith("packages/"))&&(A.existsSync(P.join(a,"packages","core"))||A.existsSync(P.join(a,"packages","functions"))))return{type:"dndev",root:a};if(r&&s.workspaces.some(i=>i.includes("dndev/packages"))){let u=s.workspaces.find(m=>m.includes("dndev/packages")).replace(/\/packages.*$/,""),d=P.resolve(a,u);if(A.existsSync(P.join(d,"packages","core")))return{type:"dndev",root:d}}}catch{}let n=P.dirname(a);if(n===a)break;a=n}return{type:"npm",root:process.cwd()}}function ie(a){return a.type==="dndev"?a.root:null}function H(a){let e={};if(a.type==="dndev"){let t=ie(a);t&&(e["@donotdev/types"]=P.join(t,"packages","core","types","src"),e["@donotdev/functions"]=P.join(t,"packages","functions","src"),e["@donotdev/utils"]=P.join(t,"packages","core","utils","src"),e["@donotdev/schemas"]=P.join(t,"packages","core","schemas","src"),e["@donotdev/core"]=P.join(t,"packages","core"))}return e}import*as h from"node:fs";import"node:fs";import{createRequire as ce}from"node:module";import{resolve as C,join as S,dirname as F,relative as K,normalize as le,sep as q,extname as ue}from"node:path";import"node:url";import pe from"fast-glob";var D={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"},w={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:[`${D.SOURCE_EAGER}/*_*.json`],lazy:[`${D.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]};var Y={base:{absolute:!0,onlyFiles:!0,ignore:w.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...w.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...w.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:w.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:w.globalIgnore}};function V(a,e=null){let t=w[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(o=>`${e}/${o}`)}:t}function J(a){return Y[a]||Y.base}var _={getGlobOptionsFor:J||void 0,SCAN_PATTERNS:w||void 0,getPatternsFor:V||void 0,I18N_PATHS:D||void 0},y={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function X(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Z={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 a{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,a._instance=this}normalizePath(e){if(!e)return"";try{return le(e).split(q).join("/")}catch{return String(e).split(q).join("/")}}getRelativePath(e){let t=this.getAppRoot(),o=K(t,e);return this.normalizePath(o)}getBasename(e){if(!e)return"";let o=this.normalizePath(e).split("/");return o[o.length-1]||""}getDirname(e){return e?this.normalizePath(F(e)):""}resolvePackage(e,t=null){try{let o=t||this.getAppRoot(),s=ce(S(o,"package.json")).resolve(e);return this.normalizePath(s)}catch{return null}}resolveFrameworkPackage(e,t=null){let o=this.resolvePackage(`${e}/package.json`,t);if(o)return this.getDirname(o);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let r=e.replace("@donotdev/",""),c=this.resolveRepoPath(`packages/${r}`);if(this.pathExists(c))return c;if(["auth","billing","crud","oauth"].includes(r)){let l=this.resolveRepoPath(`packages/features/${r}`);if(this.pathExists(l))return l}if(r==="firebase"){let l=this.resolveRepoPath(`packages/providers/${r}`);if(this.pathExists(l))return l}}let n=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(n))return n;let s=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(s)?s:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),o=C(t,e);return this.normalizePath(o)}resolveRepoPath(e){let t=this.getRepoRoot(),o=this.normalizePath(e),n=C(t,o);return this.normalizePath(n)}resolvePath(e,t){let o=this.normalizePath(t),n=this.normalizePath(e),s=C(o,n);return this.normalizePath(s)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=h.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:ue(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:o="auto",encoding:n="utf8"}=t,s=this._detectFormat(e,o);try{if(s==="buffer")return await h.promises.readFile(e);let r=await h.promises.readFile(e,n),c=this.stripBom(r);return s==="json"?JSON.parse(c):c}catch(r){return this.options.debug&&y.warn(`Failed to read file: ${e}`,r),null}}readSync(e,t={}){let{format:o="auto",encoding:n="utf8"}=t,s=this._detectFormat(e,o);try{if(s==="buffer")return h.readFileSync(e);let r=h.readFileSync(e,n),c=this.stripBom(r);return s==="json"?JSON.parse(c):c}catch(r){return this.options.debug&&y.warn(`Failed to read file: ${e}`,r),null}}async write(e,t,o={}){let{format:n="auto",overwrite:s=!1,dryRun:r=!1,verbose:c=!1}=o,l=this.normalizePath(e),f=this.normalizePath(F(l)),i=this.pathExists(l);if(i&&!s)return c&&y.info(`Skipping existing file: ${l}`),!1;if(r)return y.info(`[DRY RUN] Would write file: ${l}`),!0;try{await h.promises.mkdir(f,{recursive:!0})}catch(m){if(m?.code!=="EEXIST")throw m}let u=this._detectFormat(e,n),d;Buffer.isBuffer(t)?d=t:u==="json"&&typeof t=="object"?d=JSON.stringify(t,null,2):d=String(t);try{return await X(async()=>(Buffer.isBuffer(d)?await h.promises.writeFile(l,d):await h.promises.writeFile(l,d,"utf8"),c&&y.info(`${i?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,o={}){let{format:n="auto",overwrite:s=!1,dryRun:r=!1,verbose:c=!1}=o,l=this.normalizePath(e),f=this.normalizePath(F(l)),i=this.pathExists(l);if(i&&!s)return c&&y.info(`Skipping existing file: ${l}`),!1;if(r)return y.info(`[DRY RUN] Would write file: ${l}`),!0;try{h.mkdirSync(f,{recursive:!0})}catch(m){if(m?.code!=="EEXIST")throw m}let u=this._detectFormat(e,n),d;Buffer.isBuffer(t)?d=t:u==="json"&&typeof t=="object"?d=JSON.stringify(t,null,2):d=String(t);try{return Buffer.isBuffer(d)?h.writeFileSync(l,d):h.writeFileSync(l,d,"utf8"),c&&y.info(`${i?"Updated":"Created"} file: ${l}`),!0}catch(m){throw new Error(`Failed to write file: ${l}: ${m instanceof Error?m.message:String(m)}`)}}async copy(e,t,o={}){let{overwrite:n=!1,dryRun:s=!1,verbose:r=!1}=o,c=this.normalizePath(t),l=this.pathExists(c);if(l&&!n)return r&&y.info(`Skipping existing file: ${c}`),!1;if(s)return y.info(`[DRY RUN] Would copy file: ${c}`),!0;let f=this.normalizePath(F(c));try{await h.promises.mkdir(f,{recursive:!0})}catch(i){if(i?.code!=="EEXIST")throw i}try{return await X(async()=>(await h.promises.copyFile(e,c),r&&y.info(`${l?"Updated":"Created"} file: ${c}`),!0),`Failed to copy file from ${e} to ${c}`)}catch{return!1}}copySync(e,t,o={}){let{overwrite:n=!1,dryRun:s=!1,verbose:r=!1}=o,c=this.normalizePath(t),l=this.pathExists(c);if(l&&!n)return r&&y.info(`Skipping existing file: ${c}`),!1;if(s)return y.info(`[DRY RUN] Would copy file: ${c}`),!0;let f=this.normalizePath(F(c));try{h.mkdirSync(f,{recursive:!0})}catch(i){if(i?.code!=="EEXIST")throw i}try{return h.copyFileSync(e,c),r&&y.info(`${l?"Updated":"Created"} file: ${c}`),!0}catch{return!1}}pathExists(e,t=!1){try{return h.existsSync(e)}catch(o){return t||y.error(`Error checking path existence: ${e}`,o),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return h.existsSync(t)||h.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return h.readdirSync(e,t)}catch(o){return this.options.debug&&y.warn(`Failed to read directory: ${e}`,o),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return h.statSync(e)}catch(t){return this.options.debug&&y.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return h.realpathSync(e)}watch(e,t,o){return h.watch(e,t,o)}lstatSync(e){try{return h.lstatSync(e)}catch(t){return this.options.debug&&y.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await h.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{h.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await h.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){h.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return h.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=S(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(C(e)),o=this.getAppRoot(),n=K(o,t),s=this.normalizePath(n);return!s.startsWith("../")&&!s.startsWith("/")}async findFiles(e,t,o={}){let n=this.normalizePath(S(e,t)),s=this.getAppRoot(),r=this.normalizePath(s),c=n.startsWith(r)?n.slice(r.length+1):n,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:_.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([c],{...l,...o})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=_.I18N_PATHS;if(!t)return null;let o=e.replace(t.SOURCE_ROOT+"/",""),n=this.resolveFrameworkPackage("@donotdev/core");if(!n)return null;let s=this.normalizePath(S(n,t.PUBLISHED_ROOT,o)),r=s.replace(/\/[^/]*\*.*$/,"");return this.pathExists(r),s}async _globWithNormalization(e,t){return(await pe(e,t)).map(n=>{let s=typeof n=="string"?n:n.path;return this.normalizePath(s)})}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 o=[...e.framework,...e.consumer];for(let i of o)if(typeof i!="string"||i.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let n=this.getAppRoot(),s=_.getGlobOptionsFor?_.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},r=this.normalizePath(n),c=e.framework.map(i=>{let u=this.normalizePath(i);return u.startsWith(r)?u.slice(r.length+1):u}),l=e.consumer.map(i=>{let u=this.normalizePath(i);return u.startsWith(r)?u.slice(r.length+1):u}),f={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n};try{let i=c.length>0?await this._globWithNormalization(c,f):[],u=await this._globWithNormalization(l,f);return{frameworkFiles:i,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!_.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),o=this.getRepoRoot();if(e==="i18n"&&(!t||t===o))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${o}). Ensure configResolved hook has run before discovery.`);let n=_.getPatternsFor(e),s=this.isMonorepo();if(e==="i18n"){let l=n,f={eager:l.eager.map(i=>i.startsWith("!")?"!"+this.resolveAppPath(i.slice(1)):this.resolveAppPath(i)),lazy:l.lazy.map(i=>i.startsWith("!")?"!"+this.resolveAppPath(i.slice(1)):this.resolveAppPath(i)),framework:{eager:s?(l.framework?.eager||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(i=>this._resolveFrameworkI18nPattern(i))).then(i=>i.filter(Boolean)),lazy:s?(l.framework?.lazy||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(i=>this._resolveFrameworkI18nPattern(i))).then(i=>i.filter(Boolean))},all:[]};return f.all=[...f.eager,...f.lazy,...f.framework.eager,...f.framework.lazy],f}let r=n,c={framework:s?(r.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(r.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return c.all=[...c.consumer,...c.framework],c}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),o=0,n=this.options.maxLevels;for(;o<n;){let s=this.normalizePath(S(t,Z.TOOLING)),r=this.normalizePath(S(t,Z.CORE));if(this.pathExists(s)&&this.pathExists(r))return t;let c=S(t,"apps");if(this.pathExists(c)&&this.statSync(c)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(S(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(F(t))===t)return t;let f=this.normalizePath(F(t));if(f===t)break;t=f,o++}return this.normalizePath(e)}};function T(a={}){let{entry:e="src/index.ts",outDir:t="lib",minify:o=!1,sourcemap:n=!0,platform:s="firebase",workspace:r,bundleWorkspaceDeps:c=!1,importFramework:l=!1,external:f=!1,...i}=a,u=O.getInstance(),d=H(r),m={entryPoints:[e],bundle:!0,platform:"node",target:"node20",format:"esm",outdir:t,outExtension:{".js":".js"},minify:o,sourcemap:n,metafile:!0,logLevel:"info",loader:{".ts":"ts",".tsx":"tsx",".css":"empty"},keepNames:!0,treeShaking:!0,...i};c&&Object.keys(d).length>0&&(m.alias=Object.fromEntries(Object.entries(d).map(([v,p])=>[v,u.normalizePath(p)]))),m.mainFields=["module","main"],m.conditions=["import","module","node"];let $=["fs","path","crypto","util","stream","events","buffer","url","querystring","http","https","zlib","os","child_process","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","perf_hooks","async_hooks"],I=[];if(c)try{let v=r?.root||process.cwd(),p=process.cwd(),g=10;for(let k=0;k<g;k++){let x=u.normalizePath(`${p}/package.json`);if(u.pathExists(x)){let b=u.readSync(x,{format:"json"});if(b&&Array.isArray(b.workspaces)){v=u.normalizePath(p);for(let R of b.workspaces)R==="apps/*"||R==="functions"||!R.includes("*")&&!R.includes("/")&&I.push(R);break}}let E=u.getDirname(p);if(E===p)break;p=E}}catch{}let W={name:"external-node-modules",setup(v){v.onResolve({filter:/^firebase($|\/)/},p=>{if(p.path==="firebase-admin"||p.path.startsWith("firebase-admin/")||p.path==="firebase-functions"||p.path.startsWith("firebase-functions/"))return null;let g;if(r?.type==="dndev"&&r.root)g=u.normalizePath(`${r.root}/packages/core/config/functions/firebase-stub.js`);else{let k=import.meta.url,E=new URL(k).pathname.replace(/^\/([A-Z]:)/i,"$1"),b=u.getDirname(E);g=u.normalizePath(`${b}/firebase-stub.js`)}return{path:g}}),v.onResolve({filter:/.*/},p=>{if(p.kind==="entry-point")return null;if(p.path.match(/@donotdev\/functions\/.+/)&&c&&r?.type==="dndev"){let g=p.path.replace("@donotdev/functions/","");return{path:u.normalizePath(`${r.root}/packages/functions/src/${g}/index.ts`)}}if(p.path==="@donotdev/utils")return r?.type==="dndev"?{path:u.normalizePath(`${r.root}/packages/core/utils/src/server/index.ts`)}:v.resolve("@donotdev/utils/server",{kind:p.kind,resolveDir:p.resolveDir});if(p.path.match(/@donotdev\/utils\/.+/)&&r?.type==="dndev"){let g=p.path.replace("@donotdev/utils/","");return{path:u.normalizePath(`${r.root}/packages/core/utils/src/${g}/index.ts`)}}if(p.path==="@donotdev/supabase")return r?.type==="dndev"?{path:u.normalizePath(`${r.root}/packages/providers/supabase/src/server/index.ts`)}:v.resolve("@donotdev/supabase/server",{kind:p.kind,resolveDir:p.resolveDir});if(p.path==="@donotdev/core")return r?.type==="dndev"?{path:u.normalizePath(`${r.root}/packages/core/server.ts`)}:v.resolve("@donotdev/core/server",{kind:p.kind,resolveDir:p.resolveDir});if(p.path.match(/@donotdev\/core\/.+/)&&c&&r?.type==="dndev"){let g=p.path.replace("@donotdev/core/","");return{path:u.normalizePath(`${r.root}/packages/core/${g}.ts`)}}if(p.path==="firebase-admin"||p.path.startsWith("firebase-admin/")||p.path==="firebase-functions"||p.path.startsWith("firebase-functions/"))return{path:p.path,external:!0};if(p.path.match(/@donotdev\/core\/.+/)&&c&&r?.type==="dndev"){let g=p.path.replace("@donotdev/core/","");return{path:u.normalizePath(`${r.root}/packages/core/${g}.ts`)}}if(p.path.startsWith("@donotdev/")||p.path==="valibot"||p.path.startsWith("valibot/"))return null;if(I.length>0){let g=p.path.split("/")[0];if(I.includes(g))return null}return p.path.startsWith(".")||p.path.startsWith("/")?null:{path:p.path,external:!0}})}};if(m.external=[...$,"firebase-admin","firebase-functions"],m.plugins=[W,...m.plugins||[]],m.define={"process.env.NODE_ENV":JSON.stringify(process.env.NODE_ENV||"production"),...m.define||{}},l&&r.type==="dndev"){let v=r.root,p=u.normalizePath(`${v}/functions/lib`);m.alias={...m.alias,"@donotdev/functions":p}}if(s==="framework"){let v=O.getInstance(),p=r?.root?v.normalizePath(`${r.root}/packages/functions`):process.cwd(),g=v.normalizePath(`${p}/package.json`),k=v.readSync(g,{format:"json"});if(k?.exports){let x={};for(let[,E]of Object.entries(k.exports)){let b=E?.import||E?.default||(typeof E=="string"?E:null);if(!b||!b.endsWith(".ts"))continue;let R=b.replace(/^\.\/src\//,"").replace(/\.ts$/,"");x[R]=b}Object.keys(x).length>0&&(m.entryPoints=x)}}return m}import{readFileSync as N,writeFileSync as B,existsSync as L}from"fs";import"path";var U=["create","get","list","listCard","update","delete"];function Q(a,e=0){let t=" ".repeat(e),o="";for(let[n,s]of Object.entries(a))if(s!=null)if(typeof s=="object"&&!Array.isArray(s))Object.keys(s).length===0?o+=`${t}${n}: {}
|
|
1
|
+
import A from"node:fs";import P from"node:path";import{fileURLToPath as oe}from"node:url";var ne=oe(import.meta.url),Pe=P.dirname(ne);function I(){let a=process.cwd(),e=10;for(let t=0;t<e;t++){let o=P.join(a,"package.json");if(A.existsSync(o))try{let s=JSON.parse(A.readFileSync(o,"utf8")),r=s.workspaces&&Array.isArray(s.workspaces);if(r&&s.workspaces.some(i=>i==="packages/**"||i.startsWith("packages/"))&&(A.existsSync(P.join(a,"packages","core"))||A.existsSync(P.join(a,"packages","functions"))))return{type:"dndev",root:a};if(r&&s.workspaces.some(i=>i.includes("dndev/packages"))){let u=s.workspaces.find(m=>m.includes("dndev/packages")).replace(/\/packages.*$/,""),d=P.resolve(a,u);if(A.existsSync(P.join(d,"packages","core")))return{type:"dndev",root:d}}}catch{}let n=P.dirname(a);if(n===a)break;a=n}return{type:"npm",root:process.cwd()}}function ie(a){return a.type==="dndev"?a.root:null}function H(a){let e={};if(a.type==="dndev"){let t=ie(a);t&&(e["@donotdev/types"]=P.join(t,"packages","core","types","src"),e["@donotdev/functions"]=P.join(t,"packages","functions","src"),e["@donotdev/utils"]=P.join(t,"packages","core","utils","src"),e["@donotdev/schemas"]=P.join(t,"packages","core","schemas","src"),e["@donotdev/core"]=P.join(t,"packages","core"))}return e}import*as h from"node:fs";import"node:fs";import{createRequire as ce}from"node:module";import{resolve as C,join as S,dirname as F,relative as K,normalize as le,sep as q,extname as ue}from"node:path";import"node:url";import pe from"fast-glob";var D={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"},w={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:[`${D.SOURCE_EAGER}/*_*.json`],lazy:[`${D.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]};var Y={base:{absolute:!0,onlyFiles:!0,ignore:w.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...w.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...w.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:w.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:w.globalIgnore}};function V(a,e=null){let t=w[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(o=>`${e}/${o}`)}:t}function J(a){return Y[a]||Y.base}var _={getGlobOptionsFor:J||void 0,SCAN_PATTERNS:w||void 0,getPatternsFor:V||void 0,I18N_PATHS:D||void 0},y={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function X(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Z={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 a{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,a._instance=this}normalizePath(e){if(!e)return"";try{return le(e).split(q).join("/")}catch{return String(e).split(q).join("/")}}getRelativePath(e){let t=this.getAppRoot(),o=K(t,e);return this.normalizePath(o)}getBasename(e){if(!e)return"";let o=this.normalizePath(e).split("/");return o[o.length-1]||""}getDirname(e){return e?this.normalizePath(F(e)):""}resolvePackage(e,t=null){try{let o=t||this.getAppRoot(),s=ce(S(o,"package.json")).resolve(e);return this.normalizePath(s)}catch{return null}}resolveFrameworkPackage(e,t=null){let o=this.resolvePackage(`${e}/package.json`,t);if(o)return this.getDirname(o);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let r=e.replace("@donotdev/",""),c=this.resolveRepoPath(`packages/${r}`);if(this.pathExists(c))return c;if(["auth","billing","crud","oauth"].includes(r)){let l=this.resolveRepoPath(`packages/features/${r}`);if(this.pathExists(l))return l}if(r==="firebase"){let l=this.resolveRepoPath(`packages/providers/${r}`);if(this.pathExists(l))return l}}let n=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(n))return n;let s=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(s)?s:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),o=C(t,e);return this.normalizePath(o)}resolveRepoPath(e){let t=this.getRepoRoot(),o=this.normalizePath(e),n=C(t,o);return this.normalizePath(n)}resolvePath(e,t){let o=this.normalizePath(t),n=this.normalizePath(e),s=C(o,n);return this.normalizePath(s)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=h.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:ue(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:o="auto",encoding:n="utf8"}=t,s=this._detectFormat(e,o);try{if(s==="buffer")return await h.promises.readFile(e);let r=await h.promises.readFile(e,n),c=this.stripBom(r);return s==="json"?JSON.parse(c):c}catch(r){return this.options.debug&&y.warn(`Failed to read file: ${e}`,r),null}}readSync(e,t={}){let{format:o="auto",encoding:n="utf8"}=t,s=this._detectFormat(e,o);try{if(s==="buffer")return h.readFileSync(e);let r=h.readFileSync(e,n),c=this.stripBom(r);return s==="json"?JSON.parse(c):c}catch(r){return this.options.debug&&y.warn(`Failed to read file: ${e}`,r),null}}async write(e,t,o={}){let{format:n="auto",overwrite:s=!1,dryRun:r=!1,verbose:c=!1}=o,l=this.normalizePath(e),f=this.normalizePath(F(l)),i=this.pathExists(l);if(i&&!s)return c&&y.info(`Skipping existing file: ${l}`),!1;if(r)return y.info(`[DRY RUN] Would write file: ${l}`),!0;try{await h.promises.mkdir(f,{recursive:!0})}catch(m){if(m?.code!=="EEXIST")throw m}let u=this._detectFormat(e,n),d;Buffer.isBuffer(t)?d=t:u==="json"&&typeof t=="object"?d=JSON.stringify(t,null,2):d=String(t);try{return await X(async()=>(Buffer.isBuffer(d)?await h.promises.writeFile(l,d):await h.promises.writeFile(l,d,"utf8"),c&&y.info(`${i?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,o={}){let{format:n="auto",overwrite:s=!1,dryRun:r=!1,verbose:c=!1}=o,l=this.normalizePath(e),f=this.normalizePath(F(l)),i=this.pathExists(l);if(i&&!s)return c&&y.info(`Skipping existing file: ${l}`),!1;if(r)return y.info(`[DRY RUN] Would write file: ${l}`),!0;try{h.mkdirSync(f,{recursive:!0})}catch(m){if(m?.code!=="EEXIST")throw m}let u=this._detectFormat(e,n),d;Buffer.isBuffer(t)?d=t:u==="json"&&typeof t=="object"?d=JSON.stringify(t,null,2):d=String(t);try{return Buffer.isBuffer(d)?h.writeFileSync(l,d):h.writeFileSync(l,d,"utf8"),c&&y.info(`${i?"Updated":"Created"} file: ${l}`),!0}catch(m){throw new Error(`Failed to write file: ${l}: ${m instanceof Error?m.message:String(m)}`)}}async copy(e,t,o={}){let{overwrite:n=!1,dryRun:s=!1,verbose:r=!1}=o,c=this.normalizePath(t),l=this.pathExists(c);if(l&&!n)return r&&y.info(`Skipping existing file: ${c}`),!1;if(s)return y.info(`[DRY RUN] Would copy file: ${c}`),!0;let f=this.normalizePath(F(c));try{await h.promises.mkdir(f,{recursive:!0})}catch(i){if(i?.code!=="EEXIST")throw i}try{return await X(async()=>(await h.promises.copyFile(e,c),r&&y.info(`${l?"Updated":"Created"} file: ${c}`),!0),`Failed to copy file from ${e} to ${c}`)}catch{return!1}}copySync(e,t,o={}){let{overwrite:n=!1,dryRun:s=!1,verbose:r=!1}=o,c=this.normalizePath(t),l=this.pathExists(c);if(l&&!n)return r&&y.info(`Skipping existing file: ${c}`),!1;if(s)return y.info(`[DRY RUN] Would copy file: ${c}`),!0;let f=this.normalizePath(F(c));try{h.mkdirSync(f,{recursive:!0})}catch(i){if(i?.code!=="EEXIST")throw i}try{return h.copyFileSync(e,c),r&&y.info(`${l?"Updated":"Created"} file: ${c}`),!0}catch{return!1}}pathExists(e,t=!1){try{return h.existsSync(e)}catch(o){return t||y.error(`Error checking path existence: ${e}`,o),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return h.existsSync(t)||h.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return h.readdirSync(e,t)}catch(o){return this.options.debug&&y.warn(`Failed to read directory: ${e}`,o),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return h.statSync(e)}catch(t){return this.options.debug&&y.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return h.realpathSync(e)}watch(e,t,o){return h.watch(e,t,o)}lstatSync(e){try{return h.lstatSync(e)}catch(t){return this.options.debug&&y.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await h.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{h.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await h.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){h.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return h.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=S(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(C(e)),o=this.getAppRoot(),n=K(o,t),s=this.normalizePath(n);return!s.startsWith("../")&&!s.startsWith("/")}async findFiles(e,t,o={}){let n=this.normalizePath(S(e,t)),s=this.getAppRoot(),r=this.normalizePath(s),c=n.startsWith(r)?n.slice(r.length+1):n,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:_.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([c],{...l,...o})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=_.I18N_PATHS;if(!t)return null;let o=e.replace(t.SOURCE_ROOT+"/",""),n=this.resolveFrameworkPackage("@donotdev/core");if(!n)return null;let s=this.normalizePath(S(n,t.PUBLISHED_ROOT,o)),r=s.replace(/\/[^/]*\*.*$/,"");return this.pathExists(r),s}async _globWithNormalization(e,t){return(await pe(e,t)).map(n=>{let s=typeof n=="string"?n:n.path;return this.normalizePath(s)})}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 o=[...e.framework,...e.consumer];for(let i of o)if(typeof i!="string"||i.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let n=this.getAppRoot(),s=_.getGlobOptionsFor?_.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},r=this.normalizePath(n),c=e.framework.map(i=>{let u=this.normalizePath(i);return u.startsWith(r)?u.slice(r.length+1):u}),l=e.consumer.map(i=>{let u=this.normalizePath(i);return u.startsWith(r)?u.slice(r.length+1):u}),f={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n};try{let i=c.length>0?await this._globWithNormalization(c,f):[],u=await this._globWithNormalization(l,f);return{frameworkFiles:i,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!_.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),o=this.getRepoRoot();if(e==="i18n"&&(!t||t===o))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${o}). Ensure configResolved hook has run before discovery.`);let n=_.getPatternsFor(e),s=this.isMonorepo();if(e==="i18n"){let l=n,f={eager:l.eager.map(i=>i.startsWith("!")?"!"+this.resolveAppPath(i.slice(1)):this.resolveAppPath(i)),lazy:l.lazy.map(i=>i.startsWith("!")?"!"+this.resolveAppPath(i.slice(1)):this.resolveAppPath(i)),framework:{eager:s?(l.framework?.eager||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(i=>this._resolveFrameworkI18nPattern(i))).then(i=>i.filter(Boolean)),lazy:s?(l.framework?.lazy||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(i=>this._resolveFrameworkI18nPattern(i))).then(i=>i.filter(Boolean))},all:[]};return f.all=[...f.eager,...f.lazy,...f.framework.eager,...f.framework.lazy],f}let r=n,c={framework:s?(r.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(r.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return c.all=[...c.consumer,...c.framework],c}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),o=0,n=this.options.maxLevels;for(;o<n;){let s=this.normalizePath(S(t,Z.TOOLING)),r=this.normalizePath(S(t,Z.CORE));if(this.pathExists(s)&&this.pathExists(r))return t;let c=S(t,"apps");if(this.pathExists(c)&&this.statSync(c)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(S(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(F(t))===t)return t;let f=this.normalizePath(F(t));if(f===t)break;t=f,o++}return this.normalizePath(e)}};function T(a={}){let{entry:e="src/index.ts",outDir:t="lib",minify:o=!1,sourcemap:n=!0,platform:s="firebase",workspace:r,bundleWorkspaceDeps:c=!1,importFramework:l=!1,external:f=!1,...i}=a,u=O.getInstance(),d=H(r),m={entryPoints:[e],bundle:!0,platform:"node",target:"node20",format:"esm",outdir:t,outExtension:{".js":".js"},minify:o,sourcemap:n,metafile:!0,logLevel:"info",loader:{".ts":"ts",".tsx":"tsx",".css":"empty"},keepNames:!0,treeShaking:!0,...i};c&&Object.keys(d).length>0&&(m.alias=Object.fromEntries(Object.entries(d).map(([v,p])=>[v,u.normalizePath(p)]))),m.mainFields=["module","main"],m.conditions=["import","module","node"];let $=["fs","path","crypto","util","stream","events","buffer","url","querystring","http","https","zlib","os","child_process","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","perf_hooks","async_hooks"],j=[];if(c)try{let v=r?.root||process.cwd(),p=process.cwd(),g=10;for(let k=0;k<g;k++){let x=u.normalizePath(`${p}/package.json`);if(u.pathExists(x)){let b=u.readSync(x,{format:"json"});if(b&&Array.isArray(b.workspaces)){v=u.normalizePath(p);for(let R of b.workspaces)R==="apps/*"||R==="functions"||!R.includes("*")&&!R.includes("/")&&j.push(R);break}}let E=u.getDirname(p);if(E===p)break;p=E}}catch{}let W={name:"external-node-modules",setup(v){v.onResolve({filter:/^firebase($|\/)/},p=>{if(p.path==="firebase-admin"||p.path.startsWith("firebase-admin/")||p.path==="firebase-functions"||p.path.startsWith("firebase-functions/"))return null;let g;if(r?.type==="dndev"&&r.root)g=u.normalizePath(`${r.root}/packages/core/config/functions/firebase-stub.js`);else{let k=import.meta.url,E=new URL(k).pathname.replace(/^\/([A-Z]:)/i,"$1"),b=u.getDirname(E);g=u.normalizePath(`${b}/firebase-stub.js`)}return{path:g}}),v.onResolve({filter:/.*/},p=>{if(p.kind==="entry-point")return null;if(p.path.match(/@donotdev\/functions\/.+/)&&c&&r?.type==="dndev"){let g=p.path.replace("@donotdev/functions/","");return{path:u.normalizePath(`${r.root}/packages/functions/src/${g}/index.ts`)}}if(p.path==="@donotdev/utils")return r?.type==="dndev"?{path:u.normalizePath(`${r.root}/packages/core/utils/src/server/index.ts`)}:v.resolve("@donotdev/utils/server",{kind:p.kind,resolveDir:p.resolveDir});if(p.path.match(/@donotdev\/utils\/.+/)&&r?.type==="dndev"){let g=p.path.replace("@donotdev/utils/","");return{path:u.normalizePath(`${r.root}/packages/core/utils/src/${g}/index.ts`)}}if(p.path==="@donotdev/supabase")return r?.type==="dndev"?{path:u.normalizePath(`${r.root}/packages/providers/supabase/src/server/index.ts`)}:v.resolve("@donotdev/supabase/server",{kind:p.kind,resolveDir:p.resolveDir});if(p.path==="@donotdev/core")return r?.type==="dndev"?{path:u.normalizePath(`${r.root}/packages/core/server.ts`)}:v.resolve("@donotdev/core/server",{kind:p.kind,resolveDir:p.resolveDir});if(p.path.match(/@donotdev\/core\/.+/)&&c&&r?.type==="dndev"){let g=p.path.replace("@donotdev/core/","");return{path:u.normalizePath(`${r.root}/packages/core/${g}.ts`)}}if(p.path==="firebase-admin"||p.path.startsWith("firebase-admin/")||p.path==="firebase-functions"||p.path.startsWith("firebase-functions/"))return{path:p.path,external:!0};if(p.path.match(/@donotdev\/core\/.+/)&&c&&r?.type==="dndev"){let g=p.path.replace("@donotdev/core/","");return{path:u.normalizePath(`${r.root}/packages/core/${g}.ts`)}}if(p.path.startsWith("@donotdev/")||p.path==="valibot"||p.path.startsWith("valibot/"))return null;if(j.length>0){let g=p.path.split("/")[0];if(j.includes(g))return null}return p.path.startsWith(".")||p.path.startsWith("/")?null:{path:p.path,external:!0}})}};if(m.external=[...$,"firebase-admin","firebase-functions"],m.plugins=[W,...m.plugins||[]],m.define={"process.env.NODE_ENV":JSON.stringify(process.env.NODE_ENV||"production"),...m.define||{}},l&&r.type==="dndev"){let v=r.root,p=u.normalizePath(`${v}/functions/lib`);m.alias={...m.alias,"@donotdev/functions":p}}if(s==="framework"){let v=O.getInstance(),p=r?.root?v.normalizePath(`${r.root}/packages/functions`):process.cwd(),g=v.normalizePath(`${p}/package.json`),k=v.readSync(g,{format:"json"});if(k?.exports){let x={};for(let[,E]of Object.entries(k.exports)){let b=E?.import||E?.default||(typeof E=="string"?E:null);if(!b||!b.endsWith(".ts"))continue;let R=b.replace(/^\.\/src\//,"").replace(/\.ts$/,"");x[R]=b}Object.keys(x).length>0&&(m.entryPoints=x)}}return m}import{readFileSync as N,writeFileSync as B,existsSync as L}from"fs";import"path";var U=["create","get","list","listCard","update","delete"];function Q(a,e=0){let t=" ".repeat(e),o="";for(let[n,s]of Object.entries(a))if(s!=null)if(typeof s=="object"&&!Array.isArray(s))Object.keys(s).length===0?o+=`${t}${n}: {}
|
|
2
2
|
`:o+=`${t}${n}:
|
|
3
3
|
${Q(s,e+1)}`;else if(Array.isArray(s))if(s.length===0)o+=`${t}${n}: []
|
|
4
4
|
`;else{o+=`${t}${n}:
|
|
@@ -17,4 +17,4 @@ ${Q(s,e+1)}`;else if(Array.isArray(s))if(s.length===0)o+=`${t}${n}: []
|
|
|
17
17
|
`)+`
|
|
18
18
|
`)}else B(".env.local",c+r.join(`
|
|
19
19
|
`)+`
|
|
20
|
-
`);return{stripped:r.map(f=>f.split("=")[0].trim()),kept:s.length}}import{writeFileSync as he}from"fs";function me(a={}){let e=
|
|
20
|
+
`);return{stripped:r.map(f=>f.split("=")[0].trim()),kept:s.length}}import{writeFileSync as he}from"fs";function me(a={}){let e=I();return T({...a,platform:"firebase",bundleWorkspaceDeps:!0,importFramework:!0,workspace:e})}async function ge(a,e={}){let{entry:t="src/index.ts",outDir:o="lib",minify:n=process.env.NODE_ENV==="production",sourcemap:s=!0,analyze:r=!1,entryFile:c="src/index.ts",envPath:l=".env",...f}=e;try{let{build:i}=await import("esbuild"),u=me({entry:t,outDir:o,minify:n,sourcemap:s,...f}),d=await i(u);d.errors.length>0&&process.exit(1),d.warnings.length>0;let{yaml:m,staticFunctions:$,crudFunctions:j,autoDetected:W,autoSecrets:v}=M(a,{entryFile:c,envPath:l});he("functions.yaml",m),W.length>0,v.length>0;let{stripped:p}=G(a);if(p.length>0,r&&d.metafile){let{analyzeMetafile:g}=await import("esbuild"),k=await g(d.metafile)}}catch{process.exit(1)}}function se(a={}){let{entry:e="src/index.ts",outDir:t="lib",minify:o=!1,sourcemap:n=!0,platform:s="firebase",...r}=a,c=I();return T({entry:e,outDir:t,minify:o,sourcemap:n,platform:s,workspace:c,...r})}function He(a={}){return se({...a,platform:"framework",bundleWorkspaceDeps:!0})}function Ye(a={}){return se({...a,platform:"firebase",bundleWorkspaceDeps:!0,importFramework:!0})}export{ge as buildFunctions,Ye as createAppFunctionsConfig,se as createFunctionsEsbuildConfig,He as createRootFunctionsConfig,G as filterEnvSecrets,re as generateFunctionsYaml,M as generateFunctionsYamlWithInfo};
|
package/index.d.ts
CHANGED
|
@@ -5577,17 +5577,15 @@ interface UIFieldOptions<T extends string = FieldType> {
|
|
|
5577
5577
|
/** Step value for numeric inputs */
|
|
5578
5578
|
step?: T extends 'number' | 'range' ? number : never;
|
|
5579
5579
|
/**
|
|
5580
|
-
*
|
|
5581
|
-
*
|
|
5582
|
-
*
|
|
5583
|
-
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
*
|
|
5587
|
-
* Use for locale-specific suffixes like "charges comprises" / "all included".
|
|
5588
|
-
* @example `suffix: 'fields.rent_suffix'` → "700€ charges comprises"
|
|
5580
|
+
* i18n key for display formatting. Replaces the raw value in lists/cards/display views.
|
|
5581
|
+
* The formatter calls `t(displayKey, { value })`. Supports i18next array-key fallback.
|
|
5582
|
+
* Use `{{value}}` in key names for dynamic lookup (interpolated before `t()` call).
|
|
5583
|
+
*
|
|
5584
|
+
* @example Single key: `displayKey: 'fields.size_display'` → locale `"{{value}}m²"` → "20m²"
|
|
5585
|
+
* @example Array fallback: `displayKey: ['floor_{{value}}', 'fields.floor_display']`
|
|
5586
|
+
* → tries `floor_4`, falls back to `fields.floor_display`: `"{{value}}th floor"` → "4th floor"
|
|
5589
5587
|
*/
|
|
5590
|
-
|
|
5588
|
+
displayKey?: string | string[];
|
|
5591
5589
|
/** Whether to show value label for range inputs */
|
|
5592
5590
|
showValue?: T extends 'range' ? boolean : never;
|
|
5593
5591
|
/** Field specific options based on field type. Custom types: augment CustomFieldOptionsMap. */
|
|
@@ -7164,7 +7162,7 @@ interface EntityRecommendationsProps {
|
|
|
7164
7162
|
title?: string;
|
|
7165
7163
|
/** Base path for card links. Default: `/${entity.collection}` */
|
|
7166
7164
|
basePath?: string;
|
|
7167
|
-
/** Grid columns — default 3 */
|
|
7165
|
+
/** Grid columns — default `[1,1,3,3]` */
|
|
7168
7166
|
cols?: number | [number, number, number, number];
|
|
7169
7167
|
/** Additional className on wrapper Section */
|
|
7170
7168
|
className?: string;
|
|
@@ -16610,7 +16608,7 @@ declare function clearPartnerCache(): void;
|
|
|
16610
16608
|
declare function getPartnerCacheStatus(): {
|
|
16611
16609
|
authPartnersCached: boolean;
|
|
16612
16610
|
oauthPartnersCached: boolean;
|
|
16613
|
-
authPartners: ("apple" | "discord" | "emailLink" | "facebook" | "github" | "google" | "linkedin" | "microsoft" | "
|
|
16611
|
+
authPartners: ("password" | "apple" | "discord" | "emailLink" | "facebook" | "github" | "google" | "linkedin" | "microsoft" | "reddit" | "spotify" | "twitch" | "twitter" | "yahoo")[] | null;
|
|
16614
16612
|
oauthPartners: ("discord" | "github" | "google" | "linkedin" | "reddit" | "spotify" | "twitch" | "twitter" | "notion" | "slack" | "medium" | "mastodon" | "youtube")[] | null;
|
|
16615
16613
|
};
|
|
16616
16614
|
/**
|
package/next/index.js
CHANGED
|
@@ -1,9 +1,31 @@
|
|
|
1
|
-
var ne={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},We={available:["auth","oauth","billing","crud"],packageNames:{auth:"@donotdev/auth",oauth:"@donotdev/oauth",billing:"@donotdev/billing",crud:"@donotdev/crud"},hooks:{auth:["useAuth"],oauth:["useOAuth","useOAuthPartner","useOAuthConnection"],billing:["useStripeBilling","useStripeCheckout"],crud:["useCrud","useCrudCollection"]}};var I={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},X={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ae={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ae={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},he={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"},F={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:[`${he.SOURCE_EAGER}/*_*.json`],lazy:[`${he.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},fe={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},Be=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var _e={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)/}},ie={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},Ee=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ge={base:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore}};function He(a,e=null){let t=F[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function de(a){return Ge[a]||Ge.base}import*as m from"node:fs";import"node:fs";import{createRequire as Vt}from"node:module";import{resolve as me,join as W,dirname as Z,relative as Ve,normalize as Jt,sep as Je,extname as qt}from"node:path";import"node:url";import Yt from"fast-glob";var se={getGlobOptionsFor:de||void 0,SCAN_PATTERNS:F||void 0,getPatternsFor:He||void 0,I18N_PATHS:he||void 0},S={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function qe(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Ye={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"},y=class a{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,a._instance=this}normalizePath(e){if(!e)return"";try{return Jt(e).split(Je).join("/")}catch{return String(e).split(Je).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Ve(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(Z(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Vt(W(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let n=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(n)){let c=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(c))return c}if(n==="firebase"){let c=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(c))return c}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=me(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=me(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=me(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=m.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:qt(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await m.promises.readFile(e);let n=await m.promises.readFile(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&S.warn(`Failed to read file: ${e}`,n),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return m.readFileSync(e);let n=m.readFileSync(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&S.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:i=!1}=s,c=this.normalizePath(e),p=this.normalizePath(Z(c)),l=this.pathExists(c);if(l&&!o)return i&&S.info(`Skipping existing file: ${c}`),!1;if(n)return S.info(`[DRY RUN] Would write file: ${c}`),!0;try{await m.promises.mkdir(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return await qe(async()=>(Buffer.isBuffer(h)?await m.promises.writeFile(c,h):await m.promises.writeFile(c,h,"utf8"),i&&S.info(`${l?"Updated":"Created"} file: ${c}`),!0),`Failed to write file: ${c}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:i=!1}=s,c=this.normalizePath(e),p=this.normalizePath(Z(c)),l=this.pathExists(c);if(l&&!o)return i&&S.info(`Skipping existing file: ${c}`),!1;if(n)return S.info(`[DRY RUN] Would write file: ${c}`),!0;try{m.mkdirSync(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return Buffer.isBuffer(h)?m.writeFileSync(c,h):m.writeFileSync(c,h,"utf8"),i&&S.info(`${l?"Updated":"Created"} file: ${c}`),!0}catch(g){throw new Error(`Failed to write file: ${c}: ${g instanceof Error?g.message:String(g)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,i=this.normalizePath(t),c=this.pathExists(i);if(c&&!r)return n&&S.info(`Skipping existing file: ${i}`),!1;if(o)return S.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{await m.promises.mkdir(p,{recursive:!0})}catch(l){if(l?.code!=="EEXIST")throw l}try{return await qe(async()=>(await m.promises.copyFile(e,i),n&&S.info(`${c?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,i=this.normalizePath(t),c=this.pathExists(i);if(c&&!r)return n&&S.info(`Skipping existing file: ${i}`),!1;if(o)return S.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{m.mkdirSync(p,{recursive:!0})}catch(l){if(l?.code!=="EEXIST")throw l}try{return m.copyFileSync(e,i),n&&S.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return m.existsSync(e)}catch(s){return t||S.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return m.existsSync(t)||m.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return m.readdirSync(e,t)}catch(s){return this.options.debug&&S.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return m.statSync(e)}catch(t){return this.options.debug&&S.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return m.realpathSync(e)}watch(e,t,s){return m.watch(e,t,s)}lstatSync(e){try{return m.lstatSync(e)}catch(t){return this.options.debug&&S.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await m.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{m.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await m.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){m.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return m.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=W(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(me(e)),s=this.getAppRoot(),r=Ve(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(W(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),i=r.startsWith(n)?r.slice(n.length+1):r,c={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],{...c,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=se.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(W(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await Yt(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let l of s)if(typeof l!="string"||l.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=se.getGlobOptionsFor?se.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),i=e.framework.map(l=>{let u=this.normalizePath(l);return u.startsWith(n)?u.slice(n.length+1):u}),c=e.consumer.map(l=>{let u=this.normalizePath(l);return u.startsWith(n)?u.slice(n.length+1):u}),p={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let l=i.length>0?await this._globWithNormalization(i,p):[],u=await this._globWithNormalization(c,p);return{frameworkFiles:l,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!se.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=se.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let c=r,p={eager:c.eager.map(l=>l.startsWith("!")?"!"+this.resolveAppPath(l.slice(1)):this.resolveAppPath(l)),lazy:c.lazy.map(l=>l.startsWith("!")?"!"+this.resolveAppPath(l.slice(1)):this.resolveAppPath(l)),framework:{eager:o?(c.framework?.eager||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):await Promise.all((c.framework?.eager||[]).map(l=>this._resolveFrameworkI18nPattern(l))).then(l=>l.filter(Boolean)),lazy:o?(c.framework?.lazy||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):await Promise.all((c.framework?.lazy||[]).map(l=>this._resolveFrameworkI18nPattern(l))).then(l=>l.filter(Boolean))},all:[]};return p.all=[...p.eager,...p.lazy,...p.framework.eager,...p.framework.lazy],p}let n=r,i={framework:o?(n.framework||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):[],consumer:(n.consumer||[]).map(c=>this.resolveAppPath(c)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(W(t,Ye.TOOLING)),n=this.normalizePath(W(t,Ye.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let i=W(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let c=this.normalizePath(W(t,"package.json"));if(this.pathExists(c)&&this.normalizePath(Z(t))===t)return t;let p=this.normalizePath(Z(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function Ke({logger:a,debug:e=!1}={}){let t=y.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):a&&a.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&a&&a.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let n=t.resolveRepoPath("apps");if(t.pathExists(n))try{let i=process.cwd(),c=t.normalizePath(i);if(c.includes("/apps/")){let p=c.indexOf("/apps/"),u=c.substring(p+6).split("/")[0];if(u){let h=t.resolveRepoPath(`apps/${u}`),g=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(g)&&(r=h,t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}var Xe=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,B=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{..._e.selectors,...this.options.customPatterns?.selectors},themes:{..._e.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(n=>n.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((n,i)=>{let c=n.replace(/[^a-zA-Z0-9]/g,"");return c?i===0?c.toLowerCase():c.charAt(0).toUpperCase()+c.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,n=this.pathResolver.normalizePath(t),i=this._stripComments(e),c=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=c.exec(i))!==null;){let[,p,l,u]=o;if(!p||!u)continue;let h=l.match(this.patterns.themes.themeIcon),g=l.match(this.patterns.themes.themeIsDark),d={name:p,displayName:u,isDark:g?g[1]==="1":!1,meta:{icon:h?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(d),s.themes.set(p,{name:p,displayName:u,isDark:d.isDark,file:n,variables:new Set,meta:d.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${n}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Xe.lastIndex=0;(r=Xe.exec(t))!==null;){let o=r[1];o&&o.trim()&&s.add(o.trim())}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let n=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];n&&t.push(`Theme class "${n}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let n=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:n}}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||"")}};import*as _ from"@clack/prompts";var D={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 Kt(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function T(a,e){return Kt()?`${e}${a}${D.reset}`:a}function x(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=y.getInstance(),i=null;if(o){let l=n.resolveAppPath(r);n.pathExists(l)||n.mkdir(l),i=n.resolveAppPath(`${r}/${a.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${a} Log Started at ${new Date().toISOString()} ===
|
|
1
|
+
var ne={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},We={available:["auth","oauth","billing","crud"],packageNames:{auth:"@donotdev/auth",oauth:"@donotdev/oauth",billing:"@donotdev/billing",crud:"@donotdev/crud"},hooks:{auth:["useAuth"],oauth:["useOAuth","useOAuthPartner","useOAuthConnection"],billing:["useStripeBilling","useStripeCheckout"],crud:["useCrud","useCrudCollection"]}};var C={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},U={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ae={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ae={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},he={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"},F={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:[`${he.SOURCE_EAGER}/*_*.json`],lazy:[`${he.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},fe={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},Be=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var _e={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)/}},ie={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},Ee=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ge={base:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore}};function He(a,e=null){let t=F[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function de(a){return Ge[a]||Ge.base}import*as m from"node:fs";import"node:fs";import{createRequire as Vt}from"node:module";import{resolve as me,join as B,dirname as Z,relative as Ve,normalize as Jt,sep as Je,extname as qt}from"node:path";import"node:url";import Yt from"fast-glob";var se={getGlobOptionsFor:de||void 0,SCAN_PATTERNS:F||void 0,getPatternsFor:He||void 0,I18N_PATHS:he||void 0},S={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function qe(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Ye={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"},y=class a{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,a._instance=this}normalizePath(e){if(!e)return"";try{return Jt(e).split(Je).join("/")}catch{return String(e).split(Je).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Ve(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(Z(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Vt(B(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let n=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(n)){let c=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(c))return c}if(n==="firebase"){let c=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(c))return c}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=me(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=me(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=me(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=m.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:qt(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await m.promises.readFile(e);let n=await m.promises.readFile(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&S.warn(`Failed to read file: ${e}`,n),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return m.readFileSync(e);let n=m.readFileSync(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&S.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:i=!1}=s,c=this.normalizePath(e),p=this.normalizePath(Z(c)),l=this.pathExists(c);if(l&&!o)return i&&S.info(`Skipping existing file: ${c}`),!1;if(n)return S.info(`[DRY RUN] Would write file: ${c}`),!0;try{await m.promises.mkdir(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return await qe(async()=>(Buffer.isBuffer(h)?await m.promises.writeFile(c,h):await m.promises.writeFile(c,h,"utf8"),i&&S.info(`${l?"Updated":"Created"} file: ${c}`),!0),`Failed to write file: ${c}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:i=!1}=s,c=this.normalizePath(e),p=this.normalizePath(Z(c)),l=this.pathExists(c);if(l&&!o)return i&&S.info(`Skipping existing file: ${c}`),!1;if(n)return S.info(`[DRY RUN] Would write file: ${c}`),!0;try{m.mkdirSync(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return Buffer.isBuffer(h)?m.writeFileSync(c,h):m.writeFileSync(c,h,"utf8"),i&&S.info(`${l?"Updated":"Created"} file: ${c}`),!0}catch(g){throw new Error(`Failed to write file: ${c}: ${g instanceof Error?g.message:String(g)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,i=this.normalizePath(t),c=this.pathExists(i);if(c&&!r)return n&&S.info(`Skipping existing file: ${i}`),!1;if(o)return S.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{await m.promises.mkdir(p,{recursive:!0})}catch(l){if(l?.code!=="EEXIST")throw l}try{return await qe(async()=>(await m.promises.copyFile(e,i),n&&S.info(`${c?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,i=this.normalizePath(t),c=this.pathExists(i);if(c&&!r)return n&&S.info(`Skipping existing file: ${i}`),!1;if(o)return S.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{m.mkdirSync(p,{recursive:!0})}catch(l){if(l?.code!=="EEXIST")throw l}try{return m.copyFileSync(e,i),n&&S.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return m.existsSync(e)}catch(s){return t||S.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return m.existsSync(t)||m.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return m.readdirSync(e,t)}catch(s){return this.options.debug&&S.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return m.statSync(e)}catch(t){return this.options.debug&&S.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return m.realpathSync(e)}watch(e,t,s){return m.watch(e,t,s)}lstatSync(e){try{return m.lstatSync(e)}catch(t){return this.options.debug&&S.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await m.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{m.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await m.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){m.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return m.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=B(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(me(e)),s=this.getAppRoot(),r=Ve(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(B(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),i=r.startsWith(n)?r.slice(n.length+1):r,c={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],{...c,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=se.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(B(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await Yt(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let l of s)if(typeof l!="string"||l.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=se.getGlobOptionsFor?se.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),i=e.framework.map(l=>{let u=this.normalizePath(l);return u.startsWith(n)?u.slice(n.length+1):u}),c=e.consumer.map(l=>{let u=this.normalizePath(l);return u.startsWith(n)?u.slice(n.length+1):u}),p={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let l=i.length>0?await this._globWithNormalization(i,p):[],u=await this._globWithNormalization(c,p);return{frameworkFiles:l,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!se.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=se.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let c=r,p={eager:c.eager.map(l=>l.startsWith("!")?"!"+this.resolveAppPath(l.slice(1)):this.resolveAppPath(l)),lazy:c.lazy.map(l=>l.startsWith("!")?"!"+this.resolveAppPath(l.slice(1)):this.resolveAppPath(l)),framework:{eager:o?(c.framework?.eager||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):await Promise.all((c.framework?.eager||[]).map(l=>this._resolveFrameworkI18nPattern(l))).then(l=>l.filter(Boolean)),lazy:o?(c.framework?.lazy||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):await Promise.all((c.framework?.lazy||[]).map(l=>this._resolveFrameworkI18nPattern(l))).then(l=>l.filter(Boolean))},all:[]};return p.all=[...p.eager,...p.lazy,...p.framework.eager,...p.framework.lazy],p}let n=r,i={framework:o?(n.framework||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):[],consumer:(n.consumer||[]).map(c=>this.resolveAppPath(c)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(B(t,Ye.TOOLING)),n=this.normalizePath(B(t,Ye.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let i=B(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let c=this.normalizePath(B(t,"package.json"));if(this.pathExists(c)&&this.normalizePath(Z(t))===t)return t;let p=this.normalizePath(Z(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function Ke({logger:a,debug:e=!1}={}){let t=y.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):a&&a.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&a&&a.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let n=t.resolveRepoPath("apps");if(t.pathExists(n))try{let i=process.cwd(),c=t.normalizePath(i);if(c.includes("/apps/")){let p=c.indexOf("/apps/"),u=c.substring(p+6).split("/")[0];if(u){let h=t.resolveRepoPath(`apps/${u}`),g=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(g)&&(r=h,t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}var Xe=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,H=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{..._e.selectors,...this.options.customPatterns?.selectors},themes:{..._e.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(n=>n.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((n,i)=>{let c=n.replace(/[^a-zA-Z0-9]/g,"");return c?i===0?c.toLowerCase():c.charAt(0).toUpperCase()+c.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,n=this.pathResolver.normalizePath(t),i=this._stripComments(e),c=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=c.exec(i))!==null;){let[,p,l,u]=o;if(!p||!u)continue;let h=l.match(this.patterns.themes.themeIcon),g=l.match(this.patterns.themes.themeIsDark),d={name:p,displayName:u,isDark:g?g[1]==="1":!1,meta:{icon:h?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(d),s.themes.set(p,{name:p,displayName:u,isDark:d.isDark,file:n,variables:new Set,meta:d.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${n}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Xe.lastIndex=0;(r=Xe.exec(t))!==null;){let o=r[1];o&&o.trim()&&s.add(o.trim())}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let n=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];n&&t.push(`Theme class "${n}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let n=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:n}}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||"")}};import*as _ from"@clack/prompts";var O={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 Kt(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function T(a,e){return Kt()?`${e}${a}${O.reset}`:a}function k(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=y.getInstance(),i=null;if(o){let l=n.resolveAppPath(r);n.pathExists(l)||n.mkdir(l),i=n.resolveAppPath(`${r}/${a.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${a} Log Started at ${new Date().toISOString()} ===
|
|
2
2
|
`;n.writeSync(i,u)}let c=(l,u,h)=>{if(i){let g=new Date().toISOString(),d=h.length>0?" "+h.map($=>typeof $=="object"?JSON.stringify($,null,2):String($)).join(" "):"",P=`${g} [${l}] ${u}${d}
|
|
3
|
-
`;n.appendFile(i,P)}},p=(l,u)=>{if(u.length===0)return l;let h=u.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${l} ${h}`};return{debug:(l,...u)=>{e&&(o?c("DEBUG",l,u):_.log.message(T(p(l,u),
|
|
4
|
-
`],o=new Set;for(let[n,i]of e){let c=a.resolveFrameworkPackage(`@fontsource/${n}`);if(!c){s.debug(`@fontsource/${n} not found`);continue}let p=a.resolvePath(`${i}.css`,c),l=a.readSync(p,{format:"text"});if(!l){s.debug(`Missing: @fontsource/${n}/${i}.css`);continue}let u=l.replace(it,(h,g)=>{let d=a.resolvePath(`files/${g}`,c);if(!a.pathExists(d))return s.warn(`Font file missing: ${d} \u2014 dropping from CSS`),"url(data:,)";if(!o.has(g)){let $=a.resolvePath(g,t);a.copySync(d,$,{overwrite:!0}),o.add(g)}return`url(/${ve}/${g})`});r.push(u)}return{cssChunks:r,copiedFiles:o}}function
|
|
5
|
-
|
|
6
|
-
`)),t.debug(`Font copy: wrote ${Ne} (${p.size} font files copied)`)}function lt(){let a=y.getInstance(),e=a.resolveAppPath(`public/${Ne}`),t=a.resolveAppPath(`public/${ve}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var
|
|
3
|
+
`;n.appendFile(i,P)}},p=(l,u)=>{if(u.length===0)return l;let h=u.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${l} ${h}`};return{debug:(l,...u)=>{e&&(o?c("DEBUG",l,u):_.log.message(T(p(l,u),O.gray)))},verbose:(l,...u)=>{t&&(o?c("VERBOSE",l,u):_.log.message(p(l,u)))},info:(l,...u)=>{o?c("INFO",l,u):_.log.info(T(p(l,u),O.brightCyan))},warn:(l,...u)=>{e&&o?c("WARN",l,u):_.log.warn(T(p(l,u),O.brightYellow))},error:(l,...u)=>{e&&o?c("ERROR",l,u):_.log.error(T(p(l,u),O.brightRed))},success:(l,...u)=>{e&&o?c("SUCCESS",l,u):_.log.success(T(p(l,u),O.brightGreen))},when:(l,u="debug")=>(h,...g)=>{if(l){let d=p(h,g);switch(u){case"verbose":t&&(_.log.message(d),c("VERBOSE",h,g));break;case"info":_.log.info(T(d,O.brightCyan)),c("INFO",h,g);break;case"warn":_.log.warn(T(d,O.brightYellow)),c("WARN",h,g);break;case"error":_.log.error(T(d,O.brightRed)),c("ERROR",h,g);break;case"success":_.log.success(T(d,O.brightGreen)),c("SUCCESS",h,g);break;default:e&&(_.log.message(T(d,O.gray)),c("DEBUG",h,g))}}},getLogFilePath:()=>i}}var Xt=3,Ze="dndev-font-preloads.json";async function Zt(a,e){let t=k("font-preload-next",e,!1);try{let s=await a.resolvePatterns("css"),{consumerFiles:r}=await a.resolveFiles(s,"css");if(!r?.length)return[ie.Inter];let o=new H(a,{debug:e,logger:t}),n=new Set;for(let c of r)try{let p=await a.read(c,{format:"text"});p&&o.extractFontFamilies(p).forEach(l=>n.add(l))}catch{}if(n.size===0)return[ie.Inter];let i=new Set;for(let c of n){let p=ie[c];p&&i.add(p)}return Array.from(i)}catch{return[ie.Inter]}}function Qe({pathResolver:a,debug:e=!1}){let t=k("font-preload-next",e,!1);return{apply(s){s.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(r,o)=>{if(r.compiler.isChild()||r.compiler.name?.includes("server"))return o();try{if(!a.getAppRoot())return o();let c=await Zt(a,e),p=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",l=[];for(let[g]of Object.entries(r.assets)){if(!g.endsWith(".woff2")&&!g.endsWith(".woff"))continue;let d=g.toLowerCase();if(c.some(P=>d.includes(P))){let P=p?`${p}/${g}`:`/${g}`;if(l.push({href:P,type:"font/woff2"}),l.length>=Xt)break}}let u=a.resolveAppPath("public");if(!a.pathExists(u))try{a.ensureDirSync(u)}catch(g){return t.debug(`Font preload: could not create public dir: ${g?.message}`),o()}let h=a.resolvePath(Ze,u);a.writeSync(h,JSON.stringify(l,null,0),{overwrite:!0}),t.debug(`Font preload: wrote ${l.length} entries to ${Ze}`)}catch(i){t.debug(`Font preload manifest: ${i?.message}`)}o()})}}}function et({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?a({resolve:s}):a,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var tt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Qt(a){return(e,t)=>{tt[e]&&(e=tt[e]);let s=a.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),n=a.resolveFrameworkPackage(r,t);if(n){if(o){let c=a.resolvePath(o,n);if(a.pathExists(c))return c;let p=c+".css";if(a.pathExists(p))return p}let i=a.resolvePath("index.css",n);if(a.pathExists(i))return i}}return a.resolvePath(e,t)}}async function es(){let[a,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=y.getInstance();return et({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:Qt(s)})}function st(){try{let a=y.getInstance(),e=a.resolveAppPath("package.json"),t=a.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(o=>{let n=s[o];return n&&typeof n=="string"&&n.startsWith("workspace:")}).filter(o=>!fe.buildTimePackages.includes(o)).sort()}catch{return[]}}function G(a){return a&&typeof a=="object"&&!Array.isArray(a)}var rt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function ot({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],logger:r,debug:o}){return(n,i)=>{let{dev:c,isServer:p,webpack:l}=i;c&&!p&&(n.infrastructureLogging={level:"error"},n.stats={...n.stats,logging:"error",loggingTrace:!1},n.ignoreWarnings=[...n.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let u=n.module?.rules?.find(h=>h.test?.test?.(".svg"));u&&(u.exclude=/\.svg$/i),n.module=n.module||{},n.module.rules=n.module.rules||[],n.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),n.resolve=n.resolve||{},n.resolve.alias={...n.resolve.alias,...rt},l?.IgnorePlugin&&n.plugins.push(new l.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=y.getInstance();n.plugins.push(Qe({pathResolver:h,debug:o}))}catch(h){r.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(r.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),r.info(`\u2705 Including features: ${t.join(", ")}`),n.externals=n.externals||[],Array.isArray(n.externals))n.externals.push(...e);else{let h=n.externals;n.externals=(g,d,P)=>e.includes(d)?P(null,"commonjs "+d):typeof h=="function"?h(g,d,P):P()}if(s.length>0&&l?.NormalModuleReplacementPlugin){let g=y.getInstance().getEmptyCjsModulePath(),d=s.map($=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),P=new RegExp(`^(${d.join("|")})(\\/|$)`);n.plugins.push(new l.NormalModuleReplacementPlugin(P,g)),o&&r.debug(`Aliased ${s.length} missing optional deps to empty module`)}return a?a(n,i):n}}function nt({originalRewrites:a,handlers:e,logger:t}){return async function(){try{let s=a?await a():[],o=e.filter(i=>i?.getAPIRewrites).map(i=>i.getAPIRewrites()).reduce((i,c)=>(c?.beforeFiles&&i.beforeFiles.push(...c.beforeFiles),c?.afterFiles&&i.afterFiles.push(...c.afterFiles),c?.fallback&&i.fallback.push(...c.fallback),i),{beforeFiles:[],afterFiles:[],fallback:[]}),n={beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...o.fallback]};return n.beforeFiles.length===0&&n.afterFiles.length===0&&n.fallback.length===0?null:n}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),null}}}function at({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:i,discoveredPackages:c,webpackConfig:p,rewritesConfig:l,missingOptionalDeps:u,pathResolver:h,env:g,logger:d}){let P=i?.output==="export",V=i?.distDir||".next";return{transpilePackages:[...c,...u||[]],...G(i)?i:(d.warn("restNextConfig is not a plain object:",i),{}),serverExternalPackages:(i?.serverExternalPackages||i?.serverComponentsExternalPackages||[]).filter(x=>!x.startsWith("@donotdev/")&&!u?.includes(x)),turbopack:{...i?.turbopack||{},root:i?.turbopack?.root||h.getRepoRoot(),resolveAlias:{...i?.turbopack?.resolveAlias||{},...rt,...u?.length>0?Object.fromEntries(u.flatMap(x=>[[x,"@donotdev/core/empty"],[`${x}/*`,"@donotdev/core/empty"]])):{}}},distDir:V,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...G(a)?a:(d.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...G(e)?e:(d.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...G(t)?t:(d.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...G(s)?s:(d.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...G(r)?r:(d.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...G(o)?o:(d.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...G(n)?n:(d.warn("serverShimConfig returned non-object:",n),{}),webpack:p,...P?{}:{rewrites:async()=>await l()||void 0},env:g,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var ve="fonts",Ne="dndev-fonts.css",ts=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,it=/url\(\.\/files\/([^)]+)\)/g;function ss(a,e){let t=a.resolvePath("src/dndev.css",e),s=a.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=ts.exec(s))!==null;)r.push([o[1],o[2]]);return r}function rs(a,e,t,s){let r=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
4
|
+
`],o=new Set;for(let[n,i]of e){let c=a.resolveFrameworkPackage(`@fontsource/${n}`);if(!c){s.debug(`@fontsource/${n} not found`);continue}let p=a.resolvePath(`${i}.css`,c),l=a.readSync(p,{format:"text"});if(!l){s.debug(`Missing: @fontsource/${n}/${i}.css`);continue}let u=l.replace(it,(h,g)=>{let d=a.resolvePath(`files/${g}`,c);if(!a.pathExists(d))return s.warn(`Font file missing: ${d} \u2014 dropping from CSS`),"url(data:,)";if(!o.has(g)){let $=a.resolvePath(g,t);a.copySync(d,$,{overwrite:!0}),o.add(g)}return`url(/${ve}/${g})`});r.push(u)}return{cssChunks:r,copiedFiles:o}}var os=/@font-face\s*\{[^}]*\}/g;function ns(a,e,t,s){let r=a.resolvePath("dist/dndev.css",e),o=a.readSync(r,{format:"text"});if(!o)return s.debug("dist/dndev.css not found in @donotdev/ui"),{cssChunks:[],copiedFiles:new Set};let n=o.match(os);if(!n||n.length===0)return s.debug("No @font-face blocks found in dist/dndev.css"),{cssChunks:[],copiedFiles:new Set};let i=a.resolvePath("dist/files",e),c=new Set;return{cssChunks:[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
5
|
+
`,...n.map(u=>u.replace(it,(h,g)=>{let d=a.resolvePath(g,i);if(!a.pathExists(d))return s.warn(`Font file missing: ${d} \u2014 dropping from CSS`),"url(data:,)";if(!c.has(g)){let $=a.resolvePath(g,t);a.copySync(d,$,{overwrite:!0}),c.add(g)}return`url(/${ve}/${g})`}))],copiedFiles:c}}function ct({debug:a=!1,force:e=!1}={}){let t=k("font-copy",a,!1),s=y.getInstance(),r=s.resolveAppPath(`public/${Ne}`);if(!e&&s.pathExists(r)){t.debug("dndev-fonts.css already exists, skipping font copy");return}let o=s.resolveFrameworkPackage("@donotdev/ui");if(!o){t.debug("@donotdev/ui not found, skipping font copy");return}let n=s.resolveAppPath(`public/${ve}`);s.ensureDir(n);let i=ss(s,o),c,p;if(i.length>0?(t.debug(`Monorepo mode: ${i.length} @fontsource imports found`),{cssChunks:c,copiedFiles:p}=rs(s,i,n,t)):(t.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:c,copiedFiles:p}=ns(s,o,n,t)),p.size===0){t.debug("No font files found to copy");return}s.writeSync(r,c.join(`
|
|
6
|
+
`)),t.debug(`Font copy: wrote ${Ne} (${p.size} font files copied)`)}function lt(){let a=y.getInstance(),e=a.resolveAppPath(`public/${Ne}`),t=a.resolveAppPath(`public/${ve}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var as=["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"],is="dndev-config-",pt=".dndev-build";function cs(a){if(!a)return!1;let e=y.getInstance(),t=e.resolveAppPath(pt),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function ls(a){if(!a)return;let e=y.getInstance(),t=e.resolveAppPath(pt),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s)}catch{}}function Fe(a,e){if(!a)return;let t=y.getInstance();for(let r of as){let o=t.resolveAppPath(r);if(t.pathExists(o))try{t.removeSync(o),e.debug(`Cleaned: ${r}`)}catch{}}lt();let s=t.resolveAppPath("src/config");if(t.pathExists(s))try{let r=t.readdirSync(s);for(let o of r)if(o.startsWith(is)&&o.endsWith(".js"))try{let n=t.resolvePath(o,s);t.removeSync(n),e.debug(`Cleaned: src/config/${o}`)}catch{}}catch{}}async function Ce({routeHandler:a,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:o},n){let i=a?.pathResolver;if(!i)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let c=i.getAppRoot(),p=i.getRepoRoot();if(!c||c===p){n.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(d=>setTimeout(d,0));let g=i.getAppRoot();if(!g||g===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(cs(c)){n.debug("Discoveries already completed this build, skipping");return}let l=Date.now();if(a)try{n.info("\u{1F50D} Starting route discovery...");let d=(await a.generateFiles())?.routes?.length||0;n.info(`\u2705 Routes generated: ${d} routes found`),d===0&&n.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(g){throw n.error(`\u274C Route generation failed: ${g.message}`),g.stack&&n.error(`Stack: ${g.stack}`),g}else n.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let u=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:o}];for(let{name:g,handler:d}of u)try{await d.generateFiles()}catch(P){n.debug(`${g} generation failed: ${P.message}`)}try{ps(i,n)}catch(g){n.debug(`Env config generation failed (non-critical): ${g.message}`)}try{ct()}catch(g){n.debug(`Font copy failed (non-critical): ${g.message}`)}let h=Date.now()-l;n.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`),ls(c)}function ps(a,e){let t={};for(let[n,i]of Object.entries(process.env))n.startsWith("NEXT_PUBLIC_")&&i!==void 0&&(t[n]=i);let s=`// Auto-generated DnDev env config by @donotdev/config
|
|
7
|
+
// Generated at: ${new Date().toISOString()}
|
|
8
|
+
// Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
|
|
9
|
+
|
|
10
|
+
const envConfig = ${JSON.stringify(t,null,2)};
|
|
11
|
+
|
|
12
|
+
// Populate unified DnDev config for runtime access (universal CSR/SSR)
|
|
13
|
+
if (typeof globalThis !== 'undefined') {
|
|
14
|
+
if (!globalThis._DNDEV_CONFIG_) {
|
|
15
|
+
globalThis._DNDEV_CONFIG_ = {
|
|
16
|
+
platform: 'nextjs',
|
|
17
|
+
mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development',
|
|
18
|
+
version: '1.0.0',
|
|
19
|
+
context: typeof window !== 'undefined' ? 'client' : 'server',
|
|
20
|
+
timestamp: Date.now(),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
globalThis._DNDEV_CONFIG_.${C.env} = envConfig;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Export for compatibility
|
|
27
|
+
export default envConfig;
|
|
28
|
+
`,r=a.resolveAppPath(U.next.configEnv);a.writeSync(r,s);let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}async function ut(a,e,t){if(t)return!1;try{let s=await a.getDiscoveryData();return s?.copiedAssets?.length>0&&e.info(`\u{1F4E6} Copied ${s.copiedAssets.length} assets from framework`),!0}catch(s){return e.debug(`Asset discovery failed (non-critical): ${s.message}`),!1}}var ce={debug:!1,verbose:process.env.CI!=="true",features:{},generateManifest:!0,routes:{disabled:!1,debug:!1,routingMode:"app",generateMiddleware:!0},themes:{debug:!1},i18n:{debug:!1,fallbackLanguage:"en"},assets:{debug:!1},pwa:{debug:!1},seo:{disabled:!1,debug:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0,debug:!1},discovery:{debug:!1,verbose:!1,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"}};function gt(a,e){let t={...a};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=gt(a[s]||{},e[s]):t[s]=e[s]}),t}function ht(a={}){return gt(ce,a)}function ft(a){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:n={},seo:i={},serverShim:c={},discovery:p={},generateManifest:l,debug:u,verbose:h,...g}=a,d=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:l,debug:u,verbose:h,mode:d,isDev:d==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:n,seoOptions:i,serverShimOptions:c,discoveryOptions:p,nextConfigOptions:g}}var A=class{constructor(e,t={}){this.options={...t,...this.getHandlerDefaults()},this.logger=k(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=y.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...ce.discovery,...this.options};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}createNextConfig(){return(e={})=>(this.options.debug&&this.logger.debug(`${this.getHandlerName()} handler initialized`),{...e,webpack:(t,s)=>{let{dev:r,isServer:o,webpack:n}=s;return this.applyViteIgnorePlugin(t,n),this._generateFiles(),e.webpack?e.webpack(t,s):t},rewrites:async function(){try{let t=e.rewrites?await e.rewrites():[],s=this.getAPIRewrites();return this.mergeRewrites(t,s)}catch(t){return this.logger.error(`${this.getHandlerName()} handler failed to merge rewrites: ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`),[]}}.bind(this)})}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let t=this.getHandlerName().toLowerCase(),s=U.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!s)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let r=this.generateConfigContent(e);this.writeGeneratedFile(s,r,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),s=C[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
7
29
|
// Generated at: ${new Date().toISOString()}
|
|
8
30
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
9
31
|
|
|
@@ -25,7 +47,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
25
47
|
|
|
26
48
|
// Export for compatibility
|
|
27
49
|
export default ${t}Config;
|
|
28
|
-
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var C=class a{constructor(e,t={}){if(this.constructor===a)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=x(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let n=Date.now()-t;return this.logger.debug(`Discovery completed in ${n}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var be=class extends C{constructor(e,t={}){super(e,{assets:F.assets.fallback,assetPatterns:F.assets.patterns,frameworkPackage:Ae.package,assetsPath:Ae.assetsPath,modernFormats:F.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let n=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(n=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:c}=e,p=await this._processAssetFiles(c),l=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...l,logoSvgContent:u},copiedAssets:s,generatedAssets:n,pwaIcons:this._extractPWAIcons(p)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(o=>o.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",o=r.match(/(\d+)x(\d+)/),n=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:n,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let n=`/${e}.${o}`;if(s.includes(n))return n}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(ae.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let o of this.options.assets)await this._ensureAsset(o,r,s)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${ae.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let o=s.split("/").pop()||s.split("\\").pop(),n=this._analyzeAsset(o,r.size);n&&t.push(n)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(n=>this._matchesPattern(e,n))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let o=`/${e}.${r}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${ae.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(ae.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],n=[],i=[];try{let c=await this.pathResolver.read(t,{format:"text"});if(!c)return{generated:[],skipped:[...o,...r].map(l=>l.name),error:"Failed to read logo.svg"};for(let l of o){let u=`${s}/${l.name}`;if(this.pathResolver.pathExists(u)){i.push(l.name);continue}try{await this.pathResolver.write(`public/${l.name}`,c),n.push(l.name)}catch(h){this.logger.debug(`Failed to copy ${l.name}: ${h.message}`),i.push(l.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(l=>l.name));else for(let l of r){let u=`${s}/${l.name}`;if(this.pathResolver.pathExists(u)){i.push(l.name);continue}try{let h=p.default(t).resize(l.size,l.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;l.format==="ico"?g=await h.toFormat("png").toBuffer():g=await h.toFormat(l.format).toBuffer(),await this.pathResolver.write(`public/${l.name}`,g),n.push(l.name)}catch(h){this.logger.debug(`Failed to generate ${l.name}: ${h.message}`),i.push(l.name)}}return{generated:n,skipped:i,error:null}}catch(c){return this.logger.debug(`Asset generation failed: ${c.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:c.message}}}};var Oe={data:null},De=class extends A{constructor(e={}){super(be,e)}getHandlerDefaults(){return{manifestPath:X.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
50
|
+
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var D=class a{constructor(e,t={}){if(this.constructor===a)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=k(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let n=Date.now()-t;return this.logger.debug(`Discovery completed in ${n}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var be=class extends D{constructor(e,t={}){super(e,{assets:F.assets.fallback,assetPatterns:F.assets.patterns,frameworkPackage:Ae.package,assetsPath:Ae.assetsPath,modernFormats:F.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let n=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(n=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:c}=e,p=await this._processAssetFiles(c),l=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...l,logoSvgContent:u},copiedAssets:s,generatedAssets:n,pwaIcons:this._extractPWAIcons(p)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(o=>o.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",o=r.match(/(\d+)x(\d+)/),n=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:n,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let n=`/${e}.${o}`;if(s.includes(n))return n}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(ae.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let o of this.options.assets)await this._ensureAsset(o,r,s)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${ae.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let o=s.split("/").pop()||s.split("\\").pop(),n=this._analyzeAsset(o,r.size);n&&t.push(n)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(n=>this._matchesPattern(e,n))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let o=`/${e}.${r}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${ae.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(ae.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],n=[],i=[];try{let c=await this.pathResolver.read(t,{format:"text"});if(!c)return{generated:[],skipped:[...o,...r].map(l=>l.name),error:"Failed to read logo.svg"};for(let l of o){let u=`${s}/${l.name}`;if(this.pathResolver.pathExists(u)){i.push(l.name);continue}try{await this.pathResolver.write(`public/${l.name}`,c),n.push(l.name)}catch(h){this.logger.debug(`Failed to copy ${l.name}: ${h.message}`),i.push(l.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(l=>l.name));else for(let l of r){let u=`${s}/${l.name}`;if(this.pathResolver.pathExists(u)){i.push(l.name);continue}try{let h=p.default(t).resize(l.size,l.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;l.format==="ico"?g=await h.toFormat("png").toBuffer():g=await h.toFormat(l.format).toBuffer(),await this.pathResolver.write(`public/${l.name}`,g),n.push(l.name)}catch(h){this.logger.debug(`Failed to generate ${l.name}: ${h.message}`),i.push(l.name)}}return{generated:n,skipped:i,error:null}}catch(c){return this.logger.debug(`Asset generation failed: ${c.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:c.message}}}};var Oe={data:null},De=class extends A{constructor(e={}){super(be,e)}getHandlerDefaults(){return{manifestPath:U.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
29
51
|
// Generated at: ${new Date().toISOString()}
|
|
30
52
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
31
53
|
|
|
@@ -42,7 +64,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
42
64
|
timestamp: Date.now(),
|
|
43
65
|
};
|
|
44
66
|
}
|
|
45
|
-
globalThis._DNDEV_CONFIG_.${
|
|
67
|
+
globalThis._DNDEV_CONFIG_.${C.assets} = {
|
|
46
68
|
mapping: assetConfig.manifest,
|
|
47
69
|
logoSvgContent: ${JSON.stringify(t)},
|
|
48
70
|
manifest: {
|
|
@@ -83,27 +105,6 @@ export const assetStats = {
|
|
|
83
105
|
generatedAt: '${new Date().toISOString()}'
|
|
84
106
|
};
|
|
85
107
|
|
|
86
|
-
// Populate unified DnDev config for runtime access (universal CSR/SSR)
|
|
87
|
-
if (typeof globalThis !== 'undefined') {
|
|
88
|
-
if (!globalThis._DNDEV_CONFIG_) {
|
|
89
|
-
globalThis._DNDEV_CONFIG_ = {
|
|
90
|
-
platform: 'nextjs',
|
|
91
|
-
mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development',
|
|
92
|
-
version: '1.0.0',
|
|
93
|
-
context: typeof window !== 'undefined' ? 'client' : 'server',
|
|
94
|
-
timestamp: Date.now(),
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
globalThis._DNDEV_CONFIG_.assets = {
|
|
98
|
-
mapping: assetManifest,
|
|
99
|
-
logoSvgContent: ${JSON.stringify(r)},
|
|
100
|
-
manifest: {
|
|
101
|
-
totalAssets: ${e.assets.length},
|
|
102
|
-
generatedAt: '${new Date().toISOString()}',
|
|
103
|
-
},
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
|
|
107
108
|
export default assets;
|
|
108
109
|
`}async generateImageOptimization(e){let t=e.assets.filter(r=>r.type==="image");if(t.length===0){this.logger.debug("No image assets found, skipping optimization config");return}let s=this.generateImageOptimizationContent(t);this.writeGeneratedFile("src/app/image-optimization.generated.ts",s,"image optimization config")}generateImageOptimizationContent(e){let t=e.map(s=>{let r=s.path.split("/").pop().split(".")[0];return` '${r}': {
|
|
109
110
|
src: '${s.path}',
|
|
@@ -122,7 +123,7 @@ ${t}
|
|
|
122
123
|
export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
|
|
123
124
|
|
|
124
125
|
export default imageConfigs;
|
|
125
|
-
`}};function dt(a={}){return new De(a)}var ye=class extends
|
|
126
|
+
`}};function dt(a={}){return new De(a)}var ye=class extends D{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],...t})}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=de("i18n"),n=r.eager||[],i=r.lazy||[],c=(this.options.additionalPaths||[]).map(v=>{let b=v.endsWith(".json")?v:`${v}/*_*.json`;return this.pathResolver.resolveAppPath(b)});c.length>0&&this.logger.debug(`Additional i18n paths configured: ${c.join(", ")}`);let p=r.framework?.eager||[],l=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${l.join(", ")}`),p.length===0&&l.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),h=this.pathResolver.normalizePath(s),g=(v,b)=>{let w=this.pathResolver.normalizePath(v),R=this.pathResolver.normalizePath(b);return w.startsWith(R)?w.slice(R.length+1):w},d=n.map(v=>g(v,t)),$=[...i,...c].map(v=>g(v,t)),V=p.map(v=>g(v,s)),J=l.map(v=>g(v,s)),x={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},q=await this.pathResolver._globWithNormalization(d,x),Q=await this.pathResolver._globWithNormalization($,x),Y={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(v=>v!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(Y.ignore)}`);let E=await this.pathResolver._globWithNormalization(V,Y),j=await this.pathResolver._globWithNormalization(J,Y);this.logger.debug(`Found ${q.length} eager, ${Q.length} lazy, ${E.length} framework eager, ${j.length} framework lazy files`),E.length>0?this.logger.debug(`Framework eager files (first 3): ${E.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),j.length>0?this.logger.debug(`Framework lazy files (first 3): ${j.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${l.join(", ")}`);let oe=[...new Set([...q,...Q,...E,...j])],ee=new Set([...q,...E]),f={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},W=new Map,M=[...E,...j];for(let v of M){let b=this._processTranslationFile(v,E.includes(v),t);if(b){let w=`${b.namespace}_${b.language}`;W.set(w,b),f.allNamespaces.add(b.namespace),f.supportedLanguages.add(b.language),E.includes(v)&&f.eagerNamespaces.add(b.namespace)}}let I=new Set;for(let v of oe){if(M.includes(v))continue;let b=this._processTranslationFile(v,ee.has(v),t);if(b){let{namespace:w,language:R,importPath:pe,content:$e}=b,N=`${b.namespace}_${b.language}`;if(W.has(N)){let z=W.get(N);b.content=this._mergeTranslations(z.content,$e)}f.allNamespaces.add(w),f.supportedLanguages.add(R),I.add(R),ee.has(v)&&f.eagerNamespaces.add(w),f.mapping[w]||(f.mapping[w]={}),f.mapping[w][R]=pe,b.content&&(f.content[w]||(f.content[w]={}),f.content[w][R]=b.content),f.files.push({path:v,relativePath:this.pathResolver.getRelativePath(v),namespace:w,language:R,eager:ee.has(v),size:b.content?JSON.stringify(b.content).length:0})}}for(let[v,b]of W){let[w,R]=v.split("_");(!f.mapping[w]||!f.mapping[w][R])&&(f.mapping[w]||(f.mapping[w]={}),f.mapping[w][R]=b.importPath,f.content[w]||(f.content[w]={}),f.content[w][R]=b.content,f.files.push({path:b.absolutePath,relativePath:this.pathResolver.getRelativePath(b.absolutePath),namespace:w,language:R,eager:f.eagerNamespaces.has(w),size:b.content?JSON.stringify(b.content).length:0}))}let K=I.size>0?[...I].sort():[this.options.fallbackLanguage];return{mapping:f.mapping,content:f.content,eagerNamespaces:[...f.eagerNamespaces].sort(),allNamespaces:[...f.allNamespaces].sort(),supportedLanguages:K,fallbackLanguage:this.options.fallbackLanguage,files:f.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,n,i=r.match(/^([^_]+)_([^.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,n]=i,!o||!n)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let p="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),l;try{if(l=this.pathResolver.readSync(e,{format:"json"}),!l)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:o,language:n,importPath:p,absolutePath:e,content:l}}_mergeTranslations(e,t){let s={...e};for(let[r,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?s[r]=this._mergeTranslations(s[r]||{},o):s[r]=o;return s}};var Ie=class extends A{constructor(e={}){super(ye,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...ce.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:o,content:n}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
126
127
|
// Generated at: ${new Date().toISOString()}
|
|
127
128
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
128
129
|
|
|
@@ -164,12 +165,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
164
165
|
timestamp: Date.now(),
|
|
165
166
|
};
|
|
166
167
|
}
|
|
167
|
-
globalThis._DNDEV_CONFIG_.${
|
|
168
|
+
globalThis._DNDEV_CONFIG_.${C.i18n} = i18nConfig;
|
|
168
169
|
}
|
|
169
170
|
|
|
170
171
|
// Export for compatibility
|
|
171
172
|
export default i18nConfig;
|
|
172
|
-
`}};function mt(a={}){return new Ie(a)}var we=class extends
|
|
173
|
+
`}};function mt(a={}){return new Ie(a)}var we=class extends D{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:s}=e,r=[...t,...s];this.logger.debug(`Processing ${r.length} PWA files`);let o=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),o=[...this.options.assetData.pwaIcons]);let n=await this._analyzePWAFiles(r),i=n.filter(h=>h.type==="manifest"||h.type==="service-worker");o.push(...i);let c=n.filter(h=>h.type==="icon"),p=new Set(o.filter(h=>h.type==="icon").map(h=>h.path)),l=c.filter(h=>!p.has(h.path));o.push(...l);let u=this._generatePWAManifest(o);return{assets:o,manifest:u,totalFiles:r.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let s of e){let r=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,o=await this._analyzePWAAsset(r);o&&t.push(o)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let s=e.relativePath,r=e.fileName;return r.includes("manifest.json")?this._parseManifestFile(t,s):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,s):this._isPWAIcon(r)?this._parseIconFile(e,s):null}_parseManifestFile(e,t){try{let s=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:s,size:typeof e=="string"?e.length:JSON.stringify(s).length}}catch(s){return this.logger.debug(`Failed to parse manifest: ${s.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let s=e.fileName,r=this._extractIconSize(s);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(s)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(s=>e.includes(s))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(o=>o.type==="icon"),r=e.find(o=>o.type==="manifest")?.content||this._getDefaultManifest();return t.length>0&&(r.icons=t.map(o=>({src:`/${o.path}`,sizes:`${o.size.width}x${o.size.height}`,type:`image/${o.format}`,purpose:o.purpose}))),r}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let t=e.manifest||this._getDefaultManifest();return JSON.stringify(t,null,2)}generateServiceWorkerContent(e,t={}){let s=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,o=t.precacheManifest||[],n=JSON.stringify(o,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
173
174
|
// Generated at ${new Date().toISOString()}
|
|
174
175
|
|
|
175
176
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -237,7 +238,7 @@ registerRoute(
|
|
|
237
238
|
}),
|
|
238
239
|
'POST'
|
|
239
240
|
);
|
|
240
|
-
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let n=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let i of n){let c=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of c){let l=this.pathResolver.getRelativePath(p);if(l.startsWith(`${e}/static/`)){let u=`/_next/${l.replace(`${e}/static/`,"")}`;o.push({url:u,revision:null})}}}}catch(n){this.logger?.warn(`Failed to discover Next.js build assets: ${n.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Te=class extends A{constructor(e={}){super(we,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Oe.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.enabled){this.logger.debug("PWA disabled, skipping generation");return}this.options.generateManifest&&await this.generatePWAManifest(e),this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,t,"PWA manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:o,webpack:n}=s;return this.applyViteIgnorePlugin(t,n),!r&&!o&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function vt(a={}){return new Te(a)}import{createRequire as us}from"node:module";function bt(a,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=a.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(c,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(o)].forEach(c=>{let p=c[1],l=c[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${l}'`)}),Function(`return ${r}`)()}catch{return null}}var le=null,yt=null;function ls(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var re=class extends C{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(le&&yt===s)return this.logger.debug("Using cached route discovery results"),this.routes=le.routes,this.errors=le.errors,this.source=le.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let o=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(o)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),le={routes:this.routes,errors:this.errors,source:this.source},yt=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),o=await this._scanAdditionalPatterns(t),n=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),i=[...r,...n];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=i.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let c=new Map;for(let p of this.routes){let l=p.path;if(c.has(l)){let u=c.get(l);throw new Error(`Route conflict: Multiple routes found for path '${l}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}c.set(l,p)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,o="/src/"+r.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let n=this._extractMetaExport(s,e.absolutePath),i=ls(o),p=i===ne.HOMEPAGE_COMPONENT?ne.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),l=this._extractPageMeta(r,s),{entity:u,action:h,...g}=n||{};return{path:p,component:i,importPath:o,auth:n?.auth||!1,meta:{...l,...g,entity:l.entity,action:l.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=bt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let n=o.map(i=>`:${i}`).join("/");return`${r}/${n}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z])/g," $1").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),n=null,i=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?i="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?i="form":(s.includes("Detail")||s.includes("View"))&&(i="detail")),{title:r,entity:n,action:i,file:e}}};function ps(a,e,t="configuration-error",s={}){let r=`[${a}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=a,o.context=s,o}function wt(a,e,t,s={}){return ps(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function Pt(a){return a?.languages||a?.supportedLanguages||["en"]}function St(a){return a?.fallback||a?.fallbackLanguage||"en"}var je=class extends A{constructor(e={}){super(re,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:X.next.middleware,manifestPath:X.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(o=>o.auth&&o.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
241
|
+
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let n=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let i of n){let c=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of c){let l=this.pathResolver.getRelativePath(p);if(l.startsWith(`${e}/static/`)){let u=`/_next/${l.replace(`${e}/static/`,"")}`;o.push({url:u,revision:null})}}}}catch(n){this.logger?.warn(`Failed to discover Next.js build assets: ${n.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Te=class extends A{constructor(e={}){super(we,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Oe.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.enabled){this.logger.debug("PWA disabled, skipping generation");return}this.options.generateManifest&&await this.generatePWAManifest(e),this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,t,"PWA manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:o,webpack:n}=s;return this.applyViteIgnorePlugin(t,n),!r&&!o&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function vt(a={}){return new Te(a)}import{createRequire as hs}from"node:module";function bt(a,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=a.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(c,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(o)].forEach(c=>{let p=c[1],l=c[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${l}'`)}),Function(`return ${r}`)()}catch{return null}}var le=null,yt=null;function us(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var re=class extends D{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(le&&yt===s)return this.logger.debug("Using cached route discovery results"),this.routes=le.routes,this.errors=le.errors,this.source=le.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let o=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(o)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),le={routes:this.routes,errors:this.errors,source:this.source},yt=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),o=await this._scanAdditionalPatterns(t),n=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),i=[...r,...n];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=i.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let c=new Map;for(let p of this.routes){let l=p.path;if(c.has(l)){let u=c.get(l);throw new Error(`Route conflict: Multiple routes found for path '${l}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}c.set(l,p)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,o="/src/"+r.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let n=this._extractMetaExport(s,e.absolutePath),i=us(o),p=i===ne.HOMEPAGE_COMPONENT?ne.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),l=this._extractPageMeta(r,s),{entity:u,action:h,...g}=n||{};return{path:p,component:i,importPath:o,auth:n?.auth||!1,meta:{...l,...g,entity:l.entity,action:l.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=bt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let n=o.map(i=>`:${i}`).join("/");return`${r}/${n}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z])/g," $1").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),n=null,i=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?i="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?i="form":(s.includes("Detail")||s.includes("View"))&&(i="detail")),{title:r,entity:n,action:i,file:e}}};function gs(a,e,t="configuration-error",s={}){let r=`[${a}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=a,o.context=s,o}function wt(a,e,t,s={}){return gs(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function Pt(a){return a?.languages||a?.supportedLanguages||["en"]}function St(a){return a?.fallback||a?.fallbackLanguage||"en"}var je=class extends A{constructor(e={}){super(re,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:U.next.middleware,manifestPath:U.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(o=>o.auth&&o.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
241
242
|
// Generated at: ${new Date().toISOString()}
|
|
242
243
|
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
243
244
|
|
|
@@ -256,7 +257,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
256
257
|
timestamp: Date.now(),
|
|
257
258
|
};
|
|
258
259
|
}
|
|
259
|
-
globalThis._DNDEV_CONFIG_.${
|
|
260
|
+
globalThis._DNDEV_CONFIG_.${C.routes} = {
|
|
260
261
|
mapping: routeMapping,
|
|
261
262
|
manifest: routeManifest,
|
|
262
263
|
};
|
|
@@ -266,7 +267,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
266
267
|
export const routes = routeMapping;
|
|
267
268
|
export const manifest = routeManifest;
|
|
268
269
|
export default { routes: routeMapping, manifest: routeManifest };
|
|
269
|
-
`}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles();let t=0;for(let s of e.routes)await this.generateSingleAppPage(s)&&t++;this.logger.debug(`Successfully generated ${t}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=["src/app/**/page.tsx","src/app/[...slug]/page.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let o of s)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),r++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(n){this.logger.debug(`Could not clean file ${o}: ${n.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e){try{let t=this.convertRouteToAppPath(e.path),s=`src/app${t}/page.tsx`,r=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(r)&&!await this.hasGenerationMarker(r))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let o={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},n=this.generatePageFileContent(o);return this.writeGeneratedFile(s,n,`app page: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===ne.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=
|
|
270
|
+
`}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles();let t=0;for(let s of e.routes)await this.generateSingleAppPage(s)&&t++;this.logger.debug(`Successfully generated ${t}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=["src/app/**/page.tsx","src/app/[...slug]/page.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let o of s)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),r++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(n){this.logger.debug(`Could not clean file ${o}: ${n.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e){try{let t=this.convertRouteToAppPath(e.path),s=`src/app${t}/page.tsx`,r=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(r)&&!await this.hasGenerationMarker(r))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let o={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},n=this.generatePageFileContent(o);return this.writeGeneratedFile(s,n,`app page: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===ne.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=hs(t),r=s.resolve(e);delete s.cache[r];let o=s(r);return o.default||o.i18nConfig||o}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e){let t=this.extractComponentName(e.filePath),s=e.relativePath||e.file,r=this.calculateRelativeImportPath(s,e.path),o=this.isClientComponent(e.filePath),n=e.metaExport&&Object.keys(e.metaExport).length>0,i=this.loadI18nConfig(),c=e.metaExport?.namespace,p=`// Generated by @donotdev/config - DO NOT EDIT
|
|
270
271
|
// This file will be regenerated when src/pages changes
|
|
271
272
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
272
273
|
${o?`'use client';
|
|
@@ -497,7 +498,7 @@ export const routeManifest = {
|
|
|
497
498
|
|
|
498
499
|
export default pageRoutes;
|
|
499
500
|
`}pathToComponentName(e){return e.split("/").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")+"Page"}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let r=e.replace(/\.tsx$/,"").replace(/^src\//,""),o=t==="/"?0:t.split("/").filter(Boolean).length;return`${"../".repeat(o+1)}${r}`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let s=this.pathResolver.readSync(t);return s?s.split(`
|
|
500
|
-
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function $t(a={}){return new je(a)}import{readFileSync as
|
|
501
|
+
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function $t(a={}){return new je(a)}import{readFileSync as fs,readdirSync as ds,existsSync as ms}from"fs";import{join as Rt}from"path";var Pe=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:n,crawlDelay:i=1,routes:c={},...p}=e;if(!o||!n)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:o,siteName:n,crawlDelay:i,routes:c,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=k("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,s=null){try{let r=this.generateRouteMetaTags(e.routes||[]),o={routes:e.routes||[],routeMetaTags:r,baseUrl:this.options.baseUrl,siteName:this.options.siteName},n=this.discoverBlogPosts(),i={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:o.routes.length,publicRoutes:o.routes.filter(c=>!c.auth||c.auth===!1).length,protectedRoutes:o.routes.filter(c=>c.auth&&c.auth.required).length,blogPosts:n.length};return this.options.generateRobotsTxt&&(i.robotsTxt=await this.generateRobotsTxt(o,t,s)),this.options.generateSitemap&&(i.sitemap=await this.generateSitemap(o,t,s,n)),n.length>0&&(i.rss=await this.generateRSSFeed(n,t,s)),i.manifest=await this.generateManifest(o,t,s),i}catch(r){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`),r}}async generateRobotsTxt(e,t,s=null){if(s&&await s("robots.txt"))return this.logger.info("\u2705 robots.txt already exists, skipping generation"),{fileName:"robots.txt",skipped:!0};let r=[];(e.routes||[]).forEach(n=>{if(n.auth&&n.auth.required){let i=n.path.startsWith("/")?n.path:`/${n.path}`;r.push(i)}}),r.push("/admin","/api","/_next","/static");let o=this.generateRobotsTxtContent({disallowedPaths:[...new Set(r)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",o),{fileName:"robots.txt",content:o,disallowedPaths:r.length}}async generateSitemap(e,t,s=null,r=[]){if(s&&await s("sitemap.xml"))return this.logger.info("\u2705 sitemap.xml already exists, skipping generation"),{fileName:"sitemap.xml",skipped:!0};let n=(e.routes||[]).filter(c=>!c.auth||c.auth===!1).map(c=>({url:c.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:c.path==="/"?"1.0":"0.8"}));if(r.length>0){n.push({url:"/blog",lastmod:r[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let c of r)n.push({url:`/blog/${c.slug}`,lastmod:c.date,changefreq:"monthly",priority:"0.6"})}let i=this.generateSitemapContent(n);return await t("sitemap.xml",i),{fileName:"sitemap.xml",content:i,publicRoutes:n.length}}async generateManifest(e,t,s=null){if(s&&await s("seo-manifest.json"))return this.logger.info("\u2705 seo-manifest.json already exists, skipping generation"),{fileName:"seo-manifest.json",skipped:!0};let r={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,protectedRoutes:e.routes?.filter(n=>n.auth&&n.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},o=JSON.stringify(r,null,2);return await t("seo-manifest.json",o),{fileName:"seo-manifest.json",content:o,manifest:r}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:o}=e,n=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...s.map(c=>`Disallow: ${n(c)}`),...t.map(c=>`Allow: ${n(c)}`)];return o&&i.push(`Crawl-delay: ${o}`),r&&i.push(`Sitemap: ${r}`),i.join(`
|
|
501
502
|
`)}generateSitemapContent(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
502
503
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
503
504
|
${e.map(({url:s,lastmod:r,changefreq:o,priority:n})=>{let i=[` <loc>${this.options.baseUrl}${s}</loc>`];return r&&i.push(` <lastmod>${r}</lastmod>`),o&&i.push(` <changefreq>${o}</changefreq>`),n&&i.push(` <priority>${n}</priority>`),` <url>
|
|
@@ -505,7 +506,7 @@ ${i.join(`
|
|
|
505
506
|
`)}
|
|
506
507
|
</url>`}).join(`
|
|
507
508
|
`)}
|
|
508
|
-
</urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(r=`Explore ${o[o.length-1].split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=Rt(this.appRoot,"src","content","blog");try{if(!
|
|
509
|
+
</urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(r=`Explore ${o[o.length-1].split("-").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=Rt(this.appRoot,"src","content","blog");try{if(!ms(e))return[];let t=ds(e).filter(r=>r.endsWith("_en.md"));if(t.length===0)return[];let s=[];for(let r of t){let o=fs(Rt(e,r),"utf-8"),n=r.replace(/_en\.md$/,""),i=o.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(i)for(let p of i[1].split(`
|
|
509
510
|
`)){let l=p.indexOf(":");l!==-1&&(c[p.slice(0,l).trim()]=p.slice(l+1).trim())}s.push({slug:n,title:c.title||n,description:c.description||"",date:c.date||new Date().toISOString().split("T")[0],tags:c.tags?c.tags.split(",").map(p=>p.trim()):[],image:c.image||null})}return s.sort((r,o)=>o.date.localeCompare(r.date)),this.logger.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(t){return this.logger.debug(`Blog content discovery skipped: ${t.message}`),[]}}async generateRSSFeed(e,t,s=null){if(s&&await s("rss.xml"))return this.logger.info("\u2705 rss.xml already exists, skipping generation"),{fileName:"rss.xml",skipped:!0};let r=e.map(n=>` <item>
|
|
510
511
|
<title><![CDATA[${n.title}]]></title>
|
|
511
512
|
<link>${this.options.baseUrl}/blog/${n.slug}</link>
|
|
@@ -525,7 +526,7 @@ ${i.join(`
|
|
|
525
526
|
<atom:link href="${this.options.baseUrl}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
526
527
|
${r}
|
|
527
528
|
</channel>
|
|
528
|
-
</rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}};var Me=class extends A{constructor(e={}){super(re,e);let t=y.getInstance(),s=
|
|
529
|
+
</rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}};var Me=class extends A{constructor(e={}){super(re,e);let t=y.getInstance(),s=k("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let o=e.seo?.baseUrl;if(!o&&r){let c=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(c)?c:`https://${c}`}o?s.debug(`Found app URL: ${o}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let n=e.siteName||e.seo?.siteName||null;if(s.verbose(`Name: ${n||"Not found"}`),s.verbose(`URL: ${o||"Not found"}`),n&&s.debug(` - Site name from appConfig: "${n}"`),e.seo?.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let i=[];if(o||i.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),n||i.push("siteName (APP_NAME in src/config/app.ts)"),i.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),i.forEach(c=>s.warn(` - ${c}`)),s.warn(""),s.warn(" To fix:"),o||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),n||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this.seoGenerator=new Pe({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:o,siteName:n,crawlDelay:this.options.crawlDelay,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(o,n)=>{if(!o){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${o}`,n,o)},s=async o=>{try{let n=this.pathResolver.resolveAppPath(`public/${o}`);return this.pathResolver.pathExists(n)}catch{return!1}},r=await this.seoGenerator.generateSEOFiles(e,t,s);r.robotsTxt&&!r.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${r.robotsTxt.disallowedPaths||0} disallowed paths`),r.sitemap&&!r.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${r.sitemap.publicRoutes||0} routes`),r.rss&&!r.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${r.rss.postCount||0} blog posts`),r.manifest&&!r.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json")}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function kt(a={}){return new Me(a)}function xt(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),Be.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var Se=class extends D{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new H(t,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:s}=e;this.logger.debug(`Scanning ${t.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",s),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t),await this._processConsumerFiles(s);let r=this._serializeThemes();return this.logger.debug(`Discovered ${r.length} themes:`,r.map(o=>o.name)),{themes:r,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return Ee.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning framework file ${t}: ${s.message}`)}}async _processConsumerFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${t}: ${s.message}`)}}_addEssentialThemes(){Ee.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var ze=class extends A{constructor(e={}){super(Se,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new H(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(o=>!o.essential).length,r=t.length;if(r===0)throw wt("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
529
530
|
// Generated at: ${new Date().toISOString()}
|
|
530
531
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
531
532
|
|
|
@@ -557,7 +558,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
557
558
|
timestamp: Date.now(),
|
|
558
559
|
};
|
|
559
560
|
}
|
|
560
|
-
globalThis._DNDEV_CONFIG_.${
|
|
561
|
+
globalThis._DNDEV_CONFIG_.${C.themes} = themeConfig;
|
|
561
562
|
}
|
|
562
563
|
|
|
563
564
|
// Export for compatibility
|
|
@@ -573,6 +574,6 @@ export function useTheme() {
|
|
|
573
574
|
}
|
|
574
575
|
|
|
575
576
|
export default useTheme;
|
|
576
|
-
`}};function At(a={}){return new ze(a)}function _t({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:i,pwaOptions:c,serverShimOptions:p,appUrl:l,isDev:u,logger:h}){let g=s.debug??a,d=r.debug??a,P=o.debug??a,$=n.debug??a,
|
|
577
|
-
\u{1F3D7}\uFE0F DnDev Framework - Building for ${
|
|
578
|
-
`),
|
|
577
|
+
`}};function At(a={}){return new ze(a)}function _t({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:i,pwaOptions:c,serverShimOptions:p,appUrl:l,isDev:u,logger:h}){let g=s.debug??a,d=r.debug??a,P=o.debug??a,$=n.debug??a,V=i.debug??a,J=c.debug??a,x=p.debug??a,q=s.verbose??e,Q=r.verbose??e,Y=o.verbose??e,E=n.verbose??e,j=i.verbose??e,oe=c.verbose??e,ee=p.verbose??e,f={debug:a,verbose:e,generateManifest:t},W=s.disabled?null:$t({...f,...s,debug:g,verbose:q});a&&h.debug(`Route handler created: ${W?"enabled":"disabled"} (debug: ${g})`);let M=At({...f,...r,debug:d,verbose:Q}),I=mt({...f,...o,debug:P,verbose:Y}),K=dt({...f,...n,debug:$,verbose:E}),v=kt({...f,...i,debug:V,verbose:j,appUrl:l,isDev:u}),b=vt({...f,...c,debug:J,verbose:oe}),w=xt({...f,...p,debug:x,verbose:ee});return{routeHandler:W,themeHandler:M,i18nHandler:I,assetHandler:K,seoHandler:v,pwaHandler:b,serverShimHandler:w}}function Et(a,e){let t={};if(a.routeHandler)try{t.routeConfig=a.routeHandler.createNextConfig()}catch(r){e.error(`Route handler failed during config creation: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.routeConfig=()=>({})}else t.routeConfig=()=>({});let s=[{name:"theme",handler:a.themeHandler},{name:"i18n",handler:a.i18nHandler},{name:"asset",handler:a.assetHandler},{name:"seo",handler:a.seoHandler},{name:"pwa",handler:a.pwaHandler}];for(let{name:r,handler:o}of s)try{t[`${r}Config`]=o.createNextConfig()}catch(n){e.error(`${r.charAt(0).toUpperCase()+r.slice(1)} handler failed: ${n.message}`),e.error(`Stack: ${n.stack||"No stack trace available"}`),t[`${r}Config`]=()=>({})}try{t.serverShimConfig=a.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}function vs(a){if(!a)return[];let e=y.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",a);if(!s)return[];let r=e.getDirname(e.getDirname(s)),o;try{o=e.readdirSync(r)}catch{return[]}for(let n of o)try{let i=e.resolvePath(`${n}/package.json`,r),c=e.readSync(i,{format:"json"});if(!c?.peerDependenciesMeta)continue;for(let[p,l]of Object.entries(c.peerDependenciesMeta))l?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function bs(a){if(!a)return[];let e=y.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[o,n]of Object.entries(s.peerDependenciesMeta))n?.optional&&r.add(o);if(s.optionalDependencies)for(let o of Object.keys(s.optionalDependencies))r.add(o);return Array.from(r)}catch{return[]}}function ys(a){let e=fe.optionalFeatures||[],t=vs(a),s=bs(a);return[...new Set([...e,...t,...s])]}function ws(a){let e=y.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function Ps(a,e,t){if(t.resolvePackage(a,e||void 0))return!0;let s=a.startsWith("@")?a.split("/").slice(0,2).join("/"):a.split("/")[0],r=e;for(let o=0;o<10;o++){let n=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(n))return!0;let i=t.getDirname(r);if(i===r)break;r=i}return!1}function Le(a){let e=ys(a),t=[],s=[],r=y.getInstance(),o=ws(a);for(let n of e)n.startsWith("@donotdev/")?o.has(n)?s.push(n):t.push(n):Ps(n,a,r)?s.push(n):t.push(n);return{missing:t,installed:s}}function Ss(a={}){let{port:e,...t}=a;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let L=process.env.CI==="true";process.env.DNDEV_BUILD_ID=L?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let{appConfig:s,...r}=t;if(!s)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let o=s?.features?{debug:s.features.debug}:void 0,n=s?.seo&&typeof s.seo!="boolean"?{...s.seo,siteName:s.seo.siteName||s.app?.name}:s?.app?.name?{siteName:s.app.name}:void 0,i=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:c,seo:p,...l}=r,u={...o?{features:o}:{},...n?{seo:n}:{},...l},h=ht(u),g=ft(h);if(!g)throw new Error("normalizeOptions returned undefined");let{generateManifest:d,debug:P,verbose:$,mode:V,isDev:J,routeOptions:x,themeOptions:q,i18nOptions:Q,assetOptions:Y,pwaOptions:E,seoOptions:j,serverShimOptions:oe,nextConfigOptions:ee}=g,f=k("next-config",P,$),{appRoot:W,appRootSet:M}=Ke({logger:f,debug:P}),I=!1,K=!1,{installed:v}=Le(process.cwd()),b=Object.values(We.packageNames),w=b.filter(L=>!v.includes(L)),R=b.filter(L=>v.includes(L)),pe=process.env.DNDEV_BUILD_ID,$e=x?.routingMode||"app";if(f.info(`
|
|
578
|
+
\u{1F3D7}\uFE0F DnDev Framework - Building for ${V}${pe?` [build:${pe}]`:""}`),f.info(` Platform: Next.js | Routing: ${$e}
|
|
579
|
+
`),J){let L=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${L}`,P&&(f.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&f.debug(`Port configured: ${L} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||f.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let N=_t({debug:P,verbose:$,generateManifest:d,routeOptions:x,themeOptions:q,i18nOptions:Q,assetOptions:Y,seoOptions:j,pwaOptions:E,serverShimOptions:oe,isDev:J,logger:f}),z=Et(N,f);return async function(Re={}){let te=y.getInstance(),ue=M?st():[];P&&ue.length>0&&f.debug(`Discovered ${ue.length} packages: ${ue.join(", ")}`);let{missing:ge}=Le(te.getAppRoot());P&&ge.length>0&&f.debug(`Missing optional deps (will alias to empty): ${ge.join(", ")}`);let Ue=te.getAppRoot();if(M&&!I){let ke=te.resolveAppPath(".dndev-build"),xe=process.env.DNDEV_BUILD_ID;try{te.readSync(ke,{format:"text"})?.trim()===xe?(f.debug("Discoveries already completed by another worker, skipping"),I=!0):(Fe(Ue,f),await Ce(N,f),I=!0)}catch{Fe(Ue,f),await Ce(N,f),I=!0}}let X=typeof Re=="object"&&Re!==null?Re:{},{webpack:Ft,rewrites:Ct,...Dt}=X;M&&!K&&(K=await ut(N.assetHandler,f,K));let Ot=z.routeConfig(X),It=z.themeConfig(X),Tt=z.i18nConfig(X),jt=z.assetConfig(X),Mt=z.seoConfig(X),zt=z.pwaConfig(X),Lt=z.serverShimConfig(),Ut=ot({originalWebpack:Ft,unusedFeaturePackages:w,usedFeaturePackages:R,missingOptionalDeps:ge,logger:f,debug:P}),Gt=nt({originalRewrites:Ct,handlers:[N.routeHandler,N.themeHandler,N.i18nHandler,N.assetHandler,N.pwaHandler],logger:f}),Wt={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Bt=at({routeResult:Ot,themeResult:It,i18nResult:Tt,assetResult:jt,seoResult:Mt,pwaResult:zt,serverShimResult:Lt,restNextConfig:Dt,discoveredPackages:ue,webpackConfig:Ut,rewritesConfig:Gt,missingOptionalDeps:ge,pathResolver:te,env:Wt,logger:f});if(f.debug("Next.js config generated"),M){let ke=i?.name||"app",xe=te.getAppRoot();f.info(`Name: ${ke}`),f.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),f.info("\u{1F527} Features: auto-detected"),f.info(`App root (final): ${xe}`)}return Bt}}var Nt=Ss;export{Nt as default,Nt as defineNextConfig,es as definePostCSSConfig};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.42",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"default": "./functions/index.js"
|
|
35
35
|
},
|
|
36
36
|
"./empty": {
|
|
37
|
-
"import": "./empty.
|
|
37
|
+
"import": "./empty.cjs",
|
|
38
38
|
"default": "./empty.cjs"
|
|
39
39
|
}
|
|
40
40
|
},
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
],
|
|
53
53
|
"sideEffects": false,
|
|
54
54
|
"peerDependencies": {
|
|
55
|
-
"@donotdev/components": "^0.0.
|
|
55
|
+
"@donotdev/components": "^0.0.30",
|
|
56
56
|
"lucide-react": "^0.575.0",
|
|
57
57
|
"react": "^19.2.4",
|
|
58
58
|
"react-dom": "^19.2.4",
|
|
@@ -86,8 +86,8 @@
|
|
|
86
86
|
},
|
|
87
87
|
"dependencies": {
|
|
88
88
|
"@clack/prompts": "^1.0.1",
|
|
89
|
-
"@sentry/react": "^10.39.0",
|
|
90
89
|
"@rollup/plugin-strip": "^3.0.4",
|
|
90
|
+
"@sentry/react": "^10.39.0",
|
|
91
91
|
"@tanstack/react-query": "^5.90.21",
|
|
92
92
|
"@vitejs/plugin-basic-ssl": "^2.1.4",
|
|
93
93
|
"@vitejs/plugin-react": "^5.1.4",
|
package/server.d.ts
CHANGED
|
@@ -5572,17 +5572,15 @@ interface UIFieldOptions<T extends string = FieldType> {
|
|
|
5572
5572
|
/** Step value for numeric inputs */
|
|
5573
5573
|
step?: T extends 'number' | 'range' ? number : never;
|
|
5574
5574
|
/**
|
|
5575
|
-
*
|
|
5576
|
-
*
|
|
5577
|
-
*
|
|
5578
|
-
|
|
5579
|
-
|
|
5580
|
-
|
|
5581
|
-
*
|
|
5582
|
-
* Use for locale-specific suffixes like "charges comprises" / "all included".
|
|
5583
|
-
* @example `suffix: 'fields.rent_suffix'` → "700€ charges comprises"
|
|
5575
|
+
* i18n key for display formatting. Replaces the raw value in lists/cards/display views.
|
|
5576
|
+
* The formatter calls `t(displayKey, { value })`. Supports i18next array-key fallback.
|
|
5577
|
+
* Use `{{value}}` in key names for dynamic lookup (interpolated before `t()` call).
|
|
5578
|
+
*
|
|
5579
|
+
* @example Single key: `displayKey: 'fields.size_display'` → locale `"{{value}}m²"` → "20m²"
|
|
5580
|
+
* @example Array fallback: `displayKey: ['floor_{{value}}', 'fields.floor_display']`
|
|
5581
|
+
* → tries `floor_4`, falls back to `fields.floor_display`: `"{{value}}th floor"` → "4th floor"
|
|
5584
5582
|
*/
|
|
5585
|
-
|
|
5583
|
+
displayKey?: string | string[];
|
|
5586
5584
|
/** Whether to show value label for range inputs */
|
|
5587
5585
|
showValue?: T extends 'range' ? boolean : never;
|
|
5588
5586
|
/** Field specific options based on field type. Custom types: augment CustomFieldOptionsMap. */
|
|
@@ -7159,7 +7157,7 @@ interface EntityRecommendationsProps {
|
|
|
7159
7157
|
title?: string;
|
|
7160
7158
|
/** Base path for card links. Default: `/${entity.collection}` */
|
|
7161
7159
|
basePath?: string;
|
|
7162
|
-
/** Grid columns — default 3 */
|
|
7160
|
+
/** Grid columns — default `[1,1,3,3]` */
|
|
7163
7161
|
cols?: number | [number, number, number, number];
|
|
7164
7162
|
/** Additional className on wrapper Section */
|
|
7165
7163
|
className?: string;
|
package/vite/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Qt=Object.defineProperty;var Le=(n,e)=>()=>(n&&(e=n(n=0)),e);var es=(n,e)=>{for(var t in e)Qt(n,t,{get:e[t],enumerable:!0})};function nt(n,e=null){let t=Q[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Ne(n){return rt[n]||rt.base}var We,C,V,j,Ge,xe,Ae,Q,me,ot,Be,Ve,Se,He,rt,L=Le(()=>{"use strict";We={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},C={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env"},V={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},j={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ge={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},xe={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Ae={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},Q={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${Ae.SOURCE_EAGER}/*_*.json`],lazy:[`${Ae.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},me={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},ot=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"],Be=["@donotdev/core/functions","@donotdev/core/server"],Ve={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)/}},Se={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},He=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],rt={base:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...Q.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...Q.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore}}});import*as E from"node:fs";import"node:fs";import{createRequire as is}from"node:module";import{resolve as Oe,join as ue,dirname as he,relative as at,normalize as ls,sep as it,extname as cs}from"node:path";import"node:url";import us from"fast-glob";function lt(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var ve,U,ct,_,B=Le(()=>{"use strict";L();ve={getGlobOptionsFor:Ne||void 0,SCAN_PATTERNS:Q||void 0,getPatternsFor:nt||void 0,I18N_PATHS:Ae||void 0},U={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};ct={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},_=class n{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,n._instance=this}normalizePath(e){if(!e)return"";try{return ls(e).split(it).join("/")}catch{return String(e).split(it).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=at(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(he(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=is(ue(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=Oe(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Oe(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=Oe(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=E.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:cs(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await E.promises.readFile(e);let a=await E.promises.readFile(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&U.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return E.readFileSync(e);let a=E.readFileSync(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&U.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(he(l)),c=this.pathExists(l);if(c&&!o)return i&&U.info(`Skipping existing file: ${l}`),!1;if(a)return U.info(`[DRY RUN] Would write file: ${l}`),!0;try{await E.promises.mkdir(u,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await lt(async()=>(Buffer.isBuffer(g)?await E.promises.writeFile(l,g):await E.promises.writeFile(l,g,"utf8"),i&&U.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(he(l)),c=this.pathExists(l);if(c&&!o)return i&&U.info(`Skipping existing file: ${l}`),!1;if(a)return U.info(`[DRY RUN] Would write file: ${l}`),!0;try{E.mkdirSync(u,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return Buffer.isBuffer(g)?E.writeFileSync(l,g):E.writeFileSync(l,g,"utf8"),i&&U.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(d){throw new Error(`Failed to write file: ${l}: ${d instanceof Error?d.message:String(d)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&U.info(`Skipping existing file: ${i}`),!1;if(o)return U.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(he(i));try{await E.promises.mkdir(u,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await lt(async()=>(await E.promises.copyFile(e,i),a&&U.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&U.info(`Skipping existing file: ${i}`),!1;if(o)return U.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(he(i));try{E.mkdirSync(u,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return E.copyFileSync(e,i),a&&U.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return E.existsSync(e)}catch(s){return t||U.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return E.readdirSync(e,t)}catch(s){return this.options.debug&&U.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return E.statSync(e)}catch(t){return this.options.debug&&U.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return E.realpathSync(e)}watch(e,t,s){return E.watch(e,t,s)}lstatSync(e){try{return E.lstatSync(e)}catch(t){return this.options.debug&&U.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await E.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{E.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await E.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){E.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return E.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=ue(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Oe(e)),s=this.getAppRoot(),r=at(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(ue(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=r.startsWith(a)?r.slice(a.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:ve.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ve.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(ue(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await us(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=ve.getGlobOptionsFor?ve.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),i=e.framework.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),u={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=i.length>0?await this._globWithNormalization(i,u):[],p=await this._globWithNormalization(l,u);return{frameworkFiles:c,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ve.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=ve.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=r,u={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let a=r,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(ue(t,ct.TOOLING)),a=this.normalizePath(ue(t,ct.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=ue(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(ue(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(he(t))===t)return t;let u=this.normalizePath(he(t));if(u===t)break;t=u,s++}return this.normalizePath(e)}}});var Yt={};es(Yt,{createDndevPlugin:()=>cr});import{execSync as Me,spawn as Hs}from"node:child_process";function q(){return _.getInstance()}function Bt(){return q().getRepoRoot()}function Vt(){return q().resolveRepoPath(".dndev")}function w(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function _e(n,e=Js){return new Promise((t,s)=>{let r="",o=0;n.on("data",a=>{if(o+=a.length,o>e){n.destroy(),s(new Error("Request body too large"));return}r+=a.toString()}),n.on("end",()=>t(r)),n.on("error",s)})}function qs(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function Ys(){let n=q(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",o=Me(r,{encoding:"utf8"}).trim().split(`
|
|
1
|
+
var Qt=Object.defineProperty;var Le=(n,e)=>()=>(n&&(e=n(n=0)),e);var es=(n,e)=>{for(var t in e)Qt(n,t,{get:e[t],enumerable:!0})};function nt(n,e=null){let t=Q[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Ne(n){return rt[n]||rt.base}var We,C,V,j,Ge,xe,Ae,Q,me,ot,Be,Ve,Se,He,rt,L=Le(()=>{"use strict";We={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},C={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env"},V={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},j={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ge={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},xe={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Ae={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},Q={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${Ae.SOURCE_EAGER}/*_*.json`],lazy:[`${Ae.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},me={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},ot=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"],Be=["@donotdev/core/functions","@donotdev/core/server"],Ve={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)/}},Se={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},He=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],rt={base:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...Q.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...Q.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore}}});import*as E from"node:fs";import"node:fs";import{createRequire as is}from"node:module";import{resolve as Oe,join as ue,dirname as he,relative as at,normalize as ls,sep as it,extname as cs}from"node:path";import"node:url";import us from"fast-glob";function lt(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var ve,U,ct,_,B=Le(()=>{"use strict";L();ve={getGlobOptionsFor:Ne||void 0,SCAN_PATTERNS:Q||void 0,getPatternsFor:nt||void 0,I18N_PATHS:Ae||void 0},U={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};ct={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},_=class n{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,n._instance=this}normalizePath(e){if(!e)return"";try{return ls(e).split(it).join("/")}catch{return String(e).split(it).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=at(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(he(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=is(ue(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=Oe(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Oe(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=Oe(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=E.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:cs(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await E.promises.readFile(e);let a=await E.promises.readFile(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&U.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return E.readFileSync(e);let a=E.readFileSync(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&U.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(he(l)),c=this.pathExists(l);if(c&&!o)return i&&U.info(`Skipping existing file: ${l}`),!1;if(a)return U.info(`[DRY RUN] Would write file: ${l}`),!0;try{await E.promises.mkdir(u,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await lt(async()=>(Buffer.isBuffer(g)?await E.promises.writeFile(l,g):await E.promises.writeFile(l,g,"utf8"),i&&U.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(he(l)),c=this.pathExists(l);if(c&&!o)return i&&U.info(`Skipping existing file: ${l}`),!1;if(a)return U.info(`[DRY RUN] Would write file: ${l}`),!0;try{E.mkdirSync(u,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return Buffer.isBuffer(g)?E.writeFileSync(l,g):E.writeFileSync(l,g,"utf8"),i&&U.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(d){throw new Error(`Failed to write file: ${l}: ${d instanceof Error?d.message:String(d)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&U.info(`Skipping existing file: ${i}`),!1;if(o)return U.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(he(i));try{await E.promises.mkdir(u,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await lt(async()=>(await E.promises.copyFile(e,i),a&&U.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&U.info(`Skipping existing file: ${i}`),!1;if(o)return U.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(he(i));try{E.mkdirSync(u,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return E.copyFileSync(e,i),a&&U.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return E.existsSync(e)}catch(s){return t||U.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return E.readdirSync(e,t)}catch(s){return this.options.debug&&U.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return E.statSync(e)}catch(t){return this.options.debug&&U.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return E.realpathSync(e)}watch(e,t,s){return E.watch(e,t,s)}lstatSync(e){try{return E.lstatSync(e)}catch(t){return this.options.debug&&U.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await E.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{E.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await E.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){E.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return E.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=ue(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Oe(e)),s=this.getAppRoot(),r=at(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(ue(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=r.startsWith(a)?r.slice(a.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:ve.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ve.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(ue(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await us(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=ve.getGlobOptionsFor?ve.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),i=e.framework.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),u={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=i.length>0?await this._globWithNormalization(i,u):[],p=await this._globWithNormalization(l,u);return{frameworkFiles:c,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ve.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=ve.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=r,u={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let a=r,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(ue(t,ct.TOOLING)),a=this.normalizePath(ue(t,ct.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=ue(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(ue(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(he(t))===t)return t;let u=this.normalizePath(he(t));if(u===t)break;t=u,s++}return this.normalizePath(e)}}});var Yt={};es(Yt,{createDndevPlugin:()=>cr});import{execSync as Me,spawn as Hs}from"node:child_process";function q(){return _.getInstance()}function Bt(){return q().getRepoRoot()}function Vt(){return q().resolveRepoPath(".dndev")}function w(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function _e(n,e=Js){return new Promise((t,s)=>{let r="",o=0;n.on("data",a=>{if(o+=a.length,o>e){n.destroy(),s(new Error("Request body too large"));return}r+=a.toString()}),n.on("end",()=>t(r)),n.on("error",s)})}function qs(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function Ys(){let n=q(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",o=Me(r,{encoding:"utf8"}).trim().split(`
|
|
2
2
|
`)[0];e.push(o)}catch{}let s=[process.env.NVM_DIR,n.resolvePath(".nvm",t)].filter(Boolean);for(let r of s)try{let o=n.resolvePath("versions/node",r),a=n.readdirSync(o).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/bin/node`,o))}catch{}if(process.env.NVM_BIN&&e.push(n.resolvePath("node",process.env.NVM_BIN)),process.platform==="win32"){e.push("C:\\Program Files\\nodejs\\node.exe");let r=process.env.APPDATA||"";if(r)try{let o=n.resolvePath("nvm",r),a=n.readdirSync(o).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/node.exe`,o))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let r of e)try{let o=n.realpathSync(r);if(o.includes("bun")||!n.pathExists(o))continue;return r}catch{continue}return"node"}function Ht(n){if(!n||typeof n!="string"||n.includes("\0"))return!1;let e=n.split(/[/\\]/).filter(Boolean);for(let t of e)if(t==="."||t===".."||t==="node_modules"||t===".git"||t.startsWith(".")&&t!==".dndev")return!1;return!0}function Ks(n){return n.includes("..")?!1:n.startsWith(".dndev/")||n.startsWith("docs/")||n.startsWith("guides/")}function Jt(n){let e=q(),t=e.getRepoRoot(),s=e.resolvePath(n,t),r=e.normalizePath(t),o=e.normalizePath(s);return!o.startsWith(r+"/")&&o!==r?null:s}async function Xs(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!s)return w(e,{error:"path parameter required"},400);if(!Ht(s))return w(e,{error:"Access denied"},403);let r=Jt(s);if(!r)return w(e,{error:"Access denied"},403);let o=q();if(!o.pathExists(r))return w(e,{error:"File not found"},404);let a=qs(r);if(Zs.has(a)){let i=o.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":qt[a]||"application/octet-stream","Content-Length":i.byteLength}),void e.end(Buffer.from(i))):w(e,{error:"Failed to read file"},500)}if(a===".json")try{let i=await o.read(r);return i===null?w(e,{error:"Failed to read file"},500):w(e,{path:s,content:i})}catch{return w(e,{error:"Invalid JSON"},500)}try{let i=await o.read(r,{format:"text"});if(i===null)return w(e,{error:"Failed to read file"},500);w(e,{path:s,content:i})}catch{w(e,{error:"Failed to read file"},500)}}function Qs(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("dir"),r=q(),o=r.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(c,p){try{let g=r.readdirSync(c,{withFileTypes:!0});for(let d of g){let m=p?`${p}/${d.name}`:d.name;d.isDirectory()&&i.has(d.name)||(d.isDirectory()?(a.push({path:m,name:d.name,isDirectory:!0}),l(r.resolvePath(d.name,c),m)):d.name.endsWith(".md")&&a.push({path:m,name:d.name,isDirectory:!1}))}}catch{}}let u=[".dndev","docs","guides"];if(s){if(s.includes("..")||s.includes("\0"))return w(e,{error:"Access denied"},403);if(!u.includes(s)&&!u.some(d=>s.startsWith(d+"/")))return w(e,{error:"Directory not allowed"},403);let c=r.resolvePath(s,o),p=r.normalizePath(o);if(!r.normalizePath(c).startsWith(p+"/"))return w(e,{error:"Access denied"},403);r.pathExists(c)&&(a.push({path:s,name:r.getBasename(s),isDirectory:!0}),l(c,s))}else{for(let c of u){let p=r.resolveRepoPath(c);r.pathExists(p)&&(a.push({path:c,name:c,isDirectory:!0}),l(p,c))}try{let c=r.readdirSync(o,{withFileTypes:!0});for(let p of c)!p.isDirectory()&&p.name.endsWith(".md")&&a.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}w(e,{entries:a})}async function er(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!s)return w(e,{error:"path parameter required"},400);if(!Ht(s))return w(e,{error:"Access denied"},403);if(!Ks(s))return w(e,{error:"Write not allowed to this path"},403);let r=Jt(s);if(!r)return w(e,{error:"Access denied"},403);try{let o=await _e(n),{content:a}=JSON.parse(o);if(a===void 0)return w(e,{error:"content field required"},400);let i=typeof a=="string"?a:JSON.stringify(a,null,2);await q().write(r,i,{overwrite:!0}),w(e,{ok:!0})}catch{w(e,{error:"Failed to write file"},500)}}async function tr(n,e){try{let t=await _e(n),{line:s,checked:r}=JSON.parse(t);if(typeof s!="number")return w(e,{error:"line number required"},400);let o=q(),a=o.resolveRepoPath(".dndev/implementation.md");if(!o.pathExists(a))return w(e,{error:"implementation.md not found"},404);let i=await o.read(a,{format:"text"});if(i===null)return w(e,{error:"Failed to read file"},500);let l=i.split(`
|
|
3
3
|
`);if(s<0||s>=l.length)return w(e,{error:"Line out of range"},400);let u=l[s];l[s]=r?u.replace("- [ ]","- [x]"):u.replace("- [x]","- [ ]"),await o.write(a,l.join(`
|
|
4
4
|
`),{overwrite:!0}),w(e,{ok:!0,line:l[s]})}catch{w(e,{error:"Failed to update progress"},500)}}async function sr(n,e){try{let t=await _e(n),{id:s,data:r}=JSON.parse(t);if(!s||!r)return w(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(s))return w(e,{error:"Invalid screenshot ID"},400);let o=q(),a=o.resolveRepoPath(".dndev/bugs");o.ensureDirSync(a);let i=Buffer.from(r,"base64"),l=o.resolvePath(`${s}.png`,a);await o.write(l,i,{overwrite:!0}),w(e,{ok:!0,path:`.dndev/bugs/${s}.png`})}catch{w(e,{error:"Failed to save screenshot"},500)}}async function rr(n,e){try{let t=await _e(n),{action:s,phase:r}=JSON.parse(t);if(!s||typeof r!="number")return w(e,{error:"action and phase required"},400);let o=q(),a=Vt();o.ensureDirSync(a);let i=o.resolvePath("protocol.json",a),l={currentPhase:0,phases:{}};if(o.pathExists(i))try{let u=await o.read(i);u&&(l=u)}catch{}s==="start"?(l.currentPhase=r,l.phases[r]||(l.phases[r]={}),l.phases[r].status="active",l.phases[r].startedAt=new Date().toISOString()):s==="complete"&&(l.phases[r]||(l.phases[r]={}),l.phases[r].status="completed",l.phases[r].completedAt=new Date().toISOString()),await o.write(i,l,{overwrite:!0}),w(e,{ok:!0,protocol:l})}catch{w(e,{error:"Failed to update phase"},500)}}function or(n,e){try{let t=Bt(),s=Me("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=Me("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();w(e,{commit:s,branch:r})}catch{w(e,{commit:"unknown",branch:"unknown"})}}async function nr(n,e){try{let t=await _e(n),s=JSON.parse(t);if(!s.id||!s.type||!s.result)return w(e,{error:"id, type, and result required"},400);let r=q(),o=Vt();r.ensureDirSync(o);let a=r.resolvePath("health.json",o),i={actions:[]};if(r.pathExists(a))try{let u=await r.read(a);u&&(i=u)}catch{}Array.isArray(i.actions)||(i.actions=[]);let l=i.actions.findIndex(u=>u.id===s.id);l>=0?i.actions[l]={...i.actions[l],...s}:i.actions.unshift(s),await r.write(a,i,{overwrite:!0}),w(e,{ok:!0})}catch{w(e,{error:"Failed to append action"},500)}}function ar(n,e){let t=q(),s=t.resolveRepoPath("apps");try{let o=t.readdirSync(s).filter(a=>{if(a==="dndev")return!1;let i=t.resolvePath(a,s);return t.statSync(i)?.isDirectory()&&t.pathExists(t.resolvePath("package.json",i))}).map(a=>{try{let i=t.resolvePath(`${a}/package.json`,s),l=t.readSync(i);return{name:a,packageName:l?.name||a}}catch{return{name:a,packageName:a}}});w(e,{apps:o})}catch{w(e,{apps:[]})}}function ir(n){if(Ze)return;let e=q(),t=e.normalizePath(n.config.root),s=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(s))return;try{let i=Me(`fuser ${Gt}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}Ze=!0;let r=e.getRepoRoot(),o=Ys(),a=Hs(o,[s],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(Gt),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{Ze=!1}),process.on("exit",()=>{a.kill()})}function lr(n){let e=q(),t=e.getRepoRoot(),s=[".dndev","docs","guides"];for(let r of s){let o=e.resolveRepoPath(r);if(!e.pathExists(o))continue;let a=e.watch(o,{recursive:!0},(i,l)=>{if(!l||l==="dashboard.json")return;let u=`${r}/${l}`,c=`change:${u}`;Xe.has(c)||(Xe.set(c,!0),setTimeout(()=>Xe.delete(c),300),n.hot.send("dndev:file-changed",{path:u,timestamp:Date.now()}))});n.httpServer?.on("close",()=>a.close())}}function cr(n={}){return{name:"dndev",configureServer(e){let t=Bt();n.debug,e.middlewares.use((s,r,o)=>{let a=s.url;if(!a?.startsWith(Wt))return o();let l=new URL(a,`http://${s.headers.host}`).pathname.slice(Wt.length),u=s.method?.toUpperCase();if(u==="GET")return l==="/file"?void Xs(s,r):l==="/tree"?void Qs(s,r):l==="/git/head"?void or(s,r):l==="/apps"?void ar(s,r):w(r,{error:"Not found"},404);if(u==="POST")return l==="/file"?void er(s,r):l==="/progress/toggle"?void tr(s,r):l==="/bugs/screenshot"?void sr(s,r):l==="/phase"?void rr(s,r):l==="/actions/append"?void nr(s,r):w(r,{error:"Not found"},404);w(r,{error:"Method not allowed"},405)}),ir(e),lr(e)}}}var Wt,Js,qt,Zs,Gt,Ze,Xe,Kt=Le(()=>{"use strict";B();Wt="/api/dndev";Js=5*1024*1024;qt={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},Zs=new Set(Object.keys(qt));Gt=24681,Ze=!1;Xe=new Map});import gs from"@rollup/plugin-strip";import{visualizer as ds}from"rollup-plugin-visualizer";var Ue=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-day-picker/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],ts={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/i18next-http-backend/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function ss(n){let e=n.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function et(n){let e=n.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function tt(n,e=Ue){return e.some(t=>n.includes(t))}function rs(n){for(let[e,t]of Object.entries(ts))if(t.some(s=>n.includes(s)))return e}function os(n){let e=ss(n);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=et(n);if(!t)return;if(tt(t))return"react-core";let s=rs(t);if(s)return s}function ns(n=[]){let e=n.filter(s=>!Ue.includes(s)),t=[...Ue,...e];return function(s){let r=et(s);if(r&&tt(r,t))return"react-core"}}var Qe={development:{manualChunks:void 0},production:{manualChunks:os}};function st(n,e={}){let t=Qe[n]||Qe.production,s=e.reactCore||[];return s.length>0?{manualChunks:ns(s)}:t}B();import*as Y from"@clack/prompts";var re={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 ps(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function ae(n,e){return ps()?`${e}${n}${re.reset}`:n}function I(n,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,a=_.getInstance(),i=null;if(o){let c=a.resolveAppPath(r);a.pathExists(c)||a.mkdir(c),i=a.resolveAppPath(`${r}/${n.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${n} Log Started at ${new Date().toISOString()} ===
|