UNPKG

@mdfriday/foundry

Version:

The core engine of MDFriday. Convert Markdown and shortcodes into fully themed static sites – Hugo-style, powered by TypeScript.

2 lines 729 kB
/* @mdfriday/foundry - bundled */ var ConfigError,Config,DefaultRootConfig,Root,__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__esm=(e,t)=>function(){return e&&(t=(0,e[__getOwnPropNames(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)__defProp(e,n,{get:t[n],enumerable:!0})},__copyProps=(e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of __getOwnPropNames(t))__hasOwnProp.call(e,i)||i===n||__defProp(e,i,{get:()=>t[i],enumerable:!(r=__getOwnPropDesc(t,i))||r.enumerable});return e},__toESM=(e,t,n)=>(n=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?n:__defProp(n,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(__defProp({},"__esModule",{value:!0}),e),init_type=__esm({"internal/domain/config/type.ts"(){new(ConfigError=class extends Error{constructor(e,t){super(e),this.code=t,this.name="ConfigError"}})("configuration not found","CONFIG_NOT_FOUND"),new ConfigError("invalid configuration","INVALID_CONFIG"),new ConfigError("workspace not found","WORKSPACE_NOT_FOUND"),new ConfigError("configuration file not found","CONFIG_FILE_NOT_FOUND"),new ConfigError("invalid configuration format","INVALID_CONFIG_FORMAT")}}),init_config=__esm({"internal/domain/config/entity/config.ts"(){Config=class{configSourceFs;provider;root;dir;module;service;social;language;taxonomy;markdown;constructor(e,t,n,r,i,s,a,o,l,c){this.configSourceFs=e,this.provider=t,this.root=n,this.dir=r,this.module=i,this.service=s,this.social=a,this.language=o,this.taxonomy=l,this.markdown=c}fs(){return this.configSourceFs}getProvider(){return this.provider}theme(){return this.root.defaultTheme()}getDir(){return this.dir}getRoot(){return this.root}getModule(){return this.module}getService(){return this.service}getSocial(){return this.social}getLanguage(){return this.language}getTaxonomy(){return this.taxonomy}getMarkdown(){return this.markdown}setLanguage(e){this.language=e}setTaxonomy(e){this.taxonomy=e}setMarkdown(e){this.markdown=e}validate(){let e=!0;return this.language&&(e=e&&this.language.validate()),this.markdown&&(e=e&&this.markdown.validate()),e}}}}),init_root=__esm({"internal/domain/config/vo/root.ts"(){DefaultRootConfig={baseURL:"",title:"",theme:[],timeout:"30s",contentDir:"content",dataDir:"data",layoutDir:"layouts",staticDir:"static",archetypeDir:"archetypes",assetDir:"assets",publishDir:"public",buildDrafts:!1,buildExpired:!1,buildFuture:!1,copyright:"",defaultContentLanguage:"en",defaultContentLanguageInSubdir:!1,disableAliases:!1,disablePathToLower:!1,disableKinds:[],disableLanguages:[],renderSegments:[],disableHugoGeneratorInject:!1,disableLiveReload:!1,enableEmoji:!1}}});var Module,init_root2=__esm({"internal/domain/config/entity/root.ts"(){init_root(),Root=class{rootConfig;rootParams;constructor(e,t={}){this.rootConfig=e,this.rootParams=t}defaultTheme(){return this.rootConfig.theme.length>0?this.rootConfig.theme[0]:""}compiledTimeout(){const e=this.rootConfig.timeout;if(/^\d+$/.test(e))return 1e3*parseInt(e,10);const t=e.match(/^(\d+)([smh])$/);if(t){const e=parseInt(t[1],10);switch(t[2]){case"s":return 1e3*e;case"m":return 60*e*1e3;case"h":return 60*e*60*1e3}}return 3e4}baseUrl(){return this.rootConfig.baseURL}configParams(){return this.rootParams}siteTitle(){return this.rootConfig.title}getRootConfig(){return this.rootConfig}getThemes(){return this.rootConfig.theme}getDefaultContentLanguage(){return this.rootConfig.defaultContentLanguage}shouldBuildDrafts(){return this.rootConfig.buildDrafts}shouldBuildFuture(){return this.rootConfig.buildFuture}shouldBuildExpired(){return this.rootConfig.buildExpired}}}}),init_module=__esm({"internal/domain/config/vo/module.ts"(){}});var DefaultServiceConfig,Service,init_module2=__esm({"internal/domain/config/entity/module.ts"(){init_module(),Module=class{moduleConfig;constructor(e){this.moduleConfig=e}importPaths(){return this.moduleConfig.imports.map(e=>e.path)}getModuleConfig(){return this.moduleConfig}getImports(){return this.moduleConfig.imports}getMounts(){return this.moduleConfig.mounts}importCount(){return this.moduleConfig.imports.length}mountCount(){return this.moduleConfig.mounts.length}hasImports(){return this.moduleConfig.imports.length>0}hasMounts(){return this.moduleConfig.mounts.length>0}findImport(e){return this.moduleConfig.imports.find(t=>t.path===e)}findMount(e){return this.moduleConfig.mounts.find(t=>t.source===e)}}}}),init_service=__esm({"internal/domain/config/vo/service.ts"(){DefaultServiceConfig={disqus:{disable:!1,shortname:""},googleAnalytics:{disable:!1,respectDoNotTrack:!1,id:""},rss:{limit:0},x:{respectDoNotTrack:!1,disableInlineCSS:!1}}}});var LTR_LANGUAGES,RTL_LANGUAGES,ALL_LANGUAGES,LANGUAGE_MAP,CODE_NAME_MAP,DefaultLanguageService,serviceInstance,init_service2=__esm({"internal/domain/config/entity/service.ts"(){init_service(),Service=class{serviceConfig;constructor(e){this.serviceConfig=e}isGoogleAnalyticsEnabled(){return!this.serviceConfig.googleAnalytics.disable}googleAnalyticsID(){return this.serviceConfig.googleAnalytics.id}isGoogleAnalyticsRespectDoNotTrack(){return this.serviceConfig.googleAnalytics.respectDoNotTrack}isDisqusEnabled(){return!this.serviceConfig.disqus.disable}disqusShortname(){return this.serviceConfig.disqus.shortname}isXRespectDoNotTrack(){return this.serviceConfig.x.respectDoNotTrack}isXDisableInlineCSS(){return this.serviceConfig.x.disableInlineCSS}rssLimit(){return this.serviceConfig.rss.limit}getServiceConfig(){return this.serviceConfig}getGoogleAnalytics(){return this.serviceConfig.googleAnalytics}getDisqus(){return this.serviceConfig.disqus}getRSS(){return this.serviceConfig.rss}hasEnabledServices(){return this.isGoogleAnalyticsEnabled()||this.isDisqusEnabled()}}}}),init_data=__esm({"pkg/lang/data.ts"(){LTR_LANGUAGES=[{code:"en",name:"English",direction:"ltr",englishName:"English"},{code:"zh",name:"中文",direction:"ltr",englishName:"Chinese"},{code:"ja",name:"日本語",direction:"ltr",englishName:"Japanese"},{code:"ko",name:"한국어",direction:"ltr",englishName:"Korean"},{code:"fr",name:"Français",direction:"ltr",englishName:"French"},{code:"de",name:"Deutsch",direction:"ltr",englishName:"German"},{code:"es",name:"Español",direction:"ltr",englishName:"Spanish"},{code:"pt",name:"Português",direction:"ltr",englishName:"Portuguese"},{code:"ru",name:"Русский",direction:"ltr",englishName:"Russian"},{code:"hi",name:"हिंदी",direction:"ltr",englishName:"Hindi"},{code:"it",name:"Italiano",direction:"ltr",englishName:"Italian"},{code:"nl",name:"Nederlands",direction:"ltr",englishName:"Dutch"},{code:"tr",name:"Türkçe",direction:"ltr",englishName:"Turkish"},{code:"vi",name:"Tiếng Việt",direction:"ltr",englishName:"Vietnamese"},{code:"th",name:"ไทย",direction:"ltr",englishName:"Thai"}],RTL_LANGUAGES=[],ALL_LANGUAGES=[...LTR_LANGUAGES,...RTL_LANGUAGES],LANGUAGE_MAP=ALL_LANGUAGES.reduce((e,t)=>(e[t.code]=t,e),{}),CODE_NAME_MAP=ALL_LANGUAGES.reduce((e,t)=>(e[t.code]=t.name,e),{})}});function getLanguageService(){return serviceInstance||(serviceInstance=new DefaultLanguageService),serviceInstance}function createLanguageService(){return new DefaultLanguageService}var lang,languages,init_service3=__esm({"pkg/lang/service.ts"(){init_data(),DefaultLanguageService=class{getAllCodes(){return ALL_LANGUAGES.map(e=>e.code)}getAllNames(){return ALL_LANGUAGES.map(e=>e.name)}getCodesByDirection(e){return("ltr"===e?LTR_LANGUAGES:RTL_LANGUAGES).map(e=>e.code)}getNamesByDirection(e){return("ltr"===e?LTR_LANGUAGES:RTL_LANGUAGES).map(e=>e.name)}getCodeNameMap(){return{...CODE_NAME_MAP}}getCodeNameMapByDirection(e){return("ltr"===e?LTR_LANGUAGES:RTL_LANGUAGES).reduce((e,t)=>(e[t.code]=t.name,e),{})}getNameByCode(e){return LANGUAGE_MAP[e]?.name}getLanguageInfo(e){const t=LANGUAGE_MAP[e];return t?{...t}:void 0}isSupported(e){return e in LANGUAGE_MAP}getDirection(e){return LANGUAGE_MAP[e]?.direction}isLTR(e){return"ltr"===LANGUAGE_MAP[e]?.direction}isRTL(e){return"rtl"===LANGUAGE_MAP[e]?.direction}},serviceInstance=null}}),lang_exports={};__export(lang_exports,{ALL_LANGUAGES:()=>ALL_LANGUAGES,CODE_NAME_MAP:()=>CODE_NAME_MAP,DefaultLanguageService:()=>DefaultLanguageService,LANGUAGE_MAP:()=>LANGUAGE_MAP,LTR_LANGUAGES:()=>LTR_LANGUAGES,RTL_LANGUAGES:()=>RTL_LANGUAGES,createLanguageService:()=>createLanguageService,getLanguageService:()=>getLanguageService,lang:()=>lang,languages:()=>languages});var DefaultLanguageConfig,Language,init_lang=__esm({"pkg/lang/index.ts"(){init_data(),init_service3(),init_service3(),lang=getLanguageService(),languages={getAllCodes:()=>lang.getAllCodes(),getAllNames:()=>lang.getAllNames(),getCodesByDirection:e=>lang.getCodesByDirection(e),getNamesByDirection:e=>lang.getNamesByDirection(e),getCodeNameMap:()=>lang.getCodeNameMap(),getCodeNameMapByDirection:e=>lang.getCodeNameMapByDirection(e),getNameByCode:e=>lang.getNameByCode(e),getLanguageInfo:e=>lang.getLanguageInfo(e),isSupported:e=>lang.isSupported(e),getDirection:e=>lang.getDirection(e),isLTR:e=>lang.isLTR(e),isRTL:e=>lang.isRTL(e)}}}),init_language=__esm({"internal/domain/config/vo/language.ts"(){init_lang(),DefaultLanguageConfig={languageCode:"en",languageName:"English",title:"",weight:0,contentDir:"content",disabled:!1,params:{}}}});var DefaultTaxonomies,init_language2=__esm({"internal/domain/config/entity/language.ts"(){init_language(),Language=class{defaultLang;configs;indices;constructor(e){this.configs=e,this.defaultLang=this.calculateDefaultLanguage(),this.indices=[],this.setIndices()}calculateDefaultLanguage(){if(0===Object.keys(this.configs).length)return"en";let e="",t=Number.MAX_SAFE_INTEGER;for(const[n,r]of Object.entries(this.configs))r.weight<t&&(t=r.weight,e=n);return e||Object.keys(this.configs)[0]}languages(){return Object.values(this.configs)}defaultLanguage(){return this.defaultLang}isLanguageValid(e){return Object.prototype.hasOwnProperty.call(this.configs,e)}otherLanguageKeys(){return Object.keys(this.configs).filter(e=>e!==this.defaultLang)}getRelDir(e,t){const n=this.configs[t];if(!n)throw new Error(`Language "${t}" not found`);return n.contentDir||"content"}validate(){return e=this.configs,t=this.defaultLang,Object.prototype.hasOwnProperty.call(e,t);var e,t}setIndices(){const e=[];this.configs[this.defaultLang]&&e.push(this.defaultLang);for(const t of Object.keys(this.configs))t!==this.defaultLang&&e.push(t);this.indices=e}languageKeys(){return[...this.indices]}languageIndexes(){return this.indices.map((e,t)=>t)}getLanguageIndex(e){const t=this.indices.indexOf(e);if(-1===t)throw new Error("Language not found in indices");return t}getLanguageByIndex(e){if(e<0||e>=this.indices.length)throw new Error("Language index out of range");return this.indices[e]}getLanguageName(e){const t=this.configs[e];return t?t.languageName:""}getLanguageConfig(e){return this.configs[e]}getConfigs(){return this.configs}}}});function cleanTreeKey(...e){let t="";return e.length>0&&(t=e[0],e.length>1&&(t=e.join("/"))),t=t.replace(/^[.\s/]+|[.\s/]+$/g,""),t=t.toLowerCase(),t=t.replace(/\\/g,"/"),""===t||"/"===t?"":(t.startsWith("/")||(t="/"+t),t)}var Taxonomy,init_taxonomy=__esm({"internal/domain/config/vo/taxonomy.ts"(){DefaultTaxonomies={tag:"tags",category:"categories"}}});function newTaxonomy(e){const t=function(e){if(e.taxonomies&&"object"==typeof e.taxonomies){const t={};for(const[n,r]of Object.entries(e.taxonomies))"string"==typeof r&&(t[n]=r);return t}return{...DefaultTaxonomies}}(e);return new Taxonomy(t)}var DefaultSocialPlatformTemplates,Social,init_taxonomy2=__esm({"internal/domain/config/entity/taxonomy.ts"(){init_taxonomy(),Taxonomy=class{taxonomies;views;viewsByTreeKey;constructor(e){this.taxonomies=e,this.views=[],this.viewsByTreeKey={},this.setupViews()}getViews(){return[...this.views]}getTaxonomies(){return{...this.taxonomies}}getViewByTreeKey(e){return this.viewsByTreeKey[e]}hasTaxonomy(e){return Object.prototype.hasOwnProperty.call(this.taxonomies,e)}getPluralForm(e){return this.taxonomies[e]}getSingularForm(e){for(const[t,n]of Object.entries(this.taxonomies))if(n===e)return t}getSingularForms(){return Object.keys(this.taxonomies)}getPluralForms(){return Object.values(this.taxonomies)}setupViews(){this.views=function(e){const t=[];for(const[n,r]of Object.entries(e))t.push({singular:n,plural:r,pluralTreeKey:cleanTreeKey(r)});return t.sort((e,t)=>e.plural.localeCompare(t.plural)),t}(this.taxonomies),this.viewsByTreeKey={};for(const e of this.views)this.viewsByTreeKey[e.pluralTreeKey]=e}getViewCount(){return this.views.length}isEmpty(){return 0===Object.keys(this.taxonomies).length}}}}),init_social=__esm({"internal/domain/config/vo/social.ts"(){DefaultSocialPlatformTemplates=[{id:"email",title:"Email me"},{id:"facebook",title:"Facebook"},{id:"github",title:"GitHub"},{id:"gitlab",title:"GitLab"},{id:"bitbucket",title:"Bitbucket"},{id:"twitter",title:"Twitter"},{id:"slack",title:"Slack"},{id:"reddit",title:"Reddit"},{id:"linkedin",title:"LinkedIn"},{id:"xing",title:"Xing"},{id:"stackoverflow",title:"StackOverflow"},{id:"snapchat",title:"Snapchat"},{id:"instagram",title:"Instagram"},{id:"youtube",title:"Youtube"},{id:"soundcloud",title:"SoundCloud"},{id:"spotify",title:"Spotify"},{id:"bandcamp",title:"Bandcamp"},{id:"itchio",title:"Itch.io"},{id:"keybase",title:"Keybase"},{id:"vk",title:"VK"},{id:"paypal",title:"PayPal"},{id:"telegram",title:"Telegram"},{id:"500px",title:"500px"},{id:"codepen",title:"CodePen"},{id:"kaggle",title:"kaggle"},{id:"mastodon",title:"Mastodon"},{id:"weibo",title:"Weibo"},{id:"medium",title:"Medium"},{id:"discord",title:"Discord"},{id:"strava",title:"Strava"},{id:"steam",title:"Steam"},{id:"quora",title:"Quora"},{id:"amazonwishlist",title:"Amazon Wishlist"},{id:"slideshare",title:"Slideshare"},{id:"angellist",title:"AngelList"},{id:"about",title:"About"},{id:"lastfm",title:"Last.fm"},{id:"bluesky",title:"Bluesky"},{id:"goodreads",title:"Goodreads"}]}});var DefaultMarkdownPlugins,DefaultMarkdownConfig,Markdown,init_social2=__esm({"internal/domain/config/entity/social.ts"(){init_social(),Social=class{socialConfig;constructor(e){this.socialConfig=e}getUserConfig(){return this.socialConfig.userConfig}getPlatformTemplates(){return this.socialConfig.platformTemplates}getPlatformTemplate(e){return t=e,DefaultSocialPlatformTemplates.find(e=>e.id===t);var t}isPlatformConfigured(e){return e in this.socialConfig.userConfig}getConfiguredPlatforms(){return Object.keys(this.socialConfig.userConfig)}getProcessedSocialLinks(){const e=[];for(const[t,n]of Object.entries(this.socialConfig.userConfig)){const r=this.getPlatformTemplate(t);r?e.push({id:t,title:r.title,url:n.link}):e.push({id:t,title:t.charAt(0).toUpperCase()+t.slice(1),url:n.link})}return e}getSocialLink(e){const t=this.socialConfig.userConfig[e];if(!t)return;const n=this.getPlatformTemplate(e);return n?{id:e,title:n.title,url:t.link}:{id:e,title:e.charAt(0).toUpperCase()+e.slice(1),url:t.link}}hasSocialLinks(){return Object.keys(this.socialConfig.userConfig).length>0}getSocialLinkCount(){return Object.keys(this.socialConfig.userConfig).length}getAvailablePlatforms(){return this.socialConfig.platformTemplates.map(e=>e.id)}getSocialConfig(){return this.socialConfig}}}}),init_markdown=__esm({"internal/domain/config/vo/markdown.ts"(){DefaultMarkdownPlugins={wikilink:!0,tag:!0,callout:!0,latex:!0,mermaid:!0},DefaultMarkdownConfig={useInternalRenderer:!1,plugins:{...DefaultMarkdownPlugins}}}});var import_path,DEFAULT_PUBLISH_DIR,Dir,DefaultConfigProvider,path2,ConfigLoader,ConfigSourceDescriptor,path3,init_markdown2=__esm({"internal/domain/config/entity/markdown.ts"(){init_markdown(),Markdown=class{markdownConfig;constructor(e){this.markdownConfig=e}useInternalRenderer(){return this.markdownConfig.useInternalRenderer}isWikilinkEnabled(){return this.markdownConfig.plugins.wikilink}isTagEnabled(){return this.markdownConfig.plugins.tag}isCalloutEnabled(){return this.markdownConfig.plugins.callout}isLatexEnabled(){return this.markdownConfig.plugins.latex}isMermaidEnabled(){return this.markdownConfig.plugins.mermaid}getMarkdownConfig(){return this.markdownConfig}getPlugins(){return this.markdownConfig.plugins}hasEnabledPlugins(){const e=this.markdownConfig.plugins;return e.wikilink||e.tag||e.callout||e.latex||e.mermaid}validate(){return!this.markdownConfig.useInternalRenderer||this.hasEnabledPlugins()}}}}),init_dir=__esm({"internal/domain/config/entity/dir.ts"(){import_path=__toESM(require("path")),DEFAULT_PUBLISH_DIR="public",Dir=class{workingDir;themesDir;publishDir;constructor(e,t,n=DEFAULT_PUBLISH_DIR){this.workingDir=e,this.themesDir=t,this.publishDir=n}getWorkingDir(){return import_path.default.resolve(this.workingDir)}getThemesDir(){return import_path.default.resolve(this.themesDir)}getThemesCacheDir(){return import_path.default.resolve(this.themesDir,".cache")}getPublishDir(){return import_path.default.resolve(this.publishDir)}}}}),init_provider=__esm({"internal/domain/config/factory/provider.ts"(){DefaultConfigProvider=class{root;keyCache;constructor(e={}){this.root=this.prepareParams(e),this.keyCache=new Map}prepareParams(e){const t={};for(const[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}getNestedKeyAndMap(e,t){let n;this.keyCache.has(e)?n=this.keyCache.get(e):(n=e.split("."),this.keyCache.set(e,n));let r=this.root;for(let e=0;e<n.length-1;e++){const i=n[e];if(!(i in r)){if(!t)return["",null];r[i]={}}const s=r[i];if("object"!=typeof s||null===s)return["",null];r=s}return[n[n.length-1],r]}getString(e){const t=this.get(e);return String(t||"")}getInt(e){const t=this.get(e),n=Number(t);return isNaN(n)?0:Math.floor(n)}getBool(e){const t=this.get(e);return"boolean"==typeof t?t:"string"==typeof t?"true"===t.toLowerCase():Boolean(t)}getParams(e){const t=this.get(e);return t&&"object"==typeof t?t:{}}getStringMap(e){const t=this.get(e);return t&&"object"==typeof t?t:{}}getStringMapString(e){const t=this.get(e);if(t&&"object"==typeof t){const e={};for(const[n,r]of Object.entries(t))e[n]=String(r);return e}return{}}getStringSlice(e){const t=this.get(e);return Array.isArray(t)?t.map(e=>String(e)):[]}get(e){if(""===e)return this.root;const[t,n]=this.getNestedKeyAndMap(e.toLowerCase(),!1);return null!==n?n[t]:void 0}set(e,t){const n=e.toLowerCase();if(""===n)return void(t&&"object"==typeof t?Object.assign(this.root,this.prepareParams(t)):this.root[n]=t);const[r,i]=this.getNestedKeyAndMap(n,!0);null!==i&&(r in i&&"object"==typeof i[r]&&"object"==typeof t&&null!==t?Object.assign(i[r],t):i[r]=t)}keys(){return Object.keys(this.root)}merge(e,t){const n=e.toLowerCase();if(""===n)return void(t&&"object"==typeof t&&Object.assign(this.root,this.prepareParams(t)));const[r,i]=this.getNestedKeyAndMap(n,!0);null!==i&&(r in i&&"object"==typeof i[r]&&"object"==typeof t&&null!==t?Object.assign(i[r],t):i[r]=t)}setDefaults(e){const t=this.prepareParams(e);for(const[e,n]of Object.entries(t))e in this.root||(this.root[e]=n)}setDefaultMergeStrategy(){}walkParams(e){const t=n=>{if(n&&"object"==typeof n&&!Array.isArray(n)){if(e(n))return!0;for(const e of Object.values(n))if(t(e))return!0}return!1};t(this.root)}isSet(e){const[t,n]=this.getNestedKeyAndMap(e.toLowerCase(),!1);return null!==n&&t in n}}}}),init_loader=__esm({"internal/domain/config/factory/loader.ts"(){init_provider(),path2=__toESM(require("path")),ConfigLoader=class{cfg;sourceDescriptor;baseDirs;constructor(e,t){this.cfg=new DefaultConfigProvider,this.sourceDescriptor=e,this.baseDirs=t}async loadConfigByDefault(){const e=this.sourceDescriptor.filename();if(await this.loadProvider(e),this.applyDefaultConfig(),this.cfg.setDefaultMergeStrategy(),!this.cfg.isSet("languages")){const e=this.cfg.getString("defaultContentLanguage");this.cfg.set("languages",{[e]:{}})}return this.cfg}deleteMergeStrategies(){this.cfg.walkParams(e=>!1)}async loadProvider(e){const t=this.baseDirs.workingDir;let n;n=path2.isAbsolute(e)?e:path2.join(t,e);let r="";if(""!==path2.extname(e)&&await this.fileExists(n)&&(r=n),""===r)throw new Error("Unable to locate config file or config directory.");const i=await this.loadConfigFromFile(r);this.cfg.set("",i)}applyDefaultConfig(){this.cfg.setDefaults({baseURL:"",cleanDestinationDir:!1,watch:!1,contentDir:"content",resourceDir:"resources",publishDir:"public",publishDirOrig:"public",themesDir:"themes",assetDir:"assets",layoutDir:"layouts",i18nDir:"i18n",dataDir:"data",archetypeDir:"archetypes",configDir:"config",staticDir:"static",buildDrafts:!1,buildFuture:!1,buildExpired:!1,params:{},environment:"production",uglyURLs:!1,verbose:!1,ignoreCache:!1,canonifyURLs:!1,relativeURLs:!1,removePathAccents:!1,titleCaseStyle:"AP",taxonomies:{tag:"tags",category:"categories"},permalinks:{},sitemap:{priority:-1,filename:"sitemap.xml"},menus:{},disableLiveReload:!1,pluralizeListTitles:!0,capitalizeListTitles:!0,forceSyncStatic:!1,footnoteAnchorPrefix:"",footnoteReturnLinkContents:"",newContentEditor:"",paginate:10,paginatePath:"page",summaryLength:70,rssLimit:-1,sectionPagesMenu:"",disablePathToLower:!1,hasCJKLanguage:!1,enableEmoji:!1,defaultContentLanguage:"en",defaultContentLanguageInSubdir:!1,enableMissingTranslationPlaceholders:!1,enableGitInfo:!1,ignoreFiles:[],disableAliases:!1,debug:!1,disableFastRender:!1,timeout:"30s",timeZone:"",enableInlineShortcodes:!1})}async fileExists(e){try{const t=this.sourceDescriptor.fs();return!(await t.stat(e)).isDir()}catch{return!1}}async loadConfigFromFile(e){const t=this.sourceDescriptor.fs(),n=await t.open(e);try{const e=new Uint8Array(1048576),{bytesRead:t}=await n.read(e),r=(new TextDecoder).decode(e.slice(0,t));try{return JSON.parse(r)}catch{return{}}}finally{await n.close()}}}}}),init_sourcedescriptor=__esm({"internal/domain/config/factory/sourcedescriptor.ts"(){ConfigSourceDescriptor=class{fileSystem;configFilename;constructor(e,t){this.fileSystem=e,this.configFilename=t}fs(){return this.fileSystem}filename(){return this.configFilename}}}});async function loadConfigWithParams(e,t,n,r,i={}){const s={workingDir:path3.resolve(n),modulesDir:path3.resolve(r),publishDir:path3.resolve(DEFAULT_PUBLISH_DIR),cacheDir:""};s.cacheDir=await async function(e,t){if(""!==t)return t;const n=process.env.HOME||process.env.USERPROFILE||"",r=path3.join(n,".cache","mdf");try{return await e.mkdirAll(r,493),r}catch{return path3.join("/tmp","hugo-cache")}}(e,s.cacheDir);const a=new ConfigLoader(function(e,t){return new ConfigSourceDescriptor(e,t)}(e,t),s);try{const t=await a.loadConfigByDefault();for(const[e,n]of Object.entries(i))t.set(e,n);const n=path3.resolve(t.get("publishDir")||DEFAULT_PUBLISH_DIR);return await e.mkdirAll(n,511),function(e,t,n,r,i,s,a,o,l,c){return new Config(e,t,n,r,i,s,a,o,l,c)}(e,t,function(e,t={}){const n=function(e){return{baseURL:e.baseurl||DefaultRootConfig.baseURL,title:e.title||DefaultRootConfig.title,theme:e.theme||DefaultRootConfig.theme,timeout:e.timeout||DefaultRootConfig.timeout,contentDir:e.contentDir||DefaultRootConfig.contentDir,dataDir:e.dataDir||DefaultRootConfig.dataDir,layoutDir:e.layoutDir||DefaultRootConfig.layoutDir,staticDir:e.staticDir||DefaultRootConfig.staticDir,archetypeDir:e.archetypeDir||DefaultRootConfig.archetypeDir,assetDir:e.assetDir||DefaultRootConfig.assetDir,publishDir:e.publishDir||DefaultRootConfig.publishDir,buildDrafts:void 0!==e.buildDrafts?e.buildDrafts:DefaultRootConfig.buildDrafts,buildExpired:void 0!==e.buildExpired?e.buildExpired:DefaultRootConfig.buildExpired,buildFuture:void 0!==e.buildFuture?e.buildFuture:DefaultRootConfig.buildFuture,copyright:e.copyright||DefaultRootConfig.copyright,defaultContentLanguage:e.defaultContentLanguage||DefaultRootConfig.defaultContentLanguage,defaultContentLanguageInSubdir:void 0!==e.defaultContentLanguageInSubdir?e.defaultContentLanguageInSubdir:DefaultRootConfig.defaultContentLanguageInSubdir,disableAliases:void 0!==e.disableAliases?e.disableAliases:DefaultRootConfig.disableAliases,disablePathToLower:void 0!==e.disablePathToLower?e.disablePathToLower:DefaultRootConfig.disablePathToLower,disableKinds:e.disableKinds||DefaultRootConfig.disableKinds,disableLanguages:e.disableLanguages||DefaultRootConfig.disableLanguages,renderSegments:e.renderSegments||DefaultRootConfig.renderSegments,disableHugoGeneratorInject:void 0!==e.disableHugoGeneratorInject?e.disableHugoGeneratorInject:DefaultRootConfig.disableHugoGeneratorInject,disableLiveReload:void 0!==e.disableLiveReload?e.disableLiveReload:DefaultRootConfig.disableLiveReload,enableEmoji:void 0!==e.enableEmoji?e.enableEmoji:DefaultRootConfig.enableEmoji}}(e);return new Root(n,t)}(t.get(""),t.getParams("params")),function(e,t,n){return new Dir(e,t,n)}(s.workingDir,s.modulesDir,n),function(e){const t=function(e){const t={mounts:[],imports:[]};return e.mounts&&Array.isArray(e.mounts)&&(t.mounts=e.mounts.map(e=>({source:e.source||"",target:e.target||"",lang:e.lang}))),e.imports&&Array.isArray(e.imports)&&(t.imports=e.imports.map(e=>({path:e.path||"",url:e.url,version:e.version,mounts:e.mounts||[]}))),t}(e);return new Module(t)}(t.get("module")||{}),function(e){const t=function(e){const t={disqus:{...DefaultServiceConfig.disqus},googleAnalytics:{...DefaultServiceConfig.googleAnalytics},rss:{...DefaultServiceConfig.rss},x:{...DefaultServiceConfig.x}};return e&&(e.disqus&&(t.disqus.shortname=e.disqus.shortname||t.disqus.shortname),e.googleAnalytics&&(t.googleAnalytics.id=e.googleAnalytics.id||t.googleAnalytics.id),e.rss&&(t.rss.limit=void 0!==e.rss.limit?e.rss.limit:t.rss.limit)),t}(e);return new Service(t)}(t.get("services")),function(e){const t=function(e){const t={userConfig:{},platformTemplates:[...DefaultSocialPlatformTemplates]};if(e&&"object"==typeof e)for(const[n,r]of Object.entries(e))if(r&&"object"==typeof r){const e=r;e.link&&(t.userConfig[n]={link:e.link})}return t}(e);return new Social(t)}(t.get("social")),function(e){const t=function(e){const t={};if(!e||0===Object.keys(e).length)return t.en={...DefaultLanguageConfig,title:e?.title||DefaultLanguageConfig.title,params:e?.params||DefaultLanguageConfig.params},t;for(const[n,r]of Object.entries(e)){const i=r,s=languages.getNameByCode(n)||n;t[n]={languageCode:n,languageName:s,title:i.title||e.title||"",weight:void 0!==i.weight?i.weight:0,contentDir:i.contentDir||"content",disabled:void 0!==i.disabled&&i.disabled,params:i.params||e.params||{}}}return t}(e);return new Language(t)}(t.get("languages")),t.isSet("taxonomies")?newTaxonomy(t.get("taxonomies")):newTaxonomy(t.get("")),function(e){const t=function(e){const t={useInternalRenderer:DefaultMarkdownConfig.useInternalRenderer,plugins:{...DefaultMarkdownConfig.plugins}};return e&&(void 0!==e.useInternalRenderer&&(t.useInternalRenderer=Boolean(e.useInternalRenderer)),e.plugins&&(void 0!==e.plugins.wikilink&&(t.plugins.wikilink=Boolean(e.plugins.wikilink)),void 0!==e.plugins.tag&&(t.plugins.tag=Boolean(e.plugins.tag)),void 0!==e.plugins.callout&&(t.plugins.callout=Boolean(e.plugins.callout)),void 0!==e.plugins.latex&&(t.plugins.latex=Boolean(e.plugins.latex)),void 0!==e.plugins.mermaid&&(t.plugins.mermaid=Boolean(e.plugins.mermaid)))),t}(e);return new Markdown(t)}(t.get("markdown")))}finally{a.deleteMergeStrategies()}}var ComponentFolderContent,ComponentFolders,ModuleError,path4,Mount,util,Logger,globalLoggerManager,init_config2=__esm({"internal/domain/config/factory/config.ts"(){init_config(),init_dir(),init_root2(),init_module2(),init_service2(),init_social2(),init_language2(),init_taxonomy2(),init_markdown2(),init_loader(),init_sourcedescriptor(),path3=__toESM(require("path"))}}),init_config3=__esm({"internal/domain/config/index.ts"(){init_type(),init_config(),init_root2(),init_module2(),init_service2(),init_language2(),init_taxonomy2(),init_social2(),init_markdown2(),init_root(),init_module(),init_service(),init_language(),init_taxonomy(),init_social(),init_markdown(),init_config2()}}),init_type2=__esm({"internal/domain/module/type.ts"(){ComponentFolders=["workflows","prompts",ComponentFolderContent="content","layouts","static","assets","i18n"],new(ModuleError=class extends Error{constructor(e,t){super(e),this.code=t,this.name="ModuleError"}})("module not found","MODULE_NOT_FOUND"),new ModuleError("download failed","DOWNLOAD_FAILED"),new ModuleError("invalid zip file","INVALID_ZIP"),new ModuleError("mount failed","MOUNT_FAILED")}}),init_mount=__esm({"internal/domain/module/vo/mount.ts"(){path4=__toESM(require("path")),Mount=class e{constructor(e,t,n=""){this.sourcePath=e,this.targetPath=t,this.language=n}source(){return this.sourcePath}target(){return this.targetPath}lang(){return this.language}setLanguage(e){this.language=e}component(){return this.targetPath.split(path4.sep)[0]||""}componentAndName(){const e=this.targetPath.split(path4.sep);return{component:e[0]||"",name:e.slice(1).join(path4.sep)}}copy(){return new e(this.sourcePath,this.targetPath,this.language)}equals(e){return this.sourcePath===e.sourcePath&&this.targetPath===e.targetPath&&this.language===e.language}toConfig(){const e={sourcePath:this.sourcePath,targetPath:this.targetPath};return this.language&&(e.language=this.language),e}toString(){return`${this.sourcePath} -> ${this.targetPath} (${this.language})`}}}}),init_types=__esm({"pkg/log/types.ts"(){}}),init_logger=__esm({"pkg/log/logger.ts"(){util=__toESM(require("util")),init_types(),Logger=class e{config;fields;constructor(e){this.config={enableCaller:!0,jsonFormat:!0,...e},this.fields={}}shouldLog(e){const t=["debug","info","warn","error","fatal"],n=t.indexOf(this.config.level);return t.indexOf(e)>=n}getCaller(){if(!this.config.enableCaller)return;const e=(new Error).stack;if(!e)return;const t=e.split("\n")[4];if(!t)return;const n=t.match(/at .* \((.+):(\d+):(\d+)\)/);if(n){const[,e,t]=n;return`${e.split("/").pop()}:${t}`}const r=t.match(/at (.+):(\d+):(\d+)/);if(r){const[,e,t]=r;return`${e.split("/").pop()}:${t}`}}formatMessage(e,t){return 0===t.length?e:util.format(e,...t)}writeLog(e,t){if(!this.shouldLog(e))return;const n={level:e,timestamp:(new Date).toISOString(),message:t,...this.fields},r=this.getCaller();r&&(n.caller=r);const i=this.config.jsonFormat?JSON.stringify(n):this.formatPlainText(n);"error"===e||"fatal"===e?process.stderr.write(i+"\n"):process.stdout.write(i+"\n"),"fatal"===e&&process.exit(1)}formatPlainText(e){const t=[e.timestamp,e.level.toUpperCase()];e.caller&&t.push(`[${e.caller}]`),t.push(e.message);const n=Object.keys(e).filter(e=>!["level","timestamp","message","caller"].includes(e)).map(t=>`${t}=${JSON.stringify(e[t])}`).join(" ");return n&&t.push(n),t.join(" ")}debug(e,...t){this.writeLog("debug",this.formatMessage(e,t))}info(e,...t){this.writeLog("info",this.formatMessage(e,t))}warn(e,...t){this.writeLog("warn",this.formatMessage(e,t))}error(e,...t){this.writeLog("error",this.formatMessage(e,t))}fatal(e,...t){this.writeLog("fatal",this.formatMessage(e,t))}debugf(e,...t){this.writeLog("debug",this.formatMessage(e,t))}infof(e,...t){this.writeLog("info",this.formatMessage(e,t))}warnf(e,...t){this.writeLog("warn",this.formatMessage(e,t))}errorf(e,...t){this.writeLog("error",this.formatMessage(e,t))}fatalf(e,...t){this.writeLog("fatal",this.formatMessage(e,t))}with(t){const n=new e(this.config);return n.fields={...this.fields,...t},n}}}}),init_http=__esm({"pkg/log/http.ts"(){}});function getDomainLogger(e,t){return globalLoggerManager.getLogger(e,t)}var path5,http,https,log,NodeHttpClient,init_manager=__esm({"pkg/log/manager.ts"(){init_logger(),init_types(),globalLoggerManager=class e{static instance;globalConfig;loggers;constructor(){this.globalConfig={level:"error",enableCaller:!0,jsonFormat:!0},this.loggers=new Map}static getInstance(){return e.instance||(e.instance=new e),e.instance}setGlobalConfig(e){this.globalConfig={...this.globalConfig,...e},this.loggers.clear()}getGlobalConfig(){return{...this.globalConfig}}getLogger(e,t){const n=e+(t?JSON.stringify(t):"");if(!this.loggers.has(n)){const i=(r=this.globalConfig,new Logger(r)),s={domain:e,...t},a=i.with(s);this.loggers.set(n,a)}var r;return this.loggers.get(n)}getComponentLogger(e,t,n){const r={component:t,...n};return this.getLogger(e,r)}clearCache(){this.loggers.clear()}getCachedDomains(){return Array.from(this.loggers.keys())}setLogLevel(e){this.setGlobalConfig({level:e})}setCallerEnabled(e){this.setGlobalConfig({enableCaller:e})}setJsonFormat(e){this.setGlobalConfig({jsonFormat:e})}}.getInstance()}}),init_log=__esm({"pkg/log/index.ts"(){init_types(),init_logger(),init_http(),init_manager(),init_logger(),init_types(),function(e="info"){new Logger({level:e})}("info")}});function newHttpClient(e,t,n,r){return r||new NodeHttpClient(e,t,n)}var import_jszip,path6,log2,JsZipExtractor,WebZipExtractor,init_httpclient=__esm({"internal/domain/module/vo/httpclient.ts"(){init_type2(),path5=__toESM(require("path")),http=__toESM(require("http")),https=__toESM(require("https")),init_log(),log=getDomainLogger("module",{component:"httpclient"}),NodeHttpClient=class{constructor(e,t=3e4,n={}){this.fs=e,this.timeout=t,this.headers=n}defaultTimeout=3e4;defaultHeaders={"User-Agent":"MDFriday-CLI/1.0.0"};async download(e,t,n){return new Promise((r,i)=>{try{const s=new URL(e),a="https:"===s.protocol,o=a?https:http,l={...this.defaultHeaders,...this.headers,...n?.headers},c={hostname:s.hostname,port:s.port||(a?443:80),path:s.pathname+s.search,method:"GET",headers:l,timeout:n?.timeout||this.timeout},u=o.request(c,async e=>{if(!e.statusCode||e.statusCode<200||e.statusCode>=300)return void i(new ModuleError(`HTTP ${e.statusCode}: ${e.statusMessage}`,"HTTP_ERROR"));const s=parseInt(e.headers["content-length"]||"0",10);let a=0,o=Date.now(),l=-1;try{const c=path5.dirname(t);await this.fs.mkdirAll(c,493);const u=await this.fs.create(t),h=[];e.on("data",e=>{if(h.push(e),a+=e.length,n?.onProgress&&s>0){const e=Date.now(),t=Math.round(a/s*100);if(e-o>=100&&t!==l||t-l>=5){const r={loaded:a,total:s,percentage:t};try{n.onProgress(r),l=t}catch(e){log.error(`Progress callback error: ${e}`)}o=e}}}),e.on("end",async()=>{try{const e=Buffer.concat(h),t=new Uint8Array(e);if(await u.write(t),await u.sync(),await u.close(),n?.onProgress&&s>0){const e={loaded:s,total:s,percentage:100};try{n.onProgress(e)}catch(e){log.warn(`Progress callback error: ${e}`)}}r()}catch(e){const t=e instanceof Error?e.message:String(e);i(new ModuleError(`File write failed: ${t}`,"WRITE_FAILED"))}}),e.on("error",e=>{log.error(`Response error: ${e.message}`),i(new ModuleError(`Download failed: ${e.message}`,"DOWNLOAD_FAILED"))})}catch(e){const t=e instanceof Error?e.message:String(e);i(new ModuleError(`File system error: ${t}`,"FS_ERROR"))}});u.on("error",e=>{log.error("Request error:",e),i(new ModuleError(`Request failed: ${e.message}`,"REQUEST_FAILED"))}),u.on("timeout",()=>{u.destroy(),log.error(`Request timeout for ${e}`),i(new ModuleError("Request timeout","TIMEOUT"))}),u.end()}catch(e){const t=e instanceof Error?e.message:String(e);i(new ModuleError(`Download failed: ${t}`,"DOWNLOAD_FAILED"))}})}async get(e,t){return new Promise((n,r)=>{try{const i=new URL(e),s="https:"===i.protocol,a=s?https:http,o={...this.defaultHeaders,...this.headers,...t?.headers},l={hostname:i.hostname,port:i.port||(s?443:80),path:i.pathname+i.search,method:"GET",headers:o,timeout:t?.timeout||this.timeout},c=a.request(l,e=>{const t=[],i={};Object.entries(e.headers).forEach(([e,t])=>{i[e]=Array.isArray(t)?t.join(", "):t||""}),e.on("data",e=>{t.push(e)}),e.on("end",()=>{const r=Buffer.concat(t),s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);n({data:s,headers:i,status:e.statusCode||0})}),e.on("error",e=>{r(new ModuleError(`Response error: ${e.message}`,"RESPONSE_ERROR"))})});c.on("error",e=>{r(new ModuleError(`GET request failed: ${e.message}`,"REQUEST_FAILED"))}),c.on("timeout",()=>{c.destroy(),r(new ModuleError("GET request timeout","TIMEOUT"))}),c.end()}catch(e){const t=e instanceof Error?e.message:String(e);r(new ModuleError(`GET request failed: ${t}`,"REQUEST_FAILED"))}})}}}});function newZipExtractor(e,t="node"){switch(t){case"node":return new JsZipExtractor(e);case"browser":return new WebZipExtractor(e);default:throw new Error(`Unsupported environment: ${t}`)}}var path7,log3,FsModuleCache,init_zipextractor=__esm({"internal/domain/module/vo/zipextractor.ts"(){init_type2(),init_log(),import_jszip=__toESM(require("jszip")),path6=__toESM(require("path")),log2=getDomainLogger("module",{component:"zipextractor"}),JsZipExtractor=class{constructor(e){this.fs=e}async extract(e,t){try{const n=await this.fs.open(e),r=(await n.stat()).size(),i=new Uint8Array(r),s=await n.read(i);await n.close(),await this.extractZipData(s.buffer,t)}catch(t){const n=t instanceof Error?t.message:String(t);throw log2.error(`ZIP extraction failed for ${e}: ${n}`),new ModuleError(`ZIP extraction failed: ${n}`,"EXTRACTION_FAILED")}}async list(e){try{const t=await this.fs.open(e),n=await t.stat(),r=new Uint8Array(n.size()),i=await t.read(r);return await t.close(),await this.listZipContents(i.buffer)}catch(e){const t=e instanceof Error?e.message:String(e);throw new ModuleError(`ZIP listing failed: ${t}`,"LIST_FAILED")}}async extractZipData(e,t){try{await this.fs.mkdirAll(t,493);const n=new import_jszip.default,r=await n.loadAsync(e),i=[];r.forEach((e,t)=>{t.dir||i.push(e)});const s=[];let a=0;r.forEach((e,n)=>{s.push(this.extractSingleEntry(e,n,t).then(()=>{a++}))}),await Promise.all(s)}catch(e){const t=e instanceof Error?e.message:String(e);throw log2.error(`Failed to extract ZIP data: ${t}`),new ModuleError(`Failed to extract ZIP data: ${t}`,"EXTRACTION_FAILED")}}async extractSingleEntry(e,t,n){const r=path6.join(n,e);if(t.dir)await this.fs.mkdirAll(r,493);else{const e=path6.dirname(r);e!==n&&await this.fs.mkdirAll(e,493);const i=await t.async("uint8array"),s=await this.fs.create(r);await s.write(i),await s.close()}}async listZipContents(e){try{const t=new import_jszip.default,n=await t.loadAsync(e),r=[];return n.forEach(e=>{r.push(e)}),r}catch(e){const t=e instanceof Error?e.message:String(e);throw new ModuleError(`Failed to list ZIP contents: ${t}`,"LIST_FAILED")}}},WebZipExtractor=class{constructor(e){this.fs=e}async extract(e,t){try{throw new ModuleError("Web ZIP extraction not implemented","NOT_IMPLEMENTED")}catch(e){const t=e instanceof Error?e.message:String(e);throw new ModuleError(`Web ZIP extraction failed: ${t}`,"WEB_EXTRACTION_FAILED")}}async list(e){try{throw new ModuleError("Web ZIP listing not implemented","NOT_IMPLEMENTED")}catch(e){const t=e instanceof Error?e.message:String(e);throw new ModuleError(`Web ZIP listing failed: ${t}`,"WEB_LIST_FAILED")}}}}});function newModuleCache(e,t){return new FsModuleCache(e,t)}var path8,Module2,ProjectModule,init_cache=__esm({"internal/domain/module/vo/cache.ts"(){init_type2(),init_log(),path7=__toESM(require("path")),log3=getDomainLogger("module",{component:"cache"}),FsModuleCache=class{constructor(e,t="./module/cache"){this.fs=e,this.cacheDir=t}cacheDir;async get(e){try{const t=this.getCacheFilePath(e),n=await this.fs.open(t),r=await n.stat(),i=new Uint8Array(r.size());await n.read(i),await n.close();const s=(new TextDecoder).decode(i);return JSON.parse(s)}catch(t){if(t.message?.includes("ENOENT")||t.message?.includes("no such file"))return log3.error(`Cache miss: ${e}`,t),null;const n=t instanceof Error?t.message:String(t);throw log3.error(`Cache read error for ${e}: ${n}`),new ModuleError(`Failed to read cache: ${n}`,"CACHE_READ_FAILED")}}async set(e,t){try{await this.fs.mkdirAll(this.cacheDir,493);const n=this.getCacheFilePath(e),r=JSON.stringify(t,null,2),i=(new TextEncoder).encode(r),s=await this.fs.create(n);await s.write(i),await s.sync(),await s.close()}catch(t){const n=t instanceof Error?t.message:String(t);throw log3.error(`Cache write error for ${e}: ${n}`),new ModuleError(`Failed to write cache: ${n}`,"CACHE_WRITE_FAILED")}}async has(e){try{const t=this.getCacheFilePath(e);return await this.fs.stat(t),!0}catch(e){return!1}}async delete(e){try{const t=this.getCacheFilePath(e);await this.fs.remove(t)}catch(t){if(!t.message?.includes("ENOENT")&&!t.message?.includes("no such file")){const n=t instanceof Error?t.message:String(t);throw log3.error(`Cache delete error for ${e}: ${n}`),new ModuleError(`Failed to delete cache: ${n}`,"CACHE_DELETE_FAILED")}}}async clear(){try{await this.fs.removeAll(this.cacheDir)}catch(e){if(!e.message?.includes("ENOENT")&&!e.message?.includes("no such file")){const t=e instanceof Error?e.message:String(e);throw log3.error(`Cache clear error: ${t}`),new ModuleError(`Failed to clear cache: ${t}`,"CACHE_CLEAR_FAILED")}}}getCacheFilePath(e){const t=e.replace(/[/\\:*?"<>|]/g,"_").replace(/^_+|_+$/g,"")+".json";return path7.join(this.cacheDir,t)}getCacheDir(){return this.cacheDir}async getStats(){try{const e=await this.listCacheFiles();let t=0;for(const n of e)try{const e=path7.join(this.cacheDir,n);t+=(await this.fs.stat(e)).size()}catch(e){}return{totalEntries:e.length,totalSize:t}}catch(e){return{totalEntries:0,totalSize:0}}}async listCached(){try{return(await this.listCacheFiles()).map(e=>path7.basename(e,".json").replace(/_/g,"/"))}catch(e){return[]}}async listCacheFiles(){try{const e=await this.fs.open(this.cacheDir),t=await e.readdirnames(-1);return await e.close(),t.filter(e=>e.endsWith(".json"))}catch(e){return[]}}}}});function newModule2(e,t,n,r){return new Module2(e,t,n,r||null,!1)}var import_path2,Lang,Themes,import_smol_toml,path10,log4,Modules,init_module3=__esm({"internal/domain/module/vo/module.ts"(){init_type2(),init_mount(),path8=__toESM(require("path")),Module2=class e{constructor(e,t,n,r=null,i=!1){this.fs=e,this.absoluteDir=t,this.modulePath=n,this.parentModule=r,this.mountDirs=[],this.metadata=null,this.isProject=i}absoluteDir;modulePath;parentModule;mountDirs;metadata;isProject=!1;isProjectModule(){return this.isProject}owner(){return this.parentModule}mounts(){return this.mountDirs.map(e=>e)}dir(){return this.absoluteDir}path(){return this.modulePath}setMetadata(e){this.metadata=e}getMetadata(){return this.metadata}async applyMounts(e){try{let t=e.mounts||[];if(0===t.length)for(const e of ComponentFolders){const n=path8.join(this.absoluteDir,e);try{(await this.fs.stat(n)).isDir()&&t.push({sourcePath:e,targetPath:e})}catch(e){}}this.mountDirs=t.map(e=>{return t=e.sourcePath,n=e.targetPath,new Mount(t,n);var t,n})}catch(e){const t=e instanceof Error?e.message:String(e);throw new ModuleError(`Failed to apply mounts: ${t}`,"MOUNT_FAILED")}}appendMount(e){this.mountDirs.push(e)}removeMount(e){const t=this.mountDirs.findIndex(t=>t.equals(e));return t>=0&&(this.mountDirs.splice(t,1),!0)}getMountByTarget(e){return this.mountDirs.find(t=>t.target()===e)||null}getMountsByComponent(e){return this.mountDirs.filter(t=>t.component()===e)}isDownloaded(){return"completed"===this.metadata?.downloadStatus}isDownloading(){return"downloading"===this.metadata?.downloadStatus}isDownloadFailed(){return"failed"===this.metadata?.downloadStatus}async exists(){try{return(await this.fs.stat(this.absoluteDir)).isDir()}catch(e){return!1}}copy(){const t=new e(this.fs,this.absoluteDir,this.modulePath,this.parentModule,this.isProject);return t.mountDirs=this.mountDirs.map(e=>e.copy()),t.metadata=this.metadata?{...this.metadata}:null,t}toString(){return`Module{path: ${this.modulePath}, dir: ${this.absoluteDir}, mounts: ${this.mountDirs.length}}`}},ProjectModule=class{constructor(e){this.module=e}getModule(){return this.module}appendMount(e){this.module.appendMount(e)}setDefaultLanguage(e){const t=this.module.mounts();for(const n of t)n instanceof Mount&&n.setLanguage(e)}applyDefaultMounts(){const e=ComponentFolders.map(e=>new Mount(e,e));for(const t of e)this.module.appendMount(t)}owner(){return this.module.owner()}mounts(){return this.module.mounts()}dir(){return this.module.dir()}path(){return this.module.path()}}}}),init_lang2=__esm({"internal/domain/module/entity/lang.ts"(){import_path2=__toESM(require("path")),Lang=class{sourceLangMap;constructor(e){this.sourceLangMap=new Map;for(const t of e)for(const e of t.mounts())this.sourceLangMap.set(e.source(),e.lang())}getSourceLang(e){const t=this.sourceLangMap.get(import_path2.default.basename(e));return void 0!==t?[t,!0]:["",!1]}}}}),init_themes=__esm({"internal/domain/module/vo/themes.ts"(){Themes=class e{themes;constructor(e){this.themes=e}static fromJson(t){return new e(t)}findThemeByUrl(e){const t=this.extractBaseUrl(e);for(const e of this.themes)if(t===this.extractBaseUrl(e.download_url))return e;return null}resolveLatestVersion(e){const t=this.findThemeByUrl(e);return t?t.download_url:e}extractBaseUrl(e){try{const t=new URL(e);return t.searchParams.delete("version"),t.toString()}catch(t){const n=e.indexOf("?");if(-1===n)return e;const r=e.substring(0,n),i=new URLSearchParams(e.substring(n+1));i.delete("version");const s=i.toString();return s?`${r}?${s}`:r}}getAllThemes(){return[...this.themes]}getThemeByName(e){return this.themes.find(t=>t.name.toLowerCase()===e.toLowerCase())||null}getThemesByTag(e){return this.themes.filter(t=>t.tags.some(t=>t.toLowerCase()===e.toLowerCase()))}}}});function newModules(e,t,n,r){return new Modules(e,t,n,r)}var log5,FsError,ErrFileClosed,ErrFileNotFound,ErrSkipDir,OverlayFsError,ErrNoFilesystems,OriginFs,FileMeta,init_module4=__esm({"internal/domain/module/entity/module.ts"(){init_type2(),init_module3(),init_lang2(),init_themes(),init_log(),import_smol_toml=require("smol-toml"),path10=__toESM(require("path")),log4=getDomainLogger("module",{component:"modules"}),Modules=class{constructor(e,t,n,r){var i;this.info=e,this.httpClient=t,this.zipExtractor=n,this.moduleCache=r,this.projectModule=function(e){const t=e.osFs(),n=e.projDir(),r=e.defaultLanguageKey(),i=new Module2(t,n,"project-root",null,!0),s=new ProjectModule(i);s.applyDefaultMounts(),r&&s.setDefaultLanguage(r);const a=e.otherLanguageKeys();for(const t of a)try{const n=e.getRelDir(ComponentFolderContent,t);if(n&&""!==n){const e=new Mount(n,ComponentFolderContent,t);s.appendMount(e)}}catch(e){console.warn(`Failed to get relative directory for language ${t}:`,e)}return s}(this.info),this.lang=(i=this.all(),new Lang(i))}projectModule;modules=[];downloadedModules=new Set;lang;themesCache=new Map;proj(){return this.projectModule.getModule()}all(){const e=[this.projectModule.getModule()];return e.push(...this.modules),e}isProjMod(e){return e===this.projectModule.getModule()}async load(e){const t=this.info.importPaths();if(0!==t.length)for(let n=0;n<t.length;n++){const r=t[n],{cleanUrl:i,version:s}=this.parseVersionFromImportPath(r);let a=r;"latest"===s&&(a=await this.resolveLatestVersion(r)),this.downloadedModules.has(a)?log4.info(`Module already downloaded: ${a}`):await this.addModule(this.projectModule.getModule(),a,t=>{e?.({modulePath:a,downloadPercentage:t.percentage})})}else log4.warn("No import paths configured - no modules will be downloaded")}parseVersionFromImportPath(e){try{const t=new URL(e),n=t.searchParams.get("version")||"latest";return t.searchParams.delete("version"),{cleanUrl:t.toString(),version:n}}catch(t){return log4.warn(`Failed to parse import path ${e}:`,t),{cleanUrl:e,version:"latest"}}}getThemeRegistryUrl(e){try{const t=new URL(e).hostname;return"sunwei.xyz"===t||"www.sunwei.xyz"===t?"https://sunwei.xyz/mdf/themes-zh.json":"https://gohugo.net/themes.json"}catch(t){return log4.warn(`Failed to parse import path ${e}, using default theme registry`),"https://gohugo.net/themes.json"}}async resolveLatestVersion(e){const{version:t}=this.parseVersionFromImportPath(e);if("latest"!==t)return e;try{const t=this.getThemeRegistryUrl(e);log4.info(`Fetching latest theme versions from ${t}...`);let n=this.themesCache.get(t);if(!n){const e=await this.httpClient.get(t),r=(new TextDecoder).decode(e.data),i=JSON.parse(r);n=Themes.fromJson(i),this.themesCache.set(t,n)}const r=n.resolveLatestVersion(e);return r!==e?log4.info(`Resolved latest version: ${e} -> ${r}`):log4.warn(`Could not resolve latest version for ${e}, using original path`),r}catch(t){return log4.error(`Failed to resolve latest version for ${e}:`,t),e}}async downloadModule(e,t){try{let n=e.version;if("latest"===e.version){const t=await this.resolveLatestVersion(e.path),{version:r}=this.parseVersionFromImportPath(t);n=r}const r=await this.moduleCache.get(e.path);if(r&&"completed"===r.downloadStatus&&this.isCacheValidForVersion(r.version,n)){const t=await this.createModuleFromCache(e,r);if(await t.exists())return log4.info(`Using cached module ${e.path} version ${r.version}`),t}r&&"completed"===r.downloadStatus&&!this.isCacheValidForVersion(r.version,n)&&log4.info(`Cache version mismatch for ${e.path}: cached=${r.version}, requested=${n||"latest"}`);const i=this.getModuleDir(e.path),s=path10.join(i,"module.zip"),a={path:e.path,version:e.version||"latest",url:e.url,dir:i,downloadStatus:"downloading",downloadedAt:new Date};await this.moduleCache.set(e.path,a);try{const n=this.addTimestampToUrl(e.url);await this.httpClient.download(n,s,{onProgress:e=>{t?.({percentage:e.percentage})}}),await this.zipExtractor.extract(s,i),a.downloadStatus="completed",a.downloadedAt=new Date;try{const e=await this.info.osFs().stat(s);a.size=e.size()}catch(e){}try{await this.info.osFs().remove(s)}catch(e){}await this.moduleCache.set(e.path,a);const r=newModule2(this.info.osFs(),i,e.path);return r.setMetadata(a),await r.applyMounts(e),r}catch(t){a.downloadStatus="failed",await this.moduleCache.set(e.path,a);const n=t instanceof Error?t.message:String(t);throw new ModuleError(`Failed to download module ${e.path}: ${n}`,"DOWNLOAD_FAILED")}}catch(e){if(e instanceof ModuleError)throw e;const t=e instanceof Error?e.message:String(e);throw new ModuleError(`Module download failed: ${t}`,"DOWNLOAD_FAILED")}}async addModule(e,t,n){try{if(this.downloadedModules.has(t))return;const{cleanUrl:e,version:r}=this.parseVersionFromImportPath(t),i={path:t,url:this.getDownloadUrl(e),...r&&{version:r}},s=await this.downloadModule(i,n);this.modules.push(s),this.downloadedModules.add(t);try{const e=await this.parseThemeToml(s);for(const t of e){if(this.downloadedModules.has(t)